<?php
namespace IcreatorCookieConsent;

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

class Ajax {
    public static function boot(): void {
        add_action('wp_ajax_nopriv_iccb_log_consent', [self::class, 'acknowledge_consent']);
        add_action('wp_ajax_iccb_log_consent', [self::class, 'acknowledge_consent']);
        add_action('wp_ajax_nopriv_iccb_cookie_definitions', [self::class, 'cookie_definitions']);
        add_action('wp_ajax_iccb_cookie_definitions', [self::class, 'cookie_definitions']);
        add_action('wp_ajax_iccb_scan_cookies', [self::class, 'scan_cookies']);
    }

    public static function acknowledge_consent(): void {
        wp_send_json_success([
            'stored' => false,
            'message' => __('Consent logging is available in ConsentPress Pro.', 'consentpress'),
        ]);
    }

    public static function cookie_definitions(): void {
        wp_send_json(self::get_cookie_definitions());
    }

    public static function get_cookie_definitions(): array {
        $definitions = get_option('iccb_cookie_definitions', []);

        return is_array($definitions) ? $definitions : [];
    }

    public static function scan_cookies(): void {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have permission to scan cookies.', 'consentpress')], 403);
        }

        check_ajax_referer('iccb_scan_cookies', 'nonce');

        $raw_cookies = isset($_POST['cookies']) ? wp_unslash($_POST['cookies']) : '[]';
        $cookies = json_decode((string) $raw_cookies, true);
        if (!is_array($cookies)) {
            wp_send_json_error(['message' => __('Invalid cookie scan data.', 'consentpress')], 400);
        }

        $definitions = self::get_cookie_definitions();
        $added = [];
        $allowed_sources = ['client'];

        foreach ($cookies as $cookie) {
            if (!is_array($cookie)) {
                continue;
            }

            $name = sanitize_text_field($cookie['name'] ?? '');
            $source = sanitize_key($cookie['source'] ?? 'client');
            if (!in_array($source, $allowed_sources, true)) {
                $source = 'client';
            }

            if (!$name || isset($definitions[$name]) || self::should_exclude_cookie($name)) {
                continue;
            }

            $definition = self::lookup_cookie($name);
            $definition['domain'] = sanitize_text_field(wp_parse_url(home_url(), PHP_URL_HOST) ?: '');
            $definition['path'] = '/';
            $definition['source'] = $source;

            $definitions[$name] = $definition;
            $added[$name] = $definition;
        }

        if ($added) {
            update_option('iccb_cookie_definitions', $definitions);
        }

        wp_send_json_success([
            'added' => $added,
            'count' => count($added),
        ]);
    }

    private static function should_exclude_cookie(string $cookie_name): bool {
        $excluded = [
            'wp-settings',
            'wp-settings-time',
            'wordpress_logged_in',
            'wordpress_sec',
            'wordpress_test_cookie',
            'wp_lang',
            'PHPSESSID',
            'comment_author',
            'comment_author_email',
            'comment_author_url',
            'iccb_prefs_v1',
        ];

        foreach ($excluded as $pattern) {
            if (stripos($cookie_name, $pattern) === 0) {
                return true;
            }
        }

        return false;
    }

    private static function lookup_cookie(string $cookie_name): array {
        $patterns = self::known_cookie_patterns();
        $name_lc = strtolower($cookie_name);

        foreach ($patterns as $pattern => $definition) {
            $is_prefix = substr($pattern, -1) === '*';
            $needle = strtolower(rtrim($pattern, '*'));
            $matched = $is_prefix ? strpos($name_lc, $needle) === 0 : $name_lc === $needle;

            if ($matched) {
                return $definition;
            }
        }

        return [
            'type' => 'uncategorized',
            'duration' => '',
            'purpose' => __('Detected by the browser cookie scan. Review and complete this definition before publishing your policy.', 'consentpress'),
            'provider' => '',
        ];
    }

    private static function known_cookie_patterns(): array {
        return [
            '_ga' => [
                'type' => 'analytics',
                'duration' => '2 years',
                'purpose' => __('Used by Google Analytics to distinguish users.', 'consentpress'),
                'provider' => 'Google',
            ],
            '_ga_*' => [
                'type' => 'analytics',
                'duration' => '2 years',
                'purpose' => __('Used by Google Analytics 4 to persist session state.', 'consentpress'),
                'provider' => 'Google',
            ],
            '_gid' => [
                'type' => 'analytics',
                'duration' => '24 hours',
                'purpose' => __('Used by Google Analytics to distinguish users.', 'consentpress'),
                'provider' => 'Google',
            ],
            '_gat' => [
                'type' => 'analytics',
                'duration' => '1 minute',
                'purpose' => __('Used by Google Analytics to throttle request rate.', 'consentpress'),
                'provider' => 'Google',
            ],
            '_gcl_*' => [
                'type' => 'marketing',
                'duration' => '90 days',
                'purpose' => __('Used by Google advertising services to store campaign and conversion information.', 'consentpress'),
                'provider' => 'Google',
            ],
            '_fbp' => [
                'type' => 'marketing',
                'duration' => '3 months',
                'purpose' => __('Used by Meta Pixel to identify browsers for advertising and measurement.', 'consentpress'),
                'provider' => 'Meta',
            ],
            '_fbc' => [
                'type' => 'marketing',
                'duration' => '3 months',
                'purpose' => __('Used by Meta Pixel to store click identifiers for advertising measurement.', 'consentpress'),
                'provider' => 'Meta',
            ],
            'li_fat_id' => [
                'type' => 'marketing',
                'duration' => '30 days',
                'purpose' => __('Used by LinkedIn Insight Tag for conversion tracking.', 'consentpress'),
                'provider' => 'LinkedIn',
            ],
            'bcookie' => [
                'type' => 'marketing',
                'duration' => '2 years',
                'purpose' => __('Used by LinkedIn to identify browser devices.', 'consentpress'),
                'provider' => 'LinkedIn',
            ],
            'lidc' => [
                'type' => 'functional',
                'duration' => '24 hours',
                'purpose' => __('Used by LinkedIn for data center routing.', 'consentpress'),
                'provider' => 'LinkedIn',
            ],
            '__stripe_mid' => [
                'type' => 'necessary',
                'duration' => '1 year',
                'purpose' => __('Used by Stripe for fraud prevention and payment processing.', 'consentpress'),
                'provider' => 'Stripe',
            ],
            '__stripe_sid' => [
                'type' => 'necessary',
                'duration' => '30 minutes',
                'purpose' => __('Used by Stripe for fraud prevention and payment processing.', 'consentpress'),
                'provider' => 'Stripe',
            ],
            'woocommerce_cart_hash' => [
                'type' => 'necessary',
                'duration' => 'Session',
                'purpose' => __('Used by WooCommerce to store cart changes.', 'consentpress'),
                'provider' => 'WooCommerce',
            ],
            'woocommerce_items_in_cart' => [
                'type' => 'necessary',
                'duration' => 'Session',
                'purpose' => __('Used by WooCommerce to keep cart data synchronized.', 'consentpress'),
                'provider' => 'WooCommerce',
            ],
            'wp_woocommerce_session_*' => [
                'type' => 'necessary',
                'duration' => '2 days',
                'purpose' => __('Used by WooCommerce to identify a customer session.', 'consentpress'),
                'provider' => 'WooCommerce',
            ],
            'wordpress_test_cookie' => [
                'type' => 'necessary',
                'duration' => 'Session',
                'purpose' => __('Used by WordPress to check whether cookies are enabled.', 'consentpress'),
                'provider' => 'WordPress',
            ],
        ];
    }
}
