<?php
/**
 * Guard Dog Customizer Loader
 *
 * Handles loading of the customizer framework and implementations.
 *
 * @package GuardDog
 * @since 1.8.45
 */

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

class Guard_Dog_Customizer_Loader {

    /**
     * Initialize the customizer loader
     */
    public static function init() {
        // Load framework files
        self::load_framework();

        // Register admin menu
        add_action('admin_menu', [__CLASS__, 'register_admin_menu'], 20);

        // Enqueue assets for customizer pages
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_customizer_assets']);

        // Register AJAX handlers after WordPress init so customizer controls can
        // safely use translated labels without leaking early debug notices.
        add_action('admin_init', [__CLASS__, 'register_ajax_handlers'], 1);
    }

    /**
     * Load customizer framework files
     */
    private static function load_framework() {
        // Base classes
        require_once GUARD_DOG_PATH . 'includes/customizer/class-guard-dog-customizer.php';
        require_once GUARD_DOG_PATH . 'includes/customizer/class-guard-dog-customizer-control.php';

        // Load controls
        self::load_controls();

        // Load implementations
        self::load_implementations();
    }

    /**
     * Load all control types
     */
    private static function load_controls() {
        $controls_path = GUARD_DOG_PATH . 'includes/customizer/controls/';

        require_once $controls_path . 'class-color-control.php';
        require_once $controls_path . 'class-image-control.php';
        require_once $controls_path . 'class-text-control.php';
        require_once $controls_path . 'class-textarea-control.php';
        require_once $controls_path . 'class-number-control.php';
        require_once $controls_path . 'class-checkbox-control.php';

        // Allow plugins to load additional controls
        do_action('guard_dog_customizer_load_controls', $controls_path);
    }

    /**
     * Load customizer implementations
     */
    private static function load_implementations() {
        $implementations_path = GUARD_DOG_PATH . 'includes/customizer/implementations/';

        // Email template customizer
        require_once $implementations_path . 'class-email-template-customizer.php';

        // Access denied page customizer
        require_once $implementations_path . 'class-access-denied-customizer.php';

        // Login screen customizer
        require_once $implementations_path . 'class-login-screen-customizer.php';

        // Allow plugins to load additional customizers
        do_action('guard_dog_customizer_load_implementations', $implementations_path);
    }

    /**
     * Register admin menu items
     */
    public static function register_admin_menu() {
        // Email Template Customizer - hidden submenu page (accessed from Appearance hub)
        add_submenu_page(
            null, // Hidden from sidebar; navigated via Appearance page
            __('Email Templates', 'guard-dog'),
            __('Email Templates', 'guard-dog'),
            'manage_options',
            'guard-dog-email-customizer',
            ['Guard_Dog_Email_Template_Customizer', 'render_page']
        );

        // Access Denied Page Customizer - hidden submenu page (accessed from Appearance hub)
        add_submenu_page(
            null, // Hidden from sidebar; navigated via Appearance page
            __('Access Denied Page', 'guard-dog'),
            __('Access Denied Page', 'guard-dog'),
            'manage_options',
            'guard-dog-access-denied-customizer',
            ['Guard_Dog_Access_Denied_Customizer', 'render_page']
        );

        add_submenu_page(
            null, // Hidden from sidebar; navigated via Appearance page
            __('WordPress Login Screen', 'guard-dog'),
            __('WordPress Login Screen', 'guard-dog'),
            'manage_options',
            'guard-dog-login-customizer',
            ['Guard_Dog_Login_Screen_Customizer', 'render_page']
        );
    }

    /**
     * Enqueue assets for customizer pages
     *
     * @param string $hook Current admin page hook
     */
    public static function enqueue_customizer_assets($hook) {
        // Check if we're on a customizer page
        $customizer_pages = [
            'admin_page_guard-dog-email-customizer',
            'admin_page_guard-dog-access-denied-customizer',
            'admin_page_guard-dog-login-customizer',
        ];

        if (!in_array($hook, $customizer_pages)) {
            return;
        }

        // Enqueue customizer CSS
        wp_enqueue_style(
            'guard-dog-customizer',
            GUARD_DOG_URL . 'assets/css/guard-dog-customizer.css',
            [],
            GUARD_DOG_VERSION
        );

        // Enqueue WordPress color picker
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');

        // Enqueue WordPress media library
        wp_enqueue_media();

        // Enqueue customizer JS
        wp_enqueue_script(
            'guard-dog-customizer',
            GUARD_DOG_URL . 'assets/js/guard-dog-customizer.js',
            ['jquery', 'wp-color-picker'],
            GUARD_DOG_VERSION,
            true
        );

        // Determine which customizer we're on and get its settings
        $customizer_id = '';
        $nonces = [];

        if ($hook === 'admin_page_guard-dog-email-customizer') {
            $customizer_id = 'email_template';
            $nonces = [
                'preview' => wp_create_nonce('guard_dog_customizer_preview_email_template'),
                'save' => wp_create_nonce('guard_dog_customizer_save_email_template'),
                'reset' => wp_create_nonce('guard_dog_customizer_reset_email_template'),
                'export' => wp_create_nonce('guard_dog_customizer_export_email_template'),
                'test_email' => wp_create_nonce('guard_dog_send_test_email'),
            ];
        } elseif ($hook === 'admin_page_guard-dog-access-denied-customizer') {
            $customizer_id = 'access_denied';
            $nonces = [
                'preview' => wp_create_nonce('guard_dog_customizer_preview_access_denied'),
                'save' => wp_create_nonce('guard_dog_customizer_save_access_denied'),
                'reset' => wp_create_nonce('guard_dog_customizer_reset_access_denied'),
                'export' => wp_create_nonce('guard_dog_customizer_export_access_denied'),
            ];
        } elseif ($hook === 'admin_page_guard-dog-login-customizer') {
            $customizer_id = 'login_screen';
            $nonces = [
                'preview' => wp_create_nonce('guard_dog_customizer_preview_login_screen'),
                'save' => wp_create_nonce('guard_dog_customizer_save_login_screen'),
                'reset' => wp_create_nonce('guard_dog_customizer_reset_login_screen'),
                'export' => wp_create_nonce('guard_dog_customizer_export_login_screen'),
            ];
        }

        // Localize script with customizer-specific data
        wp_localize_script('guard-dog-customizer', 'guardDogCustomizer', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'customizerId' => $customizer_id,
            'nonces' => $nonces,
            'strings' => [
                'saving' => __('Saving...', 'guard-dog'),
                'saved' => __('Settings saved!', 'guard-dog'),
                'saveFailed' => __('Failed to save settings.', 'guard-dog'),
                'resetConfirm' => __('Are you sure you want to reset all settings to defaults? This cannot be undone.', 'guard-dog'),
                'resetting' => __('Resetting...', 'guard-dog'),
                'resetComplete' => __('Settings reset to defaults.', 'guard-dog'),
                'exportSuccess' => __('Template exported successfully!', 'guard-dog'),
                'exportFailed' => __('Failed to export template.', 'guard-dog'),
            ],
        ]);
    }

    /**
     * Register AJAX handlers for all customizers
     *
     * This must be done early, before any AJAX requests are processed,
     * because AJAX requests don't trigger page rendering where customizer
     * instances would normally be created.
     */
    public static function register_ajax_handlers() {
        // Only register on admin or AJAX requests
        if (!is_admin()) {
            return;
        }

        // Email Template Customizer AJAX handlers
        if (class_exists('Guard_Dog_Email_Template_Customizer')) {
            $email_customizer = new Guard_Dog_Email_Template_Customizer();
            // The constructor calls init_hooks() which registers AJAX actions
        }

        // Access Denied Customizer AJAX handlers
        if (class_exists('Guard_Dog_Access_Denied_Customizer')) {
            $access_denied_customizer = new Guard_Dog_Access_Denied_Customizer();
            // The constructor calls init_hooks() which registers AJAX actions
        }

        // Login Screen Customizer AJAX handlers
        if (class_exists('Guard_Dog_Login_Screen_Customizer')) {
            $login_screen_customizer = new Guard_Dog_Login_Screen_Customizer();
            // The constructor calls init_hooks() which registers AJAX actions
        }
    }

    /**
     * Check if customizer is available
     *
     * @return bool
     */
    public static function is_available() {
        return class_exists('Guard_Dog_Customizer');
    }

    /**
     * Get available customizers
     *
     * @return array Array of customizer class names
     */
    public static function get_available_customizers() {
        $customizers = [
            'email_template' => 'Guard_Dog_Email_Template_Customizer',
            'access_denied' => 'Guard_Dog_Access_Denied_Customizer',
            'login_screen' => 'Guard_Dog_Login_Screen_Customizer',
        ];

        return apply_filters('guard_dog_available_customizers', $customizers);
    }
}
