<?php
namespace IcreatorCookieConsent;

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

class Admin {
    public static function boot(): void {
        add_action('admin_menu', [self::class, 'menu']);
        add_action('admin_enqueue_scripts', [self::class, 'assets']);
    }

    public static function assets($hook): void {
        // Load only on our pages
        if (strpos($hook, 'iccb') === false) return;

        if (in_array($hook, ['iccb_page_iccb_definitions', 'consentpress_page_iccb_definitions'], true)) {
            wp_enqueue_style('iccb-admin-cookies', ICCB_ROOT_URL. 'assets/css/admin-dashboard.min.css', [], ICCB_VERSION);
            wp_enqueue_script('list-cookies-js',ICCB_ROOT_URL . 'assets/js/list-cookies.min.js', [], ICCB_VERSION, true);
            wp_enqueue_script('iccb-admin-definitions-free', ICCB_ROOT_URL . 'assets/js/admin-definitions-free.js', [], ICCB_VERSION, true);
            
            wp_localize_script('iccb-admin-definitions-free', 'ICCB_ADMIN_DEFINITIONS', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('iccb_scan_cookies'),
                'messages' => [
                    'scanComplete' => __('Cookie scan complete.', 'consentpress'),
                    'scanFailed' => __('Cookie scan failed. Please try again.', 'consentpress'),
                    'scanning' => __('Scanning browser cookies...', 'consentpress'),
                    'noneFound' => __('No new cookies found.', 'consentpress'),
                    'reviewAdded' => __('Review and save the detected cookies below.', 'consentpress'),
                ],
            ]);

            wp_localize_script('list-cookies-js', 'ICCB_CONFIG', [
                'cookie_json_url' => esc_url_raw(add_query_arg([
                    'action' => 'iccb_cookie_definitions',
                    'v' => time(),
                ], admin_url('admin-ajax.php'))),
            ]);

            wp_localize_script('list-cookies-js', 'ICCB_COOKIE_LIST_I18N', [
                'filterLabel' => __('Filter by Category:', 'consentpress'),
                'analytics'   => __('Analytics', 'consentpress'),
                'marketing'   => __('Marketing', 'consentpress'),
                'functional'  => __('Functional', 'consentpress'),
                'necessary'   => __('Necessary', 'consentpress'),
                'cookies'     => __('Cookies', 'consentpress'),
                'name'     => __('Name', 'consentpress'),
                'value'     => __('Value', 'consentpress'),
                'domain'     => __('Domain', 'consentpress'),
                'path'     => __('Path', 'consentpress'),
                'purpose'     => __('Purpose', 'consentpress'),
                'duration'     => __('Duration', 'consentpress'),
                'type'     => __('Type', 'consentpress'),
                'provider'     => __('Provider', 'consentpress'),
                'consent'     => __('Consent', 'consentpress'),
                'no_definitions_available' => __('No cookie definitions available.', 'consentpress')
            ]);
        }
        if ($hook === 'toplevel_page_iccb_dashboard') {
            wp_enqueue_style('iccb-admin-dashboard', ICCB_ROOT_URL. 'assets/css/admin-dashboard.min.css', [], ICCB_VERSION);
        }
    
        if (in_array($hook, ['iccb_page_iccb_settings', 'consentpress_page_iccb_settings'], true)) {
            wp_enqueue_style('iccb-admin-dashboard', ICCB_ROOT_URL. 'assets/css/admin-dashboard.min.css', [], ICCB_VERSION);
            wp_enqueue_style('iccb-admin-settings', ICCB_ROOT_URL. 'assets/css/admin-settings.min.css', [], ICCB_VERSION);
            wp_enqueue_script('iccb-admin-tabs', ICCB_ROOT_URL . 'assets/js/admin-settings-tabs.min.js', [], ICCB_VERSION, true);
        }

        if (in_array($hook, ['iccb_page_iccb_pixels', 'consentpress_page_iccb_pixels'], true)) {
            wp_enqueue_style('iccb-admin-dashboard', ICCB_ROOT_URL. 'assets/css/admin-dashboard.min.css', [], ICCB_VERSION);
        }

        if (in_array($hook, ['iccb_page_iccb_help', 'consentpress_page_iccb_help'], true)) {
            wp_enqueue_style('iccb-admin-cookies', ICCB_ROOT_URL. 'assets/css/admin-dashboard.min.css', [], ICCB_VERSION);
        }
    }

    public static function menu(): void {
        $iccb_icon = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGNsYXNzPSJjb25zZW50cHJlc3MtaWNvbiIgd2lkdGg9IjIxIiBoZWlnaHQ9IjIxIiB2aWV3Qm94PSIwIDAgMjEgMjEiIHJvbGU9ImltZyIgYXJpYS1sYWJlbD0iQ29uc2VudFByZXNzIj4KICAgICAgICAgICAgICAgICAg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sentPress', 'consentpress'),
            __('ConsentPress', 'consentpress'),
            'manage_options',
            'iccb_dashboard',
            [self::class, 'dashboard'],
            $iccb_icon,
            80
        );

        add_submenu_page('iccb_dashboard', __('Dashboard', 'consentpress'), __('Dashboard', 'consentpress'), 'manage_options', 'iccb_dashboard', [self::class, 'dashboard']);
        add_submenu_page('iccb_dashboard', __('Settings', 'consentpress'), __('Settings', 'consentpress'), 'manage_options', 'iccb_settings', [self::class, 'settings']);
        add_submenu_page('iccb_dashboard', __('Pixels & GTM', 'consentpress'), __('Pixels & GTM', 'consentpress'), 'manage_options', 'iccb_pixels', [self::class, 'pixels']);
        add_submenu_page('iccb_dashboard', __('Cookie Definitions', 'consentpress'), __('Cookie Definitions', 'consentpress'), 'manage_options', 'iccb_definitions', [self::class, 'definitions']);
        add_submenu_page('iccb_dashboard', __('Help & About', 'consentpress'), __('Help & About', 'consentpress'), 'manage_options', 'iccb_help', [self::class, 'help']);
    }

    public static function dashboard(): void {
        $stats = [
            'defs' => self::count_defs(),
            'version' => ICCB_VERSION,
        ];
        View::render('admin/dashboard', compact('stats'));
    }

    public static function settings(): void {
        // Defaults 
        $defaults = Settings::banner_options();
        
        $preview = new BannerPreview([
            'position'      => $defaults['banner_position'],
            'layout'        => $defaults['layout_style'],
            'button_style'  => $defaults['button_style'],
            'button_radius' => $defaults['button_radius'],
            'font_family'   => $defaults['banner_font_family'],
            'font_size'     => $defaults['banner_font_size'],
            'accent_color'  => $defaults['accent_color'],
            'default_categories' => (array) $defaults['default_categories'],
        ]);

        View::render('admin/settings', compact('defaults','preview'));
    }

    public static function pixels(): void {
        if (isset($_POST['iccb_pixel_submit']) && current_user_can('manage_options')) {
            check_admin_referer('iccb_save_pixels');

            $mode = sanitize_key($_POST['pixel_mode'] ?? 'gtm_only');
            if (!in_array($mode, ['gtm_only', 'gtm_plus_pixels'], true)) {
                $mode = 'gtm_only';
            }

            $settings = [
                'mode' => $mode,
                'gtm' => sanitize_text_field(wp_unslash($_POST['gtm_id'] ?? '')),
                'facebook' => sanitize_text_field(wp_unslash($_POST['facebook_pixel'] ?? '')),
                'linkedin' => sanitize_text_field(wp_unslash($_POST['linkedin_pixel'] ?? '')),
            ];

            update_option('iccb_pixel_settings', $settings);
            echo '<div class="updated"><p>' . esc_html__('Pixel and GTM settings saved.', 'consentpress') . '</p></div>';
        }

        $settings = wp_parse_args((array) get_option('iccb_pixel_settings', []), [
            'mode' => 'gtm_only',
            'gtm' => '',
            'facebook' => '',
            'linkedin' => '',
        ]);

        View::render('admin/pixels', compact('settings'));
    }

    public static function definitions(): void {
        $definitions = Ajax::get_cookie_definitions();

        // Save submitted form
        if (isset($_POST['iccb_save_definitions']) && current_user_can('manage_options')) {
            check_admin_referer('iccb_definitions_save');

            $new_defs = [];
            $allowed_types = ['necessary','functional','analytics','performance','marketing','uncategorized'];
            $cookie_names = isset($_POST['cookie_name']) ? wp_unslash((array) $_POST['cookie_name']) : [];
            $cookie_types = isset($_POST['cookie_type']) ? wp_unslash((array) $_POST['cookie_type']) : [];
            $cookie_domains = isset($_POST['cookie_domain']) ? wp_unslash((array) $_POST['cookie_domain']) : [];
            $cookie_paths = isset($_POST['cookie_path']) ? wp_unslash((array) $_POST['cookie_path']) : [];
            $cookie_durations = isset($_POST['cookie_duration']) ? wp_unslash((array) $_POST['cookie_duration']) : [];
            $cookie_purposes = isset($_POST['cookie_purpose']) ? wp_unslash((array) $_POST['cookie_purpose']) : [];
            $cookie_providers = isset($_POST['cookie_provider']) ? wp_unslash((array) $_POST['cookie_provider']) : [];
            $cookie_sources = isset($_POST['cookie_source']) ? wp_unslash((array) $_POST['cookie_source']) : [];

            foreach ($cookie_names as $i => $name) {
                $name = sanitize_text_field($name);
                if (!$name) continue;
                $type = sanitize_key($cookie_types[$i] ?? 'uncategorized');
                if (!in_array($type, $allowed_types, true)) {
                    $type = 'uncategorized';
                }

                $new_defs[$name] = [
                    'type'     => $type,
                    'domain'   => sanitize_text_field($cookie_domains[$i] ?? ''),
                    'path'     => sanitize_text_field($cookie_paths[$i] ?? ''),
                    'duration' => sanitize_text_field($cookie_durations[$i] ?? ''),
                    'purpose'  => sanitize_text_field($cookie_purposes[$i] ?? ''),
                    'provider' => sanitize_text_field($cookie_providers[$i] ?? ''),
                ];

                $source = sanitize_key($cookie_sources[$i] ?? '');
                if ($source) {
                    $new_defs[$name]['source'] = $source;
                }
            }

            update_option('iccb_cookie_definitions', $new_defs);
            echo '<div class="updated"><p>' . esc_html__('Cookie definitions saved.', 'consentpress') . '</p></div>';

            $definitions = $new_defs;
        }
        View::render('admin/definitions', compact('definitions'));
    }

    public static function help(): void { 
        View::render('admin/help'); 
    }

    private static function count_defs(): int {
        return count(Ajax::get_cookie_definitions());
    }
}
