<?php


// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Check if WooCommerce is active
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    add_action('admin_notices', function() {
        echo '<div class="notice notice-error"><p>' . __('Product Compare Kav requires WooCommerce to be installed and active.', 'kavehTheme') . '</p></div>';
    });
    return;
}

// Define plugin constants
define('PRODUCT_COMPARE_KAV_VERSION', '1.0.0');

// Main plugin class
class ProductCompareKav {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->init_hooks();
    }
    
    private function init_hooks() {
        // Include admin functionality first
        require_once PRODUCT_COMPARE_KAV_PLUGIN_DIR . 'admin/admin.php';
        
        // Initialize admin only in admin area
        if (is_admin()) {
            ProductCompareKavAdmin::get_instance();
        }
        
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_ajax_add_to_compare', array($this, 'ajax_add_to_compare'));
        add_action('wp_ajax_nopriv_add_to_compare', array($this, 'ajax_add_to_compare'));
        add_action('wp_ajax_remove_from_compare', array($this, 'ajax_remove_from_compare'));
        add_action('wp_ajax_nopriv_remove_from_compare', array($this, 'ajax_remove_from_compare'));
        add_action('wp_ajax_get_compare_products', array($this, 'ajax_get_compare_products'));
        add_action('wp_ajax_nopriv_get_compare_products', array($this, 'ajax_get_compare_products'));
        add_action('wp_ajax_search_products', array($this, 'ajax_search_products'));
        add_action('wp_ajax_nopriv_search_products', array($this, 'ajax_search_products'));
        
        // Auto-create compare page on every load
        add_action('wp_loaded', array($this, 'ensure_compare_page_exists'));
        
        // Add page label in admin
        add_filter('display_post_states', array($this, 'add_compare_page_label'), 10, 2);
        
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
        
        // Add compare button to product loops based on position setting and display mode
        if (class_exists('ProductCompareKavAdmin')) {
            $display_mode = ProductCompareKavAdmin::get_option('button_display_mode', 'automatic');
            if ($display_mode === 'automatic' && ProductCompareKavAdmin::get_option('show_on_shop', true)) {
                $this->add_shop_loop_hooks();
            }
            
            if ($display_mode === 'automatic' && ProductCompareKavAdmin::get_option('show_on_single', true)) {
                add_action('woocommerce_single_product_summary', array($this, 'add_compare_button'), 25);
            }
        }
        
        add_shortcode('product_compare_kav', array($this, 'compare_shortcode'));
        add_shortcode('compare_button', array($this, 'shortcode_compare_button'));
        
        // Add menu item
        add_action('wp_footer', array($this, 'add_compare_modal'));
    }
    
    
    
    public function enqueue_scripts() {
        wp_enqueue_style('product-compare-kav-style', PRODUCT_COMPARE_KAV_PLUGIN_URL . 'assets/css/main.min.css', array(), PRODUCT_COMPARE_KAV_VERSION);
        
        // Add custom button styling
        $this->add_custom_button_styles();
        
        wp_enqueue_script('product-compare-kav-script', PRODUCT_COMPARE_KAV_PLUGIN_URL . 'assets/js/compare.js', array('jquery'), PRODUCT_COMPARE_KAV_VERSION, true);
        
        $compare_page_id = $this->get_compare_page_id();
        $compare_page_url = $compare_page_id ? get_permalink($compare_page_id) : '';
        
        wp_localize_script('product-compare-kav-script', 'compareKav', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('compare_kav_nonce'),
            'compare_page_url' => $compare_page_url,
            'max_products' => $this->get_max_products(),
            'messages' => array(
                'added' => __('Product added to compare', 'kavehTheme'),
                'removed' => __('Product removed from compare', 'kavehTheme'),
                /* translators: %d: maximum number of products that can be compared */
                'max_reached' => sprintf(__('Maximum %d products can be compared', 'kavehTheme'), $this->get_max_products()),
                'error' => __('An error occurred', 'kavehTheme')
            ),
            'texts' => array(
                'add_to_compare' => __('Add to compare', 'kavehTheme'),
                'remove_from_compare' => __('Remove from compare', 'kavehTheme'),
                'added_to_compare' => __('Added to compare', 'kavehTheme'),
                'error' => __('An error occurred', 'kavehTheme'),
                'adding_to_compare' => __('Adding to compare...', 'kavehTheme'),
                'search_placeholder' => __('Search products...', 'kavehTheme'),
                'searching' => __('Searching...', 'kavehTheme'),
                'search_error' => __('Search error', 'kavehTheme'),
                'connection_error' => __('Connection error', 'kavehTheme'),
                'no_products_found' => __('No products found', 'kavehTheme'),
                'no_image' => __('No Image', 'kavehTheme'),
                'select_product' => __('Select Product', 'kavehTheme'),
                'product' => __('Product', 'kavehTheme'),
                'view_and_buy' => __('View and Buy', 'kavehTheme')
            )
        ));
    }
    
    public function add_custom_button_styles() {
        $bg_color = ProductCompareKavAdmin::get_option('button_background_color', '#007cba');
        $text_color = ProductCompareKavAdmin::get_option('button_text_color', '#ffffff');
        $border_radius = ProductCompareKavAdmin::get_option('button_border_radius', '4');
        $padding = ProductCompareKavAdmin::get_option('button_padding', '8');
        
        $custom_css = "
        .compare-button-wrapper .compare-button {
            background-color: {$bg_color}. '!important;';
            color: {$text_color}. '!important;';
            border-radius: {$border_radius}px !important;
            border: none !important;
            cursor: pointer !important;
            display: inline-flex !important;
            align-items: center !important;
            gap: 5px !important;
            font-size: 12px !important;
            padding: 6px 10px;
            text-decoration: none !important;
            transition: all 0.3s ease !important;
        }
        
        .compare-button-wrapper .compare-button:hover {
            opacity: 0.8 !important;
            transform: translateY(-1px) !important;
        }
        
        .compare-button-wrapper .compare-button svg {
            width: 16px !important;
            height: 16px !important;
            fill: {$text_color} !important;
        }
        
        .compare-button-wrapper .compare-button.remove-from-compare {
            background-color: #dc3545 !important;
        }
        
        .compare-button-wrapper {
            margin: 5px 0 !important;
        }
        ";
        
        wp_add_inline_style('product-compare-kav-style', $custom_css);
    }
    
    public function add_shop_loop_hooks() {
        $position = ProductCompareKavAdmin::get_option('button_position', 'after_add_to_cart');
        
        switch ($position) {
            case 'before_title':
                add_action('woocommerce_shop_loop_item_title', array($this, 'add_compare_button'), 5);
                break;
            case 'after_title':
                add_action('woocommerce_shop_loop_item_title', array($this, 'add_compare_button'), 15);
                break;
            case 'before_price':
                add_action('woocommerce_after_shop_loop_item_title', array($this, 'add_compare_button'), 5);
                break;
            case 'after_price':
                add_action('woocommerce_after_shop_loop_item_title', array($this, 'add_compare_button'), 15);
                break;
            case 'before_add_to_cart':
                add_action('woocommerce_after_shop_loop_item', array($this, 'add_compare_button'), 5);
                break;
            case 'after_add_to_cart':
            default:
                add_action('woocommerce_after_shop_loop_item', array($this, 'add_compare_button'), 15);
                break;
        }
    }
    
    public function add_compare_button($product_id = null) {
        global $product;
        
        if (!$product_id && $product) {
            $product_id = $product->get_id();
        }
        
        if (!$product_id) {
            return;
        }
        
        $compare_list = $this->get_compare_list();
        $is_in_compare = in_array($product_id, $compare_list);
        
        $button_style = ProductCompareKavAdmin::get_option('button_style', 'icon_text');
        $add_text = ProductCompareKavAdmin::get_option('button_text_add', __('Add to compare', 'kavehTheme'));
        $remove_text = ProductCompareKavAdmin::get_option('button_text_remove', __('Remove from compare', 'kavehTheme'));
        
        $button_class = $is_in_compare ? 'remove-from-compare' : 'add-to-compare';
        $button_text = $is_in_compare ? $remove_text : $add_text;
        
        echo '<div class="compare-button-wrapper">';
        echo '<button class="compare-button ' . $button_class . '" data-product-id="' . $product_id . '">';
        
        // Show icon based on style setting
        if ($button_style === 'icon_text' || $button_style === 'icon_only') {
            echo '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">';
            echo '<g clip-path="url(#clip0_105_1836)">';
            echo '<path d="M13 3.99976H6C4.89543 3.99976 4 4.89519 4 5.99976V17.9998C4 19.1043 4.89543 19.9998 6 19.9998H13M17 3.99976H18C19.1046 3.99976 20 4.89519 20 5.99976V6.99976M20 16.9998V17.9998C20 19.1043 19.1046 19.9998 18 19.9998H17M20 10.9998V12.9998M12 1.99976V21.9998" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/>';
            echo '</g>';
            echo '<defs>';
            echo '<clipPath id="clip0_105_1836">';
            echo '<rect fill="white" height="24" transform="translate(0 -0.000244141)" width="24"/>';
            echo '</clipPath>';
            echo '</defs>';
            echo '</svg>';
        }
        
        // Show text based on style setting
        if ($button_style === 'icon_text' || $button_style === 'text_only') {
            echo '<span>' . $button_text . '</span>';
        }
        
        echo '</button>';
        echo '</div>';
    }
    
    public function ajax_add_to_compare() {
        check_ajax_referer('compare_kav_nonce', 'nonce');
        
        $product_id = intval($_POST['product_id']);
        
        if (!$product_id) {
            wp_die();
        }
        
        $compare_list = $this->get_compare_list();
        $max_products = $this->get_max_products();
        
        if (count($compare_list) >= $max_products) {
            wp_send_json_error(array('message' => sprintf(__('Maximum %d products can be compared', 'kavehTheme'), $max_products)));
        }
        
        if (!in_array($product_id, $compare_list)) {
            $compare_list[] = $product_id;
            $this->set_compare_list($compare_list);
        }
        
        wp_send_json_success(array(
            'message' => __('Product added to compare', 'kavehTheme'),
            'count' => count($compare_list)
        ));
    }
    
    public function ajax_remove_from_compare() {
        check_ajax_referer('compare_kav_nonce', 'nonce');
        
        $product_id = intval($_POST['product_id']);
        
        if (!$product_id) {
            wp_die();
        }
        
        $compare_list = $this->get_compare_list();
        $key = array_search($product_id, $compare_list);
        
        if ($key !== false) {
            unset($compare_list[$key]);
            $compare_list = array_values($compare_list);
            $this->set_compare_list($compare_list);
        }
        
        wp_send_json_success(array(
            'message' => __('Product removed from compare', 'kavehTheme'),
            'count' => count($compare_list)
        ));
    }
    
    public function ajax_get_compare_products() {
        check_ajax_referer('compare_kav_nonce', 'nonce');
        
        $compare_list = $this->get_compare_list();
        $products_data = array();
        
        foreach ($compare_list as $product_id) {
            $product = wc_get_product($product_id);
            if ($product) {
                $products_data[] = $this->get_product_data($product);
            }
        }
        
        wp_send_json_success($products_data);
    }
    
    public function ajax_search_products() {
        check_ajax_referer('compare_kav_nonce', 'nonce');
        
        $search_term = sanitize_text_field($_POST['search_term']);
        
        $args = array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => 20,
            's' => $search_term,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_visibility',
                    'field'    => 'name',
                    'terms'    => array('exclude-from-catalog', 'exclude-from-search'),
                    'operator' => 'NOT IN',
                )
            )
        );
        
        $products = get_posts($args);
        $products_data = array();
        
        foreach ($products as $post) {
            $product = wc_get_product($post->ID);
            if ($product) {
                $products_data[] = array(
                    'id' => $product->get_id(),
                    'title' => $product->get_name(),
                    'image' => wp_get_attachment_image_url($product->get_image_id(), 'medium'),
                    'price' => $product->get_price_html(),
                    'url' => $product->get_permalink()
                );
            }
        }
        
        wp_send_json_success($products_data);
    }
    
    private function get_product_data($product) {
        $attributes = array();
        
        // Get product attributes
        $product_attributes = $product->get_attributes();
        foreach ($product_attributes as $attribute) {
            if ($attribute->get_variation()) {
                continue;
            }
            
            $attribute_name = wc_attribute_label($attribute->get_name());
            $attribute_values = array();
            
            if ($attribute->is_taxonomy()) {
                $terms = wp_get_post_terms($product->get_id(), $attribute->get_name());
                foreach ($terms as $term) {
                    $attribute_values[] = $term->name;
                }
            } else {
                $attribute_values = $attribute->get_options();
            }
            
            $attributes[$attribute_name] = implode(', ', $attribute_values);
        }
        
        // Add default attributes based on settings
        $selected_attributes = $this->get_option('compare_attributes', array('weight', 'dimensions', 'sku'));
        
        if (in_array('weight', $selected_attributes)) {
            $attributes[__('Weight', 'kavehTheme')] = $product->get_weight() ? $product->get_weight() . ' ' . get_option('woocommerce_weight_unit') : '-';
        }
        
        if (in_array('dimensions', $selected_attributes)) {
            $attributes[__('Dimensions', 'kavehTheme')] = $product->get_dimensions(false) ?: '-';
        }
        
        if (in_array('sku', $selected_attributes)) {
            $attributes[__('SKU', 'kavehTheme')] = $product->get_sku() ?: '-';
        }
        
        // Get image with fallback
        $image_url = wp_get_attachment_image_url($product->get_image_id(), 'medium');
        if (!$image_url) {
            $image_url = wc_placeholder_img_src('medium');
        }
        
        return array(
            'id' => $product->get_id(),
            'title' => $product->get_name(),
            'image' => $image_url,
            'price' => $product->get_price_html(),
            'regular_price' => $product->get_regular_price() ? wc_price($product->get_regular_price()) : '',
            'sale_price' => $product->get_sale_price() ? wc_price($product->get_sale_price()) : '',
            'rating' => $product->get_average_rating(),
            'url' => $product->get_permalink(),
            'attributes' => $attributes
        );
    }
    
    private function get_compare_list() {
        if (isset($_COOKIE['compare_kav_products'])) {
            return json_decode(stripslashes($_COOKIE['compare_kav_products']), true) ?: array();
        }
        return array();
    }
    
    private function set_compare_list($products) {
        setcookie('compare_kav_products', json_encode($products), time() + (86400 * 30), '/');
    }
    
    public function shortcode_compare_button($atts) {
        $atts = shortcode_atts(array(
            'id' => get_the_ID(),
            'product_id' => '',
            'style' => '',
            'text_add' => '',
            'text_remove' => '',
            'class' => '',
            'color' => '',
            'background_color' => '',
            'radius' => '',
            'tag' => 'button'
        ), $atts);
        
        // Support both 'id' and 'product_id' for backward compatibility
        $product_id = !empty($atts['product_id']) ? intval($atts['product_id']) : intval($atts['id']);
        
        if (!$product_id) {
            return '';
        }
        
        $product = wc_get_product($product_id);
        if (!$product) {
            return '';
        }
        
        
        $compare_list = $this->get_compare_list();
        $is_in_compare = in_array($product_id, $compare_list);
        
        // Use shortcode attributes or fall back to admin settings (shortcode has higher priority)
        $button_style = !empty($atts['style']) ? $atts['style'] : ProductCompareKavAdmin::get_option('button_style', 'icon_text');
        $add_text = !empty($atts['text_add']) ? $atts['text_add'] : ProductCompareKavAdmin::get_option('button_text_add', __('Add to compare', 'kavehTheme'));
        $remove_text = !empty($atts['text_remove']) ? $atts['text_remove'] : ProductCompareKavAdmin::get_option('button_text_remove', __('Remove from compare', 'kavehTheme'));
        
        // Styling options with shortcode priority
        $bg_color = !empty($atts['background_color']) ? $atts['background_color'] : ProductCompareKavAdmin::get_option('button_background_color', '#007cba');
        $text_color = !empty($atts['color']) ? $atts['color'] : ProductCompareKavAdmin::get_option('button_text_color', '#ffffff');
        $border_radius = !empty($atts['radius']) ? $atts['radius'] : ProductCompareKavAdmin::get_option('button_border_radius', '4');
        $html_tag = in_array($atts['tag'], array('button', 'a', 'div', 'span')) ? $atts['tag'] : 'button';
        

        
        $button_class = $is_in_compare ? 'remove-from-compare' : 'add-to-compare';
        $button_text = $is_in_compare ? $remove_text : $add_text;
        $extra_class = !empty($atts['class']) ? ' ' . esc_attr($atts['class']) : '';
        
        // Generate unique ID for this button to apply custom styles
        $unique_id = 'compare-btn-' . $product_id . '-' . uniqid();
        
        ob_start();
        
        // Add inline styles for this specific button
        echo '<style>';
        echo '#' . $unique_id . ' {';
        echo 'background-color: ' . esc_attr($bg_color) . '!important;';
        echo 'color: ' . esc_attr($text_color) . ' !important;';
        echo 'border-radius: ' . esc_attr($border_radius) . 'px !important;';
        echo 'border: none !important;';
        echo 'cursor: pointer !important;';
        echo 'display: inline-flex !important;';
        echo 'align-items: center !important;';
        echo 'gap: 5px !important;';
        echo 'padding: 6px 10px;';
        echo 'font-size: 12px !important;';
        echo 'text-decoration: none !important;';
        echo 'transition: all 0.3s ease !important;';
        echo '}';
        echo '#' . $unique_id . ':hover {';
        echo 'opacity: 0.8 !important;';
        echo 'transform: translateY(-1px) !important;';
        echo '}';
        echo '#' . $unique_id . ' svg {';
        echo 'width: 16px !important;';
        echo 'height: 16px !important;';
        echo 'stroke: ' . esc_attr($text_color) . ' !important;';
        echo '}';
        echo '#' . $unique_id . '.remove-from-compare {';
        echo 'background-color: #dc3545 !important;';
        echo '}';
        echo '</style>';
        
        echo '<div class="compare-button-wrapper' . $extra_class . '">';
        echo '<' . $html_tag . ' id="' . $unique_id . '" class="compare-button ' . $button_class . '" data-product-id="' . $product_id . '">';
        
        // Show icon based on style setting
        if ($button_style === 'icon_text' || $button_style === 'icon_only') {
            echo '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">';
            echo '<g clip-path="url(#clip0_105_1836_' . $unique_id . ')">'; 
            echo '<path d="M13 3.99976H6C4.89543 3.99976 4 4.89519 4 5.99976V17.9998C4 19.1043 4.89543 19.9998 6 19.9998H13M17 3.99976H18C19.1046 3.99976 20 4.89519 20 5.99976V6.99976M20 16.9998V17.9998C20 19.1043 19.1046 19.9998 18 19.9998H17M20 10.9998V12.9998M12 1.99976V21.9998" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/>';
            echo '</g>';
            echo '<defs>';
            echo '<clipPath id="clip0_105_1836_' . $unique_id . '">';
            echo '<rect fill="white" height="24" transform="translate(0 -0.000244141)" width="24"/>';
            echo '</clipPath>';
            echo '</defs>';
            echo '</svg>';
        }
        
        // Show text based on style setting
        if ($button_style === 'icon_text' || $button_style === 'text_only') {
            echo '<span>' . $button_text . '</span>';
        }
        
        echo '</' . $html_tag . '>';
        echo '</div>';
        
        return ob_get_clean();
    }
    
    public function compare_shortcode($atts) {
        $atts = shortcode_atts(array(
            'class' => ''
        ), $atts);
        
        ob_start();
        $this->render_compare_table();
        return ob_get_clean();
    }
    
    public function render_compare_table() {
        $compare_list = $this->get_compare_list();
        include PRODUCT_COMPARE_KAV_PLUGIN_DIR . 'templates/compare-table.php';
    }
    
    public function add_compare_modal() {
        include PRODUCT_COMPARE_KAV_PLUGIN_DIR . 'templates/compare-modal.php';
    }
    
    private function get_max_products() {
        return $this->get_option('max_products', 4);
    }
    
    private function get_option($key, $default = null) {
        $options = get_option('product_compare_kav_options', array());
        return isset($options[$key]) ? $options[$key] : $default;
    }
    
    public function activate() {
        $this->create_compare_page();
    }
    
    public function deactivate() {
        // Clean up if needed
    }
    
    private function create_compare_page() {
         // Check if compare page already exists and is valid
         $existing_page_id = get_option('product_compare_kav_page_id');
         $existing_page = $existing_page_id ? get_post($existing_page_id) : null;
         
         // If page exists and is published, we're good
         if ($existing_page && $existing_page->post_status === 'publish' && $existing_page->post_type === 'page') {
             return $existing_page_id;
         }
         
         // Check if a page with the slug already exists
         $existing_by_slug = get_page_by_path('product-compare');
         if ($existing_by_slug) {
             // Update the option to point to this page
             update_option('product_compare_kav_page_id', $existing_by_slug->ID);
             
             // Update content if it doesn't contain the shortcode
             if (strpos($existing_by_slug->post_content, '[product_compare_kav]') === false) {
                 wp_update_post(array(
                     'ID' => $existing_by_slug->ID,
                     'post_content' => '[product_compare_kav]'
                 ));
             }
             
             return $existing_by_slug->ID;
         }
         
         // Create new compare page
         $page_data = array(
             'post_title' => __('Product Compare', 'kavehTheme'),
             'post_content' => '[product_compare_kav]',
             'post_status' => 'publish',
             'post_type' => 'page',
             'post_author' => 1,
             'post_slug' => 'product-compare'
         );
         
         $page_id = wp_insert_post($page_data);
         
         if ($page_id && !is_wp_error($page_id)) {
             update_option('product_compare_kav_page_id', $page_id);
             return $page_id;
         }
         
         return false;
     }
    
    private function get_compare_page_id() {
        return get_option('product_compare_kav_page_id');
    }
    
    public function ensure_compare_page_exists() {
        $this->create_compare_page();
    }
    
    public function add_compare_page_label($post_states, $post) {
        $compare_page_id = $this->get_compare_page_id();
        if ($compare_page_id && $post->ID == $compare_page_id) {
            $post_states['product_compare_kav_page'] = __('Product Compare Page', 'kavehTheme');
        }
        return $post_states;
    }
}

// Initialize the plugin
ProductCompareKav::get_instance();