<?php
namespace WPUltimateSecurity\UltimateSecurity\Presentation\Admin;

use WPUltimateSecurity\UltimateSecurity\Support\Validation\ProValidation;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\StringHelper;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\CryptoHelper;

class AdminAssets
{
    /**
     * Static cache for user roles list.
     *
     * @var array|null
     */
    private static $user_roles_cache = null;

    /**
     * Static cache for users list.
     *
     * @var array|null
     */
    private static $users_list_cache = null;
    public static function register()
    {
        add_action('admin_enqueue_scripts', [self::class, 'enqueue_styles']);

        add_action('admin_enqueue_scripts', [self::class, 'enqueue_scripts']);

        add_action('admin_enqueue_scripts', [self::class, 'ultimate_script_deactive_functionalities']);

        add_action('current_screen', [self::class, 'ultimate_security_hide_admin_notices']);

        add_filter('admin_body_class', [self::class, 'ultimate_security_admin_body_class']);

    }



    public static function enqueue_styles()
    {
        $is_plugin_page = self::ultimate_security_is_plugin_page();
        $current_screen = get_current_screen();

        // Only load main CSS on relevant pages
        if ($is_plugin_page || ($current_screen && in_array($current_screen->id, ['user-edit', 'profile', 'plugins']))) {
            wp_enqueue_style('ultimate-security-admin' . '-admin-style', ULTIMATE_SECURITY_URL . 'assets/public/css/style.css', array(), ULTIMATE_SECURITY_VERSION, 'all');
        }

        if ($is_plugin_page) {
            // Add preconnect for Google Fonts for better performance
            add_filter('wp_resource_hints', [self::class, 'add_font_preconnect'], 10, 2);

            // Load Google Fonts with display=swap for better CLS
            wp_enqueue_style(
                'ultimate-security-admin-figtree',
                'https://fonts.googleapis.com/css2?family=Figtree:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap',
                array(),
                null, // No version for external resources
                'all'
            );
            wp_enqueue_style('ultimate-security-admin' . '-hint', ULTIMATE_SECURITY_URL . 'assets/admin/css/hint.css', array(), ULTIMATE_SECURITY_VERSION, 'all');
            wp_enqueue_style('ultimate-security-admin' . '-admin', ULTIMATE_SECURITY_URL . 'assets/admin/css/admin-style.css', array(), ULTIMATE_SECURITY_VERSION, 'all');
        }

        if ($current_screen && ($current_screen->id == 'user-edit' || $current_screen->id == 'profile')) {
            wp_enqueue_style('ultimate-security-admin' . '-hint', ULTIMATE_SECURITY_URL . 'assets/admin/css/hint.css', array(), ULTIMATE_SECURITY_VERSION, 'all');
        }
    }

    /**
     * Add preconnect hints for Google Fonts.
     *
     * @param array  $hints URLs to print for resource hints.
     * @param string $relation_type The relation type the URLs are printed for.
     * @return array
     */
    public static function add_font_preconnect($hints, $relation_type)
    {
        if ('preconnect' === $relation_type) {
            $hints[] = [
                'href' => 'https://fonts.googleapis.com',
                'crossorigin' => '',
            ];
            $hints[] = [
                'href' => 'https://fonts.gstatic.com',
                'crossorigin' => 'anonymous',
            ];
        }
        return $hints;
    }

    public static function ultimate_security_is_plugin_page()
    {
        if (!is_admin()) {
            return false;
        }

        if (function_exists('get_current_screen')) {
            $screen = get_current_screen();

            if ($screen && isset($screen->id) && $screen->id === 'toplevel_page_ultimate-security') {
                return true;
            }
        }

        return false;
    }

    public static function enqueue_scripts()
    {
        $is_plugin_page = self::ultimate_security_is_plugin_page();
        $current_screen = get_current_screen();

        // Only load core scripts on pages where they're needed
        if ($is_plugin_page || ($current_screen && in_array($current_screen->id, ['user-edit', 'profile', 'plugins']))) {
            wp_enqueue_script('ultimate-security' . '-ajax', ULTIMATE_SECURITY_URL . 'assets/public/js/ajax.js', array('jquery'), ULTIMATE_SECURITY_VERSION, false);
            wp_enqueue_script('ultimate-security' . '-admin-script', ULTIMATE_SECURITY_URL . 'assets/admin/js/admin-script.js', array('jquery'), ULTIMATE_SECURITY_VERSION, false);
        }

        if ($is_plugin_page) {
            add_thickbox();
            wp_enqueue_media();
            wp_enqueue_script('jquery-ui-accordion');
            wp_enqueue_script('jquery-ui-sortable');

            wp_enqueue_script(
                'ultimate-security-admin' . '-react',
                ULTIMATE_SECURITY_URL . 'build/index.js',
                array('wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'wp-media-utils', 'wp-block-editor', 'react', 'react-dom'),
                ULTIMATE_SECURITY_VERSION,
                true
            );
        }

        if ($current_screen && ($current_screen->id == 'user-edit' || $current_screen->id == 'profile')) {
            wp_enqueue_script('ultimate-security-admin' . '-admin-js', ULTIMATE_SECURITY_URL . 'assets/admin/js/script.js', array('jquery'), ULTIMATE_SECURITY_VERSION, false);
        }

        // Only load heavy data (users, roles) on plugin page where it's actually needed
        if ($is_plugin_page || ($current_screen && in_array($current_screen->id, ['user-edit', 'profile', 'plugins']))) {
            $userRoleList = self::get_user_roles_cached();
            $usersList = self::get_users_list_cached();

            // Fetch all pages
            global $ultimate_security_page_data;
            global $ultimate_security_product_category_data;

            $deactivation_key = get_option('ultimate_security_plugin_deactivation_secret_key');
            if (!$deactivation_key) {
                $deactivation_key = StringHelper::random(20);
                $encrypted_key = CryptoHelper::encrypt($deactivation_key);
                if ($encrypted_key) {
                    update_option('ultimate_security_plugin_deactivation_secret_key', $encrypted_key);
                } else {
                    update_option('ultimate_security_plugin_deactivation_secret_key', $deactivation_key);
                }
            } else {
                $decrypted_key = CryptoHelper::decrypt($deactivation_key);
                if ($decrypted_key) {
                    $deactivation_key = $decrypted_key;
                }
            }

            $deactivation_url = add_query_arg(
                [
                    'action' => 'ultimate_security_deactivate',
                    'secret_key' => $deactivation_key,
                ],
                admin_url('admin-post.php')
            );

            $ajax_params = array(
                'admin_url' => admin_url(),
                'abspath' => ABSPATH,
                'ajax_url' => admin_url('admin-ajax.php'),
                'rest_url' => esc_url_raw(rest_url()),
                'site_url' => esc_url_raw(site_url()),
                'security' => esc_attr(wp_create_nonce('ultimate_security_nonce')),
                'install_plugin_wpnonce' => esc_attr(wp_create_nonce('updates')),
                'userRoleList' => $userRoleList,
                'usersList' => $usersList,
                'pageList' => $ultimate_security_page_data,
                'version' => ULTIMATE_SECURITY_VERSION,
                'imageUrl' => ULTIMATE_SECURITY_URL . 'assets/admin/images/',
                'productCategoryList' => $ultimate_security_product_category_data,
                'isPro' => ProValidation::ultimate_security_is_pro(),
                'deactivation_url' => (current_user_can('manage_options')) ? $deactivation_url : '',
                'get_current_user_id' => get_current_user_id(),
            );
            wp_localize_script('ultimate-security' . '-ajax', 'ultimate_security_ajax_obj', $ajax_params);

            wp_localize_script('ultimate-security' . '-admin-script', 'ultimate_security_ajax', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('ultimate_security_passkey')
            ]);
        }
    }

    /**
     * Get user roles list with caching.
     *
     * @return array
     */
    private static function get_user_roles_cached()
    {
        if (self::$user_roles_cache !== null) {
            return self::$user_roles_cache;
        }

        $roles = get_editable_roles();
        $userRoleList = [];
        $n = 0;
        foreach ($roles as $k => $v) {
            $userRoleList[$n]['code'] = $k;
            $userRoleList[$n]['value'] = $v['name'];
            $n++;
        }

        self::$user_roles_cache = $userRoleList;
        return $userRoleList;
    }

    /**
     * Get users list with caching.
     *
     * Performance optimization: Only fetches essential fields and limits results.
     *
     * @return array
     */
    private static function get_users_list_cached()
    {
        if (self::$users_list_cache !== null) {
            return self::$users_list_cache;
        }

        // Optimize: Only fetch needed fields, limit results for large sites
        $users = get_users([
            'fields' => ['ID', 'user_login', 'display_name'],
            'number' => 1000, // Reasonable limit for dropdown
            'orderby' => 'display_name',
            'order' => 'ASC',
        ]);

        $usersList = [];
        foreach ($users as $user) {
            $usersList[] = [
                'code' => $user->user_login,
                'value' => $user->display_name,
            ];
        }

        self::$users_list_cache = $usersList;
        return $usersList;
    }

    public static function ultimate_script_deactive_functionalities($hook)
    {
        if ($hook !== 'plugins.php') {
            return;
        }

        // Enqueue the React deactivation modal
        wp_enqueue_script(
            'ultimate-security-deact',
            ULTIMATE_SECURITY_URL . 'build/deactivation.js',
            array('wp-element', 'wp-i18n'),
            ULTIMATE_SECURITY_VERSION,
            true
        );

        wp_localize_script('ultimate-security-deact', 'ULTIMATE_SECURITY_DEACT', [
            'nonce' => wp_create_nonce('ultimate_security_deact_nonce'),
            'ajax_url' => admin_url('admin-ajax.php'),
            'pluginBasename' => ULTIMATE_SECURITY_FILE,
        ]);
    }

    public static function ultimate_security_hide_admin_notices()
    {
        if (self::ultimate_security_is_plugin_page()) {
            remove_all_actions('user_admin_notices');
            remove_all_actions('admin_notices');
        }
    }

    public static function ultimate_security_admin_body_class($classes)
    {
        if (self::ultimate_security_is_plugin_page()) {
            $classes .= ' ' . 'ultimate-security' . '-settings-template ';
        }
        return $classes;
    }
}
