<?php
/**
 * Handles the registration and enqueuing of all scripts and styles.
 *
 * @package    Event_Monster
 * @subpackage Event_Monster/includes
 */
class Event_Monster_Free_Assets
{

    /**
     * The plugin version.
     * @var string
     */
    private $version;

    /**
     * Initialize the class.
     */
    public function __construct($version)
    {
        $this->version = $version;

        // Hook to enqueue scripts and styles for the frontend.
        add_action('wp_enqueue_scripts', array($this, 'enqueue_public_assets'));

        // Hook to enqueue scripts and styles for the admin area.
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    }

    /**
     * A central registry for all scripts.
     * This makes it easy to see all scripts and manage their properties.
     * @return array
     */
    private function get_registered_scripts()
    {
        return array(
            'em-bootstrap' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/js/bootstrap.min.js',
                'deps' => array('jquery'),
                'in_footer' => true,
            ),
            'em-datatables' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/js/jquery-data-tables.js',
                'deps' => array('jquery'),
                'in_footer' => true,
            ),
            'em-admin-ajax-tickets' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/js/em-ticket-ajax.js',
                'deps' => array('jquery'),
                'in_footer' => true,
            ),
            // Coupon AJAX JS removed (Pro-only feature)
            // ... Add ALL your other JS files here
        );
    }

    /**
     * A central registry for all styles.
     * @return array
     */
    private function get_registered_styles()
    {
        return array(
            // Admin styles
            'em-bootstrap' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/css/bootstrap.css',
                'deps' => array(),
            ),
            'em-datatables' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/css/jquery-data-tables.css',
                'deps' => array(),
            ),
            'em-admin-main' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/css/styles.css',
                'deps' => array('em-bootstrap'),
            ),
            'em-font-awesome' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/css/font-awesome.css',
                'deps' => array(),
            ),
            'em-tailwind' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/css/tailwind-output.css',
                'deps' => array(),
            ),

            // Frontend styles
            'em-frontend-bootstrap' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/css/event-bootstrap.css',
                'deps' => array(),
            ),
            'em-frontend-main' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/css/style-event-monster.css',
                'deps' => array('em-frontend-bootstrap', 'em-font-awesome'),
            ),
            'em-frontend-list' => array(
                'src' => EM_FREE_PLUGIN_URL . 'assets/css/em-list-styles.css',
                'deps' => array('em-frontend-main'),
            ),
        );
    }

    /**
     * Enqueue scripts and styles for the PUBLIC-facing side of the site.
     */
    public function enqueue_public_assets()
    {
        // Register all styles first
        foreach ($this->get_registered_styles() as $handle => $props) {
            wp_register_style($handle, $props['src'], $props['deps'], $this->version);
        }

        // Enqueue frontend assets when shortcode is used or on event pages
        if (is_singular('awl_event_monster') || $this->has_event_shortcode()) {
            // Core frontend styles with Tailwind
            wp_enqueue_style('em-tailwind');
            wp_enqueue_style('em-font-awesome');
            wp_enqueue_style('em-frontend-bootstrap');
            wp_enqueue_style('em-frontend-main');
            wp_enqueue_style('em-frontend-list');

            // Frontend scripts
            wp_enqueue_script('jquery');
            wp_enqueue_script('em-countdown-js', EM_FREE_PLUGIN_URL . 'count/jquery.classycountdown.js', array('jquery'), $this->version, true);
            wp_enqueue_script('em-owl-carousel', EM_FREE_PLUGIN_URL . 'assets/js/owl.carousel.min.js', array('jquery'), $this->version, true);
            wp_enqueue_script('em-isotope', EM_FREE_PLUGIN_URL . 'assets/js/isotope.pkgd.min.js', array('jquery'), $this->version, true);
            wp_enqueue_script('em-frontend-main', EM_FREE_PLUGIN_URL . 'assets/js/frontend.js', array('jquery'), $this->version, true);
        }
    }

    /**
     * Check if current page/post has event shortcode
     */
    private function has_event_shortcode()
    {
        global $post;
        if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'EM')) {
            return true;
        }
        return false;
    }

    /**
     * Enqueue scripts and styles for the ADMIN area.
     *
     * @param string $hook_suffix The current admin page.
     */
    public function enqueue_admin_assets($hook_suffix)
    {
        // CRITICAL FIX: Add jQuery UI focusable compatibility GLOBALLY for all admin pages
        // This prevents "is not focusable" errors from bootstrap components and WordPress validation
        // Must be added before any scripts are registered or enqueued
        $compatibility_script = "
        (function($) {
            // Comprehensive jQuery UI focusable polyfill
            // This fixes compatibility issues with Classic Editor and Bootstrap components

            if (typeof $.ui === 'undefined') {
                $.ui = {};
            }

            if (typeof $.ui.focusable === 'undefined') {
                $.ui.focusable = function(element, hasTabindex) {
                    var map, mapName, img,
                        nodeName = element.nodeName.toLowerCase();

                    if ('area' === nodeName) {
                        map = element.parentNode;
                        mapName = map.name;
                        if (!element.href || !mapName || map.nodeName.toLowerCase() !== 'map') {
                            return false;
                        }
                        img = $('img[usemap=\"#' + mapName + '\"]')[0];
                        return !!img && visible(img);
                    }

                    return (/^(input|select|textarea|button|object)$/.test(nodeName) ?
                        !element.disabled :
                        'a' === nodeName ?
                            element.href || hasTabindex :
                            hasTabindex) &&
                        visible(element);

                    function visible(element) {
                        return $.expr.pseudos.visible(element) &&
                            !$(element).parents().addBack().filter(function() {
                                return $.css(this, 'visibility') === 'hidden';
                            }).length;
                    }
                };
            }

            // Ensure $.expr and $.expr.pseudos exist
            if (typeof $.expr === 'undefined') {
                $.expr = {};
            }

            // Handle both old and new jQuery selector APIs
            if (typeof $.expr.pseudos === 'undefined') {
                if (typeof $.expr[':'] !== 'undefined') {
                    $.expr.pseudos = $.expr[':'];
                } else {
                    $.expr.pseudos = {};
                }
            }

            // Ensure :visible pseudo-selector exists (required by focusable)
            if (typeof $.expr.pseudos.visible === 'undefined') {
                $.expr.pseudos.visible = function(elem) {
                    return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
                };
            }

            // Add :focusable pseudo-selector
            if (typeof $.expr.pseudos.focusable === 'undefined') {
                $.expr.pseudos.focusable = function(element) {
                    var tabIndex = $.attr(element, 'tabindex'),
                        hasTabindex = tabIndex != null;
                    return $.ui.focusable(element, hasTabindex);
                };
            }

            // Also add to $.expr[':'] for older jQuery versions
            if (typeof $.expr[':'] !== 'undefined' && typeof $.expr[':'].focusable === 'undefined') {
                $.expr[':'].focusable = $.expr.pseudos.focusable;
            }
        })(jQuery);
        ";
        wp_add_inline_script('jquery', $compatibility_script, 'after');

        // First, let's register everything so WordPress knows about it.
        foreach ($this->get_registered_styles() as $handle => $props) {
            wp_register_style($handle, $props['src'], $props['deps'], $this->version);
        }
        foreach ($this->get_registered_scripts() as $handle => $props) {
            wp_register_script($handle, $props['src'], $props['deps'], $this->version, $props['in_footer']);
        }


        // Load assets ONLY on the page for adding/editing your 'event' post type.
        // =====================================================================
        if ('post.php' === $hook_suffix || 'post-new.php' === $hook_suffix) {
            global $post;
            if ($post && 'awl_event_monster' === $post->post_type) {
                wp_enqueue_style('wp-color-picker');
                wp_enqueue_script('wp-color-picker');

                // Enqueue all the specific styles from event-settings.php
                wp_enqueue_style('em-tailwind', EM_FREE_PLUGIN_URL . 'assets/css/tailwind-output.css', array(), $this->version);
                //wp_enqueue_style('awl-em-bootstrap-css', EM_FREE_PLUGIN_URL . 'assets/css/bootstrap.css');
                wp_enqueue_style('awl-em-activities-css', EM_FREE_PLUGIN_URL . 'assets/css/activities.css');
                //wp_enqueue_style('awl-em-styles-css', EM_FREE_PLUGIN_URL . 'assets/css/styles.css');

                //wp_enqueue_style('em-bootstrap-datepicker', EM_FREE_PLUGIN_URL . 'assets/css/bootstrap-datepicker.css', array(), $this->version);
                // wp_enqueue_style('em-bootstrap-clockpicker', EM_FREE_PLUGIN_URL . 'assets/css/bootstrap-clockpicker.css', array(), $this->version);
                // wp_enqueue_style('em-bootstrap-select', EM_FREE_PLUGIN_URL . 'assets/css/bootstrap-select.min.css', array(), $this->version);
                //  wp_enqueue_style('em-uploader-css', EM_FREE_PLUGIN_URL . 'assets/css/awl-em-uploader.css', array(), $this->version);

                // Enqueue Bootstrap JS (required for icon picker popover)
                wp_enqueue_script('awl-em-bootstrap-min-js', EM_FREE_PLUGIN_URL . 'assets/js/bootstrap.min.js', array('jquery'), EM_FREE_VERSION, true);

                // Enqueue FontAwesome (required for icon picker icons)
                wp_enqueue_style('em-font-awesome', EM_FREE_PLUGIN_URL . 'assets/css/font-awesome.css', array(), $this->version);

                // Enqueue Icon Picker CSS and JS
                wp_enqueue_style('em-bootstrap-iconpicker-css', EM_FREE_PLUGIN_URL . 'assets/css/bootstrap-iconpicker.min.css', array('em-font-awesome'), $this->version);
                wp_enqueue_style('em-iconpicker-fix-css', EM_FREE_PLUGIN_URL . 'assets/css/em-iconpicker-fix.css', array('em-bootstrap-iconpicker-css'), $this->version);
                wp_enqueue_script('em-iconset-all-js', EM_FREE_PLUGIN_URL . 'assets/js/iconset-all.min.js', array('jquery'), $this->version, true);
                wp_enqueue_script('em-bootstrap-iconpicker-js', EM_FREE_PLUGIN_URL . 'assets/js/bootstrap-iconpicker.min.js', array('jquery', 'awl-em-bootstrap-min-js', 'em-iconset-all-js'), $this->version, true);

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

                // Enqueue all the specific scripts from event-settings.php
                // wp_enqueue_script('em-bootstrap-datepicker-js', EM_FREE_PLUGIN_URL . 'assets/js/bootstrap-datepicker.js', array('jquery'), $this->version, true);
                //  wp_enqueue_script('em-bootstrap-clockpicker-js', EM_FREE_PLUGIN_URL . 'assets/js/bootstrap-clockpicker.js', array('jquery'), $this->version, true);
                // wp_enqueue_script('em-bootstrap-select-js', EM_FREE_PLUGIN_URL . 'assets/js/bootstrap-select.min.js', array('jquery'), $this->version, true);
                //   wp_enqueue_script('em-image-upload-js', EM_FREE_PLUGIN_URL . 'assets/js/em-image-upload.js', array('jquery', 'media-upload', 'thickbox'), $this->version, true);
                wp_enqueue_script('em-admin-metabox-js', EM_FREE_PLUGIN_URL . 'assets/js/em-admin-metabox.js', array('jquery', 'em-bootstrap-iconpicker-js'), $this->version, true);

                // Enqueue jQuery UI for layout builder drag and drop
                // IMPORTANT: Also enqueue jquery-ui-core to ensure jQuery UI utilities are available
                wp_enqueue_script('jquery-ui-core');
                wp_enqueue_script('jquery-ui-draggable');
                wp_enqueue_script('jquery-ui-droppable');
                wp_enqueue_script('jquery-ui-sortable');

                // Enqueue layout builder script
                wp_enqueue_script('em-layout-builder', EM_FREE_PLUGIN_URL . 'assets/js/layout-builder.js', array('jquery', 'jquery-ui-core', 'jquery-ui-draggable', 'jquery-ui-droppable', 'jquery-ui-sortable'), $this->version, true);

                wp_enqueue_script('em-shortcode-manager', EM_FREE_PLUGIN_URL . 'assets/js/em-shortcode-manager.js', array('jquery'), $this->version, true);

                // V-- ADD THIS NEW LOCALIZATION FOR THE NONCE --V
                wp_localize_script(
                    'em-shortcode-manager',
                    'em_shortcode_ajax_object',
                    array(
                        'ajax_url' => admin_url('admin-ajax.php'),
                        'get_nonce' => wp_create_nonce('em_get_shortcode_nonce'),
                    )
                );
            }
        }

        // Check if we are on the Settings page
        if ('awl_event_monster_page_em-setting-page' === $hook_suffix) {
            // Enqueue WordPress media library for logo upload
            wp_enqueue_media();

            // Enqueue Tailwind first as a dependency
            wp_enqueue_style('em-tailwind', EM_FREE_PLUGIN_URL . 'assets/css/tailwind-output.css', array(), $this->version);

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

            // Enqueue settings-specific assets
            wp_enqueue_script('em-settings-js', EM_FREE_PLUGIN_URL . 'assets/js/em-settings.js', array('jquery'), $this->version, true);
            wp_enqueue_style('em-settings-css', EM_FREE_PLUGIN_URL . 'assets/css/em-settings.css', array('em-tailwind'), $this->version);

             wp_localize_script(
                'jquery', // Use jQuery as the handle since it's always loaded
                'em_settings_ajax_object',
                array(
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'save_nonce' => wp_create_nonce('em_save_nonce'),
                )
            );
        }
        


        // Define which pages need which assets
        // 1. Define an array of all pages that use our custom data table.
        $table_pages = array(
            'awl_event_monster_page_em-visitors-page',
            'awl_event_monster_page_em-tickets-page',
            // Coupons and Payments pages removed (Pro-only feature)
        );

        // 2. Check if the current page is one of our table pages.
        if (in_array($hook_suffix, $table_pages)) {

            // --- Load all COMMON styles for the tables ---
            wp_enqueue_style('awl-em-bootstrap-css', EM_FREE_PLUGIN_URL . 'assets/css/bootstrap.css');
            // wp_enqueue_style('awl-em-styles-css', EM_FREE_PLUGIN_URL . 'assets/css/styles.css');
            wp_enqueue_style('awl-em-jquery-data-tables-css', EM_FREE_PLUGIN_URL . 'assets/css/jquery-data-tables.css');
            wp_enqueue_style('awl-em-font-awesome-css', EM_FREE_PLUGIN_URL . 'assets/css/font-awesome.css');
            wp_enqueue_style('awl-em-activities-css', EM_FREE_PLUGIN_URL . 'assets/css/activities.css');
            wp_enqueue_style('awl-em-event-monster-css', EM_FREE_PLUGIN_URL . 'assets/css/event_monster.css', array(), $this->version);

            // --- Load all COMMON scripts for the tables ---
            wp_enqueue_script('awl-em-bootstrap-min-js', EM_FREE_PLUGIN_URL . 'assets/js/bootstrap.min.js', array('jquery'), EM_FREE_VERSION, true);
            wp_enqueue_script('awl-em-jquery-data-tables-js', EM_FREE_PLUGIN_URL . 'assets/js/jquery-data-tables.js', array('jquery'), EM_FREE_VERSION, true);
            wp_enqueue_script('awl-em-tables-js', EM_FREE_PLUGIN_URL . 'assets/js/tables.js', array('jquery'), EM_FREE_VERSION, true);

            wp_enqueue_style('em-tailwind', EM_FREE_PLUGIN_URL . 'assets/css/tailwind-output.css', array(), $this->version);

        }


        // Check if we are on the Visitors page. The hook for this page is 'event-monster_page_em-visitors-page'
        if ('awl_event_monster_page_em-visitors-page' === $hook_suffix) {
            wp_enqueue_script('em-visitor-manager-js', EM_FREE_PLUGIN_URL . 'assets/js/em-visitor-manager.js', array('jquery'), EM_FREE_VERSION, true);
            wp_localize_script(
                'em-visitor-manager-js',
                'em_visitor_ajax_object',
                array(
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'delete_nonce' => wp_create_nonce('em_delete_visitor_nonce'),
                    'view_nonce' => wp_create_nonce('em_view_visitor_nonce'),
                    'status_nonce' => wp_create_nonce('em_update_status_nonce'),
                    'download_nonce' => wp_create_nonce('em-download-visitor-nonce'),
                    'delete_all_nonce' => wp_create_nonce('em_delete_all_visitor_nonce'),
                )
            );
        }

        if ('awl_event_monster_page_em-tickets-page' === $hook_suffix) {

            // Enqueue the new script for managing tickets
            wp_enqueue_script('em-ticket-manager', EM_FREE_PLUGIN_URL . 'assets/js/em-ticket-manager.js', array('jquery'), EM_FREE_VERSION, true);

            // Pass important PHP data to our new JavaScript file
            wp_localize_script(
                'em-ticket-manager',
                'em_ticket_ajax_object', // This will be our JavaScript object
                array(
                    'ajax_url' => admin_url('admin-ajax.php'),
                    'add_form_nonce' => wp_create_nonce('em_get_add_ticket_form_nonce'),
                    'add_nonce' => wp_create_nonce('em_add_ticket_nonce'),
                    'edit_nonce' => wp_create_nonce('em_edit_ticket_nonce'),
                    'delete_nonce' => wp_create_nonce('em_delete_ticket_nonce'),
                    'update_nonce' => wp_create_nonce('em_update_ticket_nonce'),
                )
            );
        }

        // Coupons page assets removed (Pro-only feature)

        // Payments page assets removed (Pro-only feature)

       
    }
}
