<?php
/**
 * Biscotti WooCommerce Compatibility
 *
 * Ensures consent management works correctly with WooCommerce:
 * - Auto-categorizes WooCommerce cookies as essential vs. analytics
 * - Blocks WooCommerce tracking cookies until consent is given
 * - Integrates with Google Analytics for WooCommerce
 * - Exposes WooCommerce cookie data to the banner scanner
 *
 * @package Biscotti_CMP
 * @since 3.1.0
 */

if (!defined('ABSPATH')) {
    exit;
}

// Guard: only load if WooCommerce is active
if (!class_exists('WooCommerce')) {
    return;
}

class Biscotti_WooCommerce
{
    private static $instance = null;

    /**
     * Known WooCommerce cookies categorized by purpose
     */
    private static $wc_cookies = [
        // Essential — required for cart/checkout to work
        'essential' => [
            'woocommerce_cart_hash' => [
                'name' => 'woocommerce_cart_hash',
                'description' => 'Stores a hash of the cart contents to verify cart data integrity.',
                'duration' => 'Session',
                'provider' => 'WooCommerce',
            ],
            'woocommerce_items_in_cart' => [
                'name' => 'woocommerce_items_in_cart',
                'description' => 'Indicates whether the cart contains items.',
                'duration' => 'Session',
                'provider' => 'WooCommerce',
            ],
            'wp_woocommerce_session_' => [
                'name' => 'wp_woocommerce_session_*',
                'description' => 'Contains a unique session identifier for each customer.',
                'duration' => '2 days',
                'provider' => 'WooCommerce',
            ],
            'woocommerce_recently_viewed' => [
                'name' => 'woocommerce_recently_viewed',
                'description' => 'Stores recently viewed products for the customer.',
                'duration' => 'Session',
                'provider' => 'WooCommerce',
            ],
            'store_notice' => [
                'name' => 'store_notice[notice id]',
                'description' => 'Remembers dismissed store notices.',
                'duration' => 'Session',
                'provider' => 'WooCommerce',
            ],
        ],
        // Analytics — tracking and measurement cookies
        'analytics' => [
            'tk_ai' => [
                'name' => 'tk_ai',
                'description' => 'WooCommerce analytics tracking identifier.',
                'duration' => '1 year',
                'provider' => 'WooCommerce / Jetpack',
            ],
            'tk_lr' => [
                'name' => 'tk_lr',
                'description' => 'WooCommerce analytics last request time.',
                'duration' => '1 year',
                'provider' => 'WooCommerce / Jetpack',
            ],
            'tk_or' => [
                'name' => 'tk_or',
                'description' => 'WooCommerce analytics original referrer.',
                'duration' => '5 years',
                'provider' => 'WooCommerce / Jetpack',
            ],
            'tk_r3d' => [
                'name' => 'tk_r3d',
                'description' => 'WooCommerce referrer tracking.',
                'duration' => '3 days',
                'provider' => 'WooCommerce / Jetpack',
            ],
            'tk_tc' => [
                'name' => 'tk_tc',
                'description' => 'WooCommerce tracker cookie.',
                'duration' => 'Session',
                'provider' => 'WooCommerce / Jetpack',
            ],
        ],
        // Marketing — advertising pixels from WC extensions
        'marketing' => [
            'wc_facebook_pixel' => [
                'name' => 'fbp / _fbp',
                'description' => 'Facebook Pixel cookie set by WooCommerce Facebook extension.',
                'duration' => '3 months',
                'provider' => 'Facebook / Meta',
            ],
        ],
    ];

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct()
    {
        // Register WooCommerce cookies with Biscotti scanner
        add_filter('biscotti_known_cookies', [$this, 'register_wc_cookies']);

        // Add WC cookie data to the cookie table shortcode
        add_filter('biscotti_cookie_table_data', [$this, 'add_wc_cookies_to_table']);

        // Inject consent-aware script loading for WC analytics
        add_action('wp_enqueue_scripts', [$this, 'manage_wc_tracking_scripts'], 100);

        // Add WooCommerce-specific consent categories to BiscottiConfig
        add_filter('biscotti_config_data', [$this, 'add_wc_config']);

        // WooCommerce admin integration
        if (is_admin()) {
            add_filter('biscotti_admin_status', [$this, 'add_wc_status']);
        }
    }

    /**
     * Register WC cookies so the Biscotti scanner recognizes them
     */
    public function register_wc_cookies($known_cookies)
    {
        foreach (self::$wc_cookies as $category => $cookies) {
            foreach ($cookies as $key => $cookie_data) {
                $known_cookies[] = array_merge($cookie_data, [
                    'category' => strtoupper($category),
                    'source' => 'woocommerce',
                ]);
            }
        }
        return $known_cookies;
    }

    /**
     * Add WC cookies to the cookie table shortcode output
     */
    public function add_wc_cookies_to_table($cookies)
    {
        foreach (self::$wc_cookies as $category => $cat_cookies) {
            foreach ($cat_cookies as $cookie_data) {
                $cookies[] = array_merge($cookie_data, [
                    'category' => $category,
                ]);
            }
        }
        return $cookies;
    }

    /**
     * Manage WooCommerce tracking scripts based on consent
     * Defers analytics/marketing WC scripts until consent is given
     */
    public function manage_wc_tracking_scripts()
    {
        // Only act on frontend
        if (is_admin()) {
            return;
        }

        // Check if WooCommerce analytics tracking is active
        if (class_exists('WC_Site_Tracking')) {
            // Dequeue WC tracker — it will be re-queued via Biscotti consent callback
            wp_dequeue_script('wc-tracks');

            // Add consent-aware re-enablement
            wp_add_inline_script('biscotti-widget', $this->get_consent_tracking_script(), 'after');
        }

        // Handle WooCommerce Google Analytics integration
        $ga_handles = ['woocommerce-google-analytics-integration', 'wc-google-analytics-pro'];
        foreach ($ga_handles as $handle) {
            if (wp_script_is($handle, 'enqueued')) {
                wp_dequeue_script($handle);
            }
        }
    }

    /**
     * Generate JS that re-enables WC tracking after analytics consent
     */
    private function get_consent_tracking_script()
    {
        return "
            if (window.Biscotti) {
                window.Biscotti.on('consent', function(consent) {
                    if (consent.analytics) {
                        // Re-enable WooCommerce tracking
                        if (typeof wc_tracks_params !== 'undefined') {
                            var s = document.createElement('script');
                            s.src = (typeof wc_tracks_params.js_url !== 'undefined')
                                ? wc_tracks_params.js_url : '';
                            if (s.src) document.body.appendChild(s);
                        }
                    }
                });
            }
        ";
    }

    /**
     * Add WooCommerce info to BiscottiConfig
     */
    public function add_wc_config($config)
    {
        $config['woocommerce'] = [
            'active' => true,
            'version' => defined('WC_VERSION') ? WC_VERSION : 'unknown',
            'essentialCookies' => array_keys(self::$wc_cookies['essential']),
        ];
        return $config;
    }

    /**
     * Add WooCommerce status to admin diagnostics
     */
    public function add_wc_status($status)
    {
        $status['woocommerce'] = [
            'active' => true,
            'version' => defined('WC_VERSION') ? WC_VERSION : 'unknown',
            'cookie_count' => count(self::$wc_cookies['essential'])
                + count(self::$wc_cookies['analytics'])
                + count(self::$wc_cookies['marketing']),
        ];
        return $status;
    }

    /**
     * Get all known WooCommerce cookies
     * @return array
     */
    public static function get_cookies()
    {
        return self::$wc_cookies;
    }
}

// Initialize
Biscotti_WooCommerce::get_instance();
