<?php
/**
 * Multi-Region Banner Configuration
 * 
 * Creates different banner configurations per region
 */

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

class Biscotti_MultiRegion_Banner
{

    /**
     * Cache lock TTL in seconds (short mutex to prevent stampede)
     */
    const CACHE_LOCK_TTL = 10;

    /**
     * GeoIP config cache TTL in seconds
     */
    const GEOIP_CACHE_TTL = 300;

    /**
     * Get banner configuration based on visitor region.
     * Uses transient caching with a lock to prevent race conditions on cache expiry.
     */
    public static function get_config()
    {
        // Try cached config first
        $cache_key = 'biscotti_geoip_config';
        $cached = get_transient($cache_key);
        if ($cached !== false) {
            return $cached;
        }

        // Acquire a transient-based lock to prevent multiple concurrent GeoIP lookups
        $lock_key = 'biscotti_geoip_lock';
        $lock_acquired = self::acquire_cache_lock($lock_key);

        if (!$lock_acquired) {
            // Another process is refreshing the cache; return default config
            $options = get_option('biscotti_options', []);
            return [
                'region'       => $options['default_region'] ?? 'eu',
                'region_name'  => 'Default',
                'law'          => 'GDPR',
                'consent_mode' => $options['default_consent_mode'] ?? 'opt-in',
            ];
        }

        // Double-check cache after acquiring lock (another process may have filled it)
        $cached = get_transient($cache_key);
        if ($cached !== false) {
            delete_transient($lock_key);
            return $cached;
        }

        $biscotti = biscotti_cmp();
        $region_code = Biscotti_GeoIP::get_visitor_region();
        $region = Biscotti_Regions::get_region($region_code);

        // Base config from settings
        $config = [
            'region' => $region_code,
            'region_name' => $region['name'],
            'law' => $region['law'],
            'consent_mode' => $region['consent_mode'],
        ];

        // Apply region-specific banner behavior
        switch ($region['consent_mode']) {
            case 'opt-in':
                $config = array_merge($config, self::get_opt_in_config($region, $biscotti));
                break;

            case 'opt-out':
                $config = array_merge($config, self::get_opt_out_config($region, $biscotti));
                break;

            case 'implied':
                $config = array_merge($config, self::get_implied_config($region, $biscotti));
                break;
        }

        // Add Google Consent Mode defaults
        $config['google_consent_defaults'] = self::get_google_consent_defaults($region_code);

        // Store in cache and release lock
        set_transient($cache_key, $config, self::GEOIP_CACHE_TTL);
        delete_transient($lock_key);

        return $config;
    }

    /**
     * Acquire a transient-based cache lock (mutex) to prevent stampede.
     *
     * @param string $lock_key Transient key for the lock
     * @return bool True if lock was acquired, false if another process holds it
     */
    private static function acquire_cache_lock($lock_key)
    {
        // If the lock transient already exists, another process is refreshing
        if (get_transient($lock_key) !== false) {
            return false;
        }
        // Set the lock with a short TTL (auto-expires if process crashes)
        set_transient($lock_key, time(), self::CACHE_LOCK_TTL);
        return true;
    }

    /**
     * Opt-in configuration (GDPR, LGPD, POPIA, etc.)
     */
    private static function get_opt_in_config($region, $biscotti)
    {
        $options = get_option('biscotti_options', []);
        return [
            'block_before_consent' => true,
            'show_banner_immediately' => true,
            'show_reject_button' => $region['reject_required'],
            'show_preferences_button' => $region['granular_consent'],
            'categories_required' => $region['granular_consent'],
            'accept_essential_only' => true,
            'cookie_wall_allowed' => $region['cookie_wall_allowed'],
            'buttons' => [
                'accept_all' => [
                    'text' => $options['accept_text'] ?? __('Accept all', 'biscotti-cmp'),
                    'primary' => true,
                ],
                'reject_all' => [
                    'text' => $options['reject_text'] ?? __('Reject all', 'biscotti-cmp'),
                    'show' => $region['reject_required'],
                ],
                'preferences' => [
                    'text' => $options['settings_text'] ?? __('Settings', 'biscotti-cmp'),
                    'show' => $region['granular_consent'],
                ],
            ],
            'categories' => [
                'essential' => ['enabled' => true, 'required' => true],
                'functional' => ['enabled' => true, 'required' => false],
                'analytics' => ['enabled' => true, 'required' => false],
                'marketing' => ['enabled' => true, 'required' => false],
            ],
        ];
    }

    /**
     * Opt-out configuration (CCPA, CPRA)
     */
    private static function get_opt_out_config($region, $biscotti)
    {
        return [
            'block_before_consent' => false, // Cookies allowed by default
            'show_banner_immediately' => true, // Still show notice
            'show_reject_button' => false,
            'show_do_not_sell' => isset($region['do_not_sell_required']) && $region['do_not_sell_required'],
            'show_preferences_button' => true,
            'categories_required' => false,
            'accept_essential_only' => false,
            'cookie_wall_allowed' => true,
            'buttons' => [
                'accept_all' => [
                    'text' => __('Got it', 'biscotti-cmp'),
                    'primary' => true,
                ],
                'do_not_sell' => [
                    'text' => __('Do Not Sell My Personal Information', 'biscotti-cmp'),
                    'show' => true,
                ],
                'preferences' => [
                    'text' => __('Privacy Preferences', 'biscotti-cmp'),
                    'show' => true,
                ],
            ],
            'categories' => [
                'essential' => ['enabled' => true, 'required' => true],
                'sale' => ['enabled' => true, 'required' => false, 'name' => __('Sale of Personal Information', 'biscotti-cmp')],
                'analytics' => ['enabled' => true, 'required' => false],
                'advertising' => ['enabled' => true, 'required' => false],
            ],
        ];
    }

    /**
     * Implied consent configuration (Australia, Canada, etc.)
     */
    private static function get_implied_config($region, $biscotti)
    {
        return [
            'block_before_consent' => false,
            'show_banner_immediately' => true, // Still show notice
            'show_reject_button' => false,
            'show_preferences_button' => true,
            'categories_required' => false,
            'accept_essential_only' => false,
            'cookie_wall_allowed' => true,
            'dismiss_on_scroll' => true, // Implied consent by continuing to use site
            'buttons' => [
                'accept_all' => [
                    'text' => __('I understand', 'biscotti-cmp'),
                    'primary' => true,
                ],
                'preferences' => [
                    'text' => __('Learn more', 'biscotti-cmp'),
                    'show' => true,
                ],
            ],
            'categories' => [
                'essential' => ['enabled' => true, 'required' => true],
                'analytics' => ['enabled' => true, 'required' => false],
                'marketing' => ['enabled' => true, 'required' => false],
            ],
        ];
    }

    /**
     * Get Google Consent Mode defaults per region
     */
    private static function get_google_consent_defaults($region_code)
    {
        $region = Biscotti_Regions::get_region($region_code);

        if ($region['consent_mode'] === 'opt-in') {
            // GDPR regions: all denied by default
            return [
                'ad_storage' => 'denied',
                'ad_user_data' => 'denied',
                'ad_personalization' => 'denied',
                'analytics_storage' => 'denied',
                'functionality_storage' => 'denied',
                'personalization_storage' => 'denied',
                'security_storage' => 'granted', // Always allowed
            ];
        } elseif ($region['consent_mode'] === 'opt-out') {
            // CCPA: granted by default, user can opt-out
            return [
                'ad_storage' => 'granted',
                'ad_user_data' => 'granted',
                'ad_personalization' => 'granted',
                'analytics_storage' => 'granted',
                'functionality_storage' => 'granted',
                'personalization_storage' => 'granted',
                'security_storage' => 'granted',
            ];
        } else {
            // Implied: granted by default
            return [
                'ad_storage' => 'granted',
                'ad_user_data' => 'granted',
                'ad_personalization' => 'granted',
                'analytics_storage' => 'granted',
                'functionality_storage' => 'granted',
                'personalization_storage' => 'granted',
                'security_storage' => 'granted',
            ];
        }
    }

    /**
     * Get banner texts for region
     */
    public static function get_texts($region_code)
    {
        $region = Biscotti_Regions::get_region($region_code);

        $texts = [
            'eu' => [
                'title' => __('We respect your privacy', 'biscotti-cmp'),
                'text' => __("We use cookies and similar technologies to optimise our website for you and to continuously improve it. Some of them are technically necessary, while others help us collect anonymous statistics or display personalised content.\n\nBy clicking \"Accept all\", you consent to the use of all cookies. Under \"Settings\", you can make an individual selection or decline consent.", 'biscotti-cmp'),
            ],
            'uk' => [
                'title' => __('Manage Consent', 'biscotti-cmp'),
                'text' => __('We use cookies and similar technologies to provide you with the best experience. By clicking "Accept", you consent to the use of ALL cookies.', 'biscotti-cmp'),
            ],
            'us' => [
                'title' => __('Privacy Notice', 'biscotti-cmp'),
                'text' => __('We use cookies and collect personal information to provide our services. You have the right to opt-out of the sale of your personal information.', 'biscotti-cmp'),
            ],
            'ca' => [
                'title' => __('Privacy Notice', 'biscotti-cmp'),
                'text' => __('We use cookies to enhance your browsing experience. By continuing to use our site, you consent to our use of cookies.', 'biscotti-cmp'),
            ],
            'au' => [
                'title' => __('Cookie Notice', 'biscotti-cmp'),
                'text' => __('We use cookies to improve your experience on our site. By continuing to browse, you agree to our use of cookies.', 'biscotti-cmp'),
            ],
            'br' => [
                'title' => __('Gerenciar consentimento', 'biscotti-cmp'),
                'text' => __('Utilizamos cookies para melhorar sua experiência. Ao clicar em \'Aceitar\', você concorda com o uso de todos os cookies.', 'biscotti-cmp'),
            ],
            'za' => [
                'title' => __('Manage Consent', 'biscotti-cmp'),
                'text' => __('We use cookies and process personal information in accordance with POPIA. By clicking "Accept", you consent to the use of cookies.', 'biscotti-cmp'),
            ],
        ];

        return isset($texts[$region_code]) ? $texts[$region_code] : $texts['eu'];
    }
}
