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

define('WLM_VERSION', '1.0.0');
define('WLM_TEXT_DOMAIN', 'kavehTheme');

// Main plugin class
class WishlistManager {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('init', array($this, 'init'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        
        // AJAX handlers
        add_action('wp_ajax_wlm_toggle_wishlist', array($this, 'ajax_toggle_wishlist'));
        add_action('wp_ajax_nopriv_wlm_toggle_wishlist', array($this, 'ajax_toggle_wishlist'));
        add_action('wp_ajax_wlm_remove_from_wishlist', array($this, 'ajax_remove_from_wishlist'));
        add_action('wp_ajax_nopriv_wlm_remove_from_wishlist', array($this, 'ajax_remove_from_wishlist'));
        
        // Shortcodes
        add_shortcode('wlm_button', array($this, 'wishlist_button_shortcode'));
        add_shortcode('wlm_table', array($this, 'wishlist_table_shortcode'));
        

        // Ensure wishlist page exists
        add_action('wp_loaded', array($this, 'ensure_wishlist_page_exists'));
        
        // Add admin label for wishlist page
        add_filter('display_post_states', array($this, 'add_wishlist_page_label'), 10, 2);
        
        // Admin menu
        add_action('admin_menu', array($this, 'add_admin_menu'));

        // Plugin activation/deactivation
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
    }
    
    public function init() {
        // Load text domain
        load_plugin_textdomain(WLM_TEXT_DOMAIN, false, dirname(plugin_basename(__FILE__)) . '/languages');
        
        // Create database table if needed
        $this->create_wishlist_table();
    }
    
    public function enqueue_scripts() {
        wp_enqueue_script('wlm-frontend', WLM_PLUGIN_URL . 'assets/js/frontend.js', array('jquery'), WLM_VERSION, true);
        wp_enqueue_style('wlm-frontend', WLM_PLUGIN_URL . 'assets/css/frontend.css', array(), WLM_VERSION);
        
        // Localize script
        wp_localize_script('wlm-frontend', 'wlm_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('wlm_nonce'),
            'messages' => array(
                'added' => __('Added to wishlist', WLM_TEXT_DOMAIN),
                'removed' => __('Removed from wishlist', WLM_TEXT_DOMAIN),
                'error' => __('Something went wrong', WLM_TEXT_DOMAIN)
            )
        ));
    }
    

    public function create_wishlist_table() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'wlm_wishlist';
        
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) DEFAULT NULL,
            session_id varchar(255) DEFAULT NULL,
            product_id bigint(20) NOT NULL,
            date_added datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY user_id (user_id),
            KEY session_id (session_id),
            KEY product_id (product_id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    public function ajax_toggle_wishlist() {
        check_ajax_referer('wlm_nonce', 'nonce');
        
        $product_id = intval($_POST['product_id']);
        $user_id = get_current_user_id();
        $session_id = $this->get_session_id();
        
        if (!$product_id) {
            wp_die(__('Invalid product ID', WLM_TEXT_DOMAIN));
        }
        
        $is_in_wishlist = $this->is_product_in_wishlist($product_id, $user_id, $session_id);
        
        if ($is_in_wishlist) {
            $this->remove_from_wishlist($product_id, $user_id, $session_id);
            wp_send_json_success(array('action' => 'removed', 'in_wishlist' => false));
        } else {
            $this->add_to_wishlist($product_id, $user_id, $session_id);
            wp_send_json_success(array('action' => 'added', 'in_wishlist' => true));
        }
    }
    
    public function ajax_remove_from_wishlist() {
        check_ajax_referer('wlm_nonce', 'nonce');
        
        $product_id = intval($_POST['product_id']);
        $user_id = get_current_user_id();
        $session_id = $this->get_session_id();
        
        if (!$product_id) {
            wp_die(__('Invalid product ID', WLM_TEXT_DOMAIN));
        }
        
        $this->remove_from_wishlist($product_id, $user_id, $session_id);
        wp_send_json_success(array('action' => 'removed'));
    }
    
    private function get_session_id() {
        if (session_status() === PHP_SESSION_NONE) {
            if (headers_sent()) {
                return null;
            }
            session_start();
        }
        return session_id();
    }
    
    public function is_product_in_wishlist($product_id, $user_id = null, $session_id = null) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'wlm_wishlist';
        
        if ($user_id) {
            $result = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $table_name WHERE product_id = %d AND user_id = %d",
                $product_id, $user_id
            ));
        } else {
            $result = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $table_name WHERE product_id = %d AND session_id = %s",
                $product_id, $session_id
            ));
        }
        
        return $result > 0;
    }
    
    public function add_to_wishlist($product_id, $user_id = null, $session_id = null) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'wlm_wishlist';
        
        // Check if already exists
        if ($this->is_product_in_wishlist($product_id, $user_id, $session_id)) {
            return false;
        }
        
        $data = array(
            'product_id' => $product_id,
            'date_added' => current_time('mysql')
        );
        
        if ($user_id) {
            $data['user_id'] = $user_id;
        } else {
            $data['session_id'] = $session_id;
        }
        
        return $wpdb->insert($table_name, $data);
    }
    
    public function remove_from_wishlist($product_id, $user_id = null, $session_id = null) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'wlm_wishlist';
        
        if ($user_id) {
            return $wpdb->delete($table_name, array(
                'product_id' => $product_id,
                'user_id' => $user_id
            ));
        } else {
            return $wpdb->delete($table_name, array(
                'product_id' => $product_id,
                'session_id' => $session_id
            ));
        }
    }
    
    public function get_wishlist_items($user_id = null, $session_id = null) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'wlm_wishlist';
        
        if ($user_id) {
            $results = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM $table_name WHERE user_id = %d ORDER BY date_added DESC",
                $user_id
            ));
        } else {
            $results = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM $table_name WHERE session_id = %s ORDER BY date_added DESC",
                $session_id
            ));
        }
        
        return $results;
    }
    
    public function wishlist_button_shortcode($atts) {
        $atts = shortcode_atts(array(
            'product_id' => get_the_ID(),
            'post_id' => null, // Alternative to product_id for backward compatibility
            'html_tag' => 'button',
            'class' => ''
        ), $atts);
        
        // Use post_id if provided, otherwise use product_id
        $product_id = !empty($atts['post_id']) ? $atts['post_id'] : $atts['product_id'];
        
        $args = array(
            'show_text' => false,
            'html_tag' => $atts['html_tag'],
            'custom_class' => $atts['class']
        );
        
        return $this->get_wishlist_button($product_id, $args);
    }
    
    public function wishlist_table_shortcode($atts) {
        $atts = shortcode_atts(array(
            'columns' => 'image,name,price,stock,remove',
            'show_empty_message' => 'true'
        ), $atts);
        
        return $this->get_wishlist_table($atts);
    }
    
    public function get_wishlist_button($product_id, $args = array()) {
        $defaults = array(
            'show_text' => false,
            'html_tag' => 'button',
            'custom_class' => ''
        );
        
        $args = wp_parse_args($args, $defaults);
        
        $user_id = get_current_user_id();
        $session_id = $this->get_session_id();
        $is_in_wishlist = $this->is_product_in_wishlist($product_id, $user_id, $session_id);
        
        $classes = array('wlm-button');
        if ($is_in_wishlist) {
            $classes[] = 'wlm-button--active';
        }
        
        // Add custom class if provided
        if (!empty($args['custom_class'])) {
            $custom_classes = explode(' ', $args['custom_class']);
            $classes = array_merge($classes, array_map('trim', $custom_classes));
        }
        
        $html_tag = in_array($args['html_tag'], array('button', 'a', 'div', 'span')) ? $args['html_tag'] : 'button';
        
        ob_start();
        ?>
        <<?php echo esc_attr($html_tag); ?> class="<?php echo esc_attr(implode(' ', $classes)); ?>" 
                data-product-id="<?php echo esc_attr($product_id); ?>"<?php if ($html_tag === 'button') echo ' type="button"'; ?>>
            <span class="wlm-button__icon">
                <svg class="wlm-heart" viewBox="0 0 24 24" width="20" height="20">
                    <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                </svg>
            </span>
        </<?php echo esc_attr($html_tag); ?>>
        <?php
        return ob_get_clean();
    }
    
    public function get_wishlist_table($args = array()) {
        $defaults = array(
            'columns' => array('image', 'name', 'price', 'stock', 'remove'),
            'show_empty_message' => true
        );
        
        $args = wp_parse_args($args, $defaults);
        
        if (is_string($args['columns'])) {
            $args['columns'] = explode(',', $args['columns']);
        }
        
        $user_id = get_current_user_id();
        $session_id = $this->get_session_id();
        $wishlist_items = $this->get_wishlist_items($user_id, $session_id);
        
        ob_start();
        ?>
        <div class="wlm-table-container">
            <?php if (empty($wishlist_items) && $args['show_empty_message']): ?>
                <div class="wlm-empty-wishlist">
                    <p><?php _e('Your wishlist is empty.', WLM_TEXT_DOMAIN); ?></p>
                </div>
            <?php else: ?>
                <table class="wlm-table">
                    <thead>
                        <tr>
                            <?php foreach ($args['columns'] as $column): ?>
                                <th class="wlm-table__header wlm-table__header--<?php echo esc_attr(trim($column)); ?>">
                                    <?php echo esc_html($this->get_column_title(trim($column))); ?>
                                </th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($wishlist_items as $item): ?>
                            <?php $product = wc_get_product($item->product_id); ?>
                            <?php if ($product): ?>
                                <tr class="wlm-table__row" data-product-id="<?php echo esc_attr($item->product_id); ?>">
                                    <?php foreach ($args['columns'] as $column): ?>
                                        <td class="wlm-table__cell wlm-table__cell--<?php echo esc_attr(trim($column)); ?>">
                                            <?php echo $this->get_column_content(trim($column), $product); ?>
                                        </td>
                                    <?php endforeach; ?>
                                </tr>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
        return ob_get_clean();
    }
    
    private function get_column_title($column) {
        $titles = array(
            'image' => __('Image', WLM_TEXT_DOMAIN),
            'name' => __('Product', WLM_TEXT_DOMAIN),
            'price' => __('Price', WLM_TEXT_DOMAIN),
            'stock' => __('Stock Status', WLM_TEXT_DOMAIN),
            'remove' => __('Remove', WLM_TEXT_DOMAIN)
        );
        
        return isset($titles[$column]) ? $titles[$column] : ucfirst($column);
    }
    
    private function get_column_content($column, $product) {
        switch ($column) {
            case 'image':
                return '<a href="' . esc_url($product->get_permalink()) . '">' . $product->get_image('thumbnail') . '</a>';
            
            case 'name':
                return '<a href="' . esc_url($product->get_permalink()) . '">' . esc_html($product->get_name()) . '</a>';
            
            case 'price':
                return $product->get_price_html();
            
            case 'stock':
                return $product->is_in_stock() ? __('In Stock', WLM_TEXT_DOMAIN) : __('Out of Stock', WLM_TEXT_DOMAIN);
            
            case 'remove':
                return '<button class="wlm-remove-button" data-product-id="' . esc_attr($product->get_id()) . '">' . __('Remove', WLM_TEXT_DOMAIN) . '</button>';
            
            default:
                return '';
        }
    }
    

    
    /**
     * Ensure wishlist page exists
     */
    public function ensure_wishlist_page_exists() {
        $this->create_wishlist_page();
    }
    
    /**
     * Create wishlist page with shortcode
     */
    public function create_wishlist_page() {
        // Check if page already exists and is valid
        $page_id = $this->get_wishlist_page_id();
        if ($page_id && get_post_status($page_id) === 'publish' && get_post_type($page_id) === 'page') {
            // Check if content contains the shortcode
            $page = get_post($page_id);
            if ($page && strpos($page->post_content, '[wlm_table]') === false) {
                // Update content to include shortcode
                wp_update_post(array(
                    'ID' => $page_id,
                    'post_content' => '[wlm_table]'
                ));
            }
            return $page_id;
        }
        
        // Check if a page with 'wishlist' slug exists
        $existing_page = get_page_by_path('wishlist');
        if ($existing_page && $existing_page->post_status === 'publish') {
            // Update existing page content if it doesn't contain the shortcode
            if (strpos($existing_page->post_content, '[wlm_table]') === false) {
                wp_update_post(array(
                    'ID' => $existing_page->ID,
                    'post_content' => '[wlm_table]'
                ));
            }
            update_option('wlm_wishlist_page_id', $existing_page->ID);
            return $existing_page->ID;
        }
        
        // Create new page
        $page_data = array(
            'post_title' => __('Wishlist', WLM_TEXT_DOMAIN),
            'post_content' => '[wlm_table]',
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_slug' => 'wishlist',
            'comment_status' => 'closed',
            'ping_status' => 'closed'
        );
        
        $page_id = wp_insert_post($page_data);
        
        if ($page_id && !is_wp_error($page_id)) {
            update_option('wlm_wishlist_page_id', $page_id);
            return $page_id;
        }
        
        return false;
    }
    
    /**
     * Get wishlist page ID
     */
    public function get_wishlist_page_id() {
        return get_option('wlm_wishlist_page_id', 0);
    }
    
    /**
     * Add admin label for wishlist page
     */
    public function add_wishlist_page_label($post_states, $post) {
        $wishlist_page_id = $this->get_wishlist_page_id();
        
        if ($post->ID == $wishlist_page_id) {
            $post_states['wlm_wishlist_page'] = __('Wishlist Page', WLM_TEXT_DOMAIN);
        }
        
        return $post_states;
    }
    
    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_submenu_page(
            'woocommerce',
            __('Wishlist Manager', WLM_TEXT_DOMAIN),
            __('Wishlist Manager', WLM_TEXT_DOMAIN),
            'manage_options',
            'wishlist-manager',
            array($this, 'admin_page'),
        );
        
    }
    
    /**
     * Admin page callback
     */
    public function admin_page() {
        include_once WLM_PLUGIN_PATH . 'admin/admin-page.php';
    }


    public function activate() {
        $this->create_wishlist_table();
        
        // Create wishlist page
        $this->create_wishlist_page();
        
        // Set default options
        $default_options = array(
            'button_position_shop' => 'after_add_to_cart',
            'button_position_single' => 'after_add_to_cart',
            'show_button_text' => 'yes',
            'button_text_add' => __('Add to Wishlist', WLM_TEXT_DOMAIN),
            'button_text_remove' => __('Remove from Wishlist', WLM_TEXT_DOMAIN),
            'table_columns' => 'image,name,price,stock,remove'
        );
        
        foreach ($default_options as $key => $value) {
            if (!get_option('wlm_' . $key)) {
                update_option('wlm_' . $key, $value);
            }
        }
    }
    
    public function deactivate() {
        // Clean up if needed
    }
}

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

?>