<?php
/**
 * WooCommerce integration for Blynex Theme
 *
 * @package WordPress
 * @subpackage Blynex
 * @since 1.0.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class Blynex_WooCommerce
 * Handles all WooCommerce-specific functionality for the theme
 */
class Blynex_WooCommerce {
    /**
     * Instance of this class
     */
    private static $instance = null;

    /**
     * Get the singleton instance of this class
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    public function __construct() {
        // Check if WooCommerce is active
        if (!class_exists('WooCommerce')) {
            return;
        }

        // Initialize WooCommerce functionality
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_ajax_get_product_details', array($this, 'get_product_details'));
        add_action('wp_ajax_nopriv_get_product_details', array($this, 'get_product_details'));
        add_action('wp_ajax_woocommerce_ajax_add_to_cart', array($this, 'ajax_add_to_cart'));
        add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', array($this, 'ajax_add_to_cart'));
        
        // Enable AJAX add to cart on archives
        add_filter('woocommerce_enable_ajax_add_to_cart', '__return_true');
        
        // Add nonce for AJAX requests
        add_action('wp_ajax_nopriv_get_nonce', array($this, 'get_nonce'));
        add_action('wp_ajax_get_nonce', array($this, 'get_nonce'));
    }

    /**
     * Enqueue scripts and styles
     */
    public function enqueue_scripts() {
        // AJAX add to cart support
        wp_enqueue_script('wc-add-to-cart');
        wp_enqueue_script('wc-cart-fragments');
        
        // Enqueue Quick View CSS
        wp_enqueue_style(
            'blynex-quick-view',
            get_template_directory_uri() . '/assets/css/quick-view.css',
            array(),
            '1.0.0'
        );
        
        // Enqueue Quick View JS
        wp_enqueue_script(
            'blynex-quick-view',
            get_template_directory_uri() . '/assets/js/quick-view.js',
            array('jquery'),
            '1.0.0',
            true
        );
        
        // Localize the script with new data
        $params = array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'ajax_nonce' => wp_create_nonce('blynex_quick_view_nonce'),
            'wc_ajax_url' => WC_AJAX::get_endpoint('%%endpoint%%'),
            'cart_url' => wc_get_cart_url(),
            'checkout_url' => wc_get_checkout_url(),
            'home_url' => home_url('/')
        );
        
        wp_localize_script('blynex-quick-view', 'blynex_quick_view_params', $params);
    }
    
    /**
     * Generate and return a fresh nonce
     */
    public function get_nonce() {
        // Skip nonce verification for this endpoint to prevent circular dependencies
        if (!defined('DOING_AJAX') || !DOING_AJAX) {
            wp_send_json_error(array('message' => 'Invalid request.'));
            wp_die();
        }

        $new_nonce = wp_create_nonce('blynex_quick_view_nonce');
        
        // Log the nonce refresh
        error_log('Generated new nonce for quick view');
        
        wp_send_json_success(array(
            'nonce' => $new_nonce,
            'message' => 'Nonce refreshed successfully',
            'timestamp' => time()
        ));
        
        wp_die();
    }

    /**
     * AJAX handler for getting product details
     */
    public function get_product_details() {
        // Verify nonce
        if (!check_ajax_referer('blynex_quick_view_nonce', 'security', false)) {
            wp_send_json_error(array('message' => 'Invalid nonce'));
            wp_die();
        }

        $product_identifier = isset($_POST['product_id']) ? sanitize_text_field($_POST['product_id']) : '';
        $is_slug = isset($_POST['is_slug']) ? (bool)$_POST['is_slug'] : false;
        
        if (empty($product_identifier)) {
            wp_send_json_error(array('message' => 'Product identifier is required'));
            return;
        }

        // Handle both ID and slug
        if ($is_slug) {
            // Try to get product by slug
            $product = get_posts(array(
                'name' => $product_identifier,
                'post_type' => 'product',
                'post_status' => 'publish',
                'numberposts' => 1
            ));
            
            if (!empty($product)) {
                $product = wc_get_product($product[0]->ID);
            }
        } else {
            // Get by ID
            $product = wc_get_product(intval($product_identifier));
        }
        
        if (!$product) {
            wp_send_json_error(array('message' => 'Product not found'));
            return;
        }
        
        // Get the actual product ID for further processing
        $product_id = $product->get_id();

        $response = array(
            'description' => $product->get_description() ? $product->get_description() : $product->get_short_description(),
            'sku' => $product->get_sku(),
            'categories' => wc_get_product_category_list($product_id),
            'rating' => wc_get_rating_html($product->get_average_rating()),
            'review_count' => $product->get_review_count(),
            'price' => $product->get_price_html(),
            'variations' => array()
        );
        
        // Debug: Log the review count
        error_log('Product ID: ' . $product_id . ' - Review count: ' . $product->get_review_count());

        // If product is variable, get variation data
        if ($product->is_type('variable')) {
            $available_variations = $product->get_available_variations();
            $attributes = $product->get_variation_attributes();
            
            // Process variations to include only necessary data
            $processed_variations = array();
            foreach ($available_variations as $variation) {
                $processed_variations[] = array(
                    'variation_id' => $variation['variation_id'],
                    'attributes' => $variation['attributes'],
                    'is_in_stock' => $variation['is_in_stock'],
                    'price_html' => $variation['price_html'],
                    'image' => $variation['image']
                );
            }

            // Process attributes to ensure they're not empty
            $processed_attributes = array();
            foreach ($attributes as $attribute_name => $options) {
                if (!empty($options)) {
                    $processed_attributes[$attribute_name] = array_values($options);
                }
            }

            $response['variations'] = array(
                'variations' => $processed_variations,
                'attributes' => $processed_attributes
            );
        }

        wp_send_json_success($response);
    }

    /**
     * AJAX add to cart handler
     */
    public function ajax_add_to_cart() {
        // Verify this is an AJAX request
        if (!defined('DOING_AJAX') || !DOING_AJAX) {
            wp_send_json_error(array('message' => 'Invalid request.'));
            wp_die();
        }

        // Log the incoming request for debugging
        error_log('AJAX Add to Cart Request: ' . print_r($_POST, true));
        
        // Verify nonce
        if (!check_ajax_referer('blynex_quick_view_nonce', 'security', false)) {
            error_log('Invalid nonce in AJAX request');
            wp_send_json_error(array(
                'message' => 'Session expired. Please refresh the page and try again.',
                'refresh_required' => true
            ));
            wp_die();
        }

        try {
            // Get product data from request
            $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
            $quantity = isset($_POST['quantity']) ? wc_stock_amount($_POST['quantity']) : 1;
            $variation_id = isset($_POST['variation_id']) ? absint($_POST['variation_id']) : 0;
            $variation = array();

            // Log the request details
            error_log(sprintf(
                'Processing add to cart - Product ID: %d, Qty: %d, Variation ID: %d',
                $product_id,
                $quantity,
                $variation_id
            ));
            
            // Validate product ID
            if (!$product_id) {
                throw new Exception(__('No product selected', 'blynex'));
            }
            
            // Get product object
            $product = wc_get_product($product_id);
            if (!$product) {
                throw new Exception(__('Invalid product', 'blynex'));
            }
            
            // Check if product is purchasable
            if (!$product->is_purchasable()) {
                throw new Exception(__('This product cannot be purchased', 'blynex'));
            }
            
            // Handle variable product
            if ($product->is_type('variable') && $variation_id) {
                $variation_product = wc_get_product($variation_id);
                if (!$variation_product) {
                    throw new Exception(__('Invalid product variation', 'blynex'));
                }
                
                // Get variation attributes
                foreach ($_POST as $key => $value) {
                    if (strpos($key, 'attribute_') === 0) {
                        $variation[$key] = sanitize_text_field($value);
                    }
                }
                
                $product = $variation_product;
            }
            
            // Add to cart
            $cart_item_key = WC()->cart->add_to_cart(
                $product_id,
                $quantity,
                $variation_id,
                $variation
            );
            
            if (!$cart_item_key) {
                throw new Exception(__('Failed to add product to cart', 'blynex'));
            }
            
            // Get updated cart fragments
            $fragments = array();
            
            // Get mini cart
            ob_start();
            woocommerce_mini_cart();
            $mini_cart = ob_get_clean();
            
            $fragments['div.widget_shopping_cart_content'] = '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>';
            
            // Cart hash
            $cart_hash = WC()->cart->get_cart_hash();
            
            // Success message
            $message = sprintf(
                __('"%s" has been added to your cart.', 'blynex'),
                $product->get_name()
            );
            
            // Prepare response
            $response = array(
                'success' => true,
                'message' => $message,
                'cart_hash' => $cart_hash,
                'cart_quantity' => WC()->cart->get_cart_contents_count(),
                'fragments' => $fragments,
                'cart_total' => WC()->cart->get_cart_total(),
                'cart_subtotal' => WC()->cart->get_cart_subtotal(),
                'redirect' => wc_get_cart_url()
            );
            
            // Trigger added to cart event
            do_action('woocommerce_ajax_added_to_cart', $product_id);
            
            wp_send_json($response);
            
        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => $e->getMessage(),
                'error' => true
            ));
        }
        
        wp_die();
    }
}

// Initialize the WooCommerce integration
Blynex_WooCommerce::get_instance();
