<?php
/**
 * HVAC Find Trainer Assets Manager
 * 
 * Handles script and style loading for find-a-trainer page with Safari compatibility
 *
 * @package HVAC_Community_Events
 * @since 1.0.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * HVAC Find Trainer Assets Manager
 */
class HVAC_Find_Trainer_Assets {
    
    /**
     * Instance
     *
     * @var HVAC_Find_Trainer_Assets
     */
    private static $instance = null;
    
    /**
     * Browser detection service
     *
     * @var HVAC_Browser_Detection
     */
    private $browser_detection;
    
    /**
     * Get instance
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        $this->browser_detection = HVAC_Browser_Detection::instance();
        $this->init_hooks();
    }
    
    /**
     * Initialize WordPress hooks
     */
    private function init_hooks() {
        // Use proper WordPress hook system
        add_action('wp_enqueue_scripts', [$this, 'enqueue_find_trainer_assets']);
        add_action('wp_footer', [$this, 'add_find_trainer_inline_scripts']);
    }

    
    /**
     * Check if current page is find-a-trainer
     * 
     * @return bool
     */
    private function is_find_trainer_page() {
        return is_page('find-a-trainer') || 
               strpos($_SERVER['REQUEST_URI'], 'find-a-trainer') !== false ||
               (defined('HVAC_IN_PAGE_TEMPLATE') && get_page_template_slug() === 'page-find-trainer.php');
    }
    
    /**
     * Enqueue find trainer assets with Safari compatibility
     */
    public function enqueue_find_trainer_assets() {
        // FIXED: Always load assets for find-trainer functionality
        // Safari compatibility is handled by selecting appropriate script version
        // Removed HVAC_SAFARI_MINIMAL_MODE check that was preventing asset loading
        
        // Only load on find-a-trainer page
        if (!$this->is_find_trainer_page()) {
            return;
        }
        
        // Enqueue CSS
        wp_enqueue_style(
            'hvac-find-trainer',
            HVAC_PLUGIN_URL . 'assets/css/find-trainer.css',
            [],
            HVAC_VERSION
        );
        
        wp_enqueue_style('dashicons');
        
        // Enqueue JavaScript with Safari compatibility
        $this->enqueue_compatible_script();
        
        // Handle direct profile display
        $this->handle_profile_sharing_assets();
        
        // Localize script with data
        $this->localize_find_trainer_script();
        
        // Debug logging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $browser_info = $this->browser_detection->get_browser_info();
            error_log('[HVAC Find Trainer Assets] Page detected, assets enqueued. Browser: ' . json_encode($browser_info));
        }
    }
    
    /**
     * Enqueue Safari-compatible JavaScript
     */
    private function enqueue_compatible_script() {
        $script_handle = 'hvac-find-trainer';
        $script_url = $this->get_compatible_script_url();
        
        wp_enqueue_script(
            $script_handle,
            $script_url,
            ['jquery'],
            HVAC_VERSION,
            true
        );
        
        // Debug logging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('[HVAC Find Trainer Assets] Script enqueued: ' . $script_url);
        }
    }
    
    /**
     * Get compatible script URL based on browser
     * 
     * @return string Script URL
     */
    private function get_compatible_script_url() {
        // ALWAYS use Safari-compatible script for ALL Safari versions
        // Modern Safari (18.5+) still has issues with complex DOM operations and third-party script conflicts
        if ($this->browser_detection->is_safari_browser()) {
            $safari_script = HVAC_PLUGIN_DIR . 'assets/js/find-trainer-safari-compatible.js';
            if (file_exists($safari_script)) {
                error_log('[HVAC Find Trainer Assets] Loading Safari-compatible script for Safari version: ' . $this->browser_detection->get_safari_version());
                return HVAC_PLUGIN_URL . 'assets/js/find-trainer-safari-compatible.js';
            }
        }
        
        // Default to standard ES6+ script for non-Safari browsers
        return HVAC_PLUGIN_URL . 'assets/js/find-trainer.js';
    }
    
    /**
     * Handle profile sharing assets for direct profile display
     */
    private function handle_profile_sharing_assets() {
        // Check if showing direct profile (from URL parameter or global)
        $show_direct_profile = false;
        
        if (isset($GLOBALS['hvac_show_direct_profile']) && $GLOBALS['hvac_show_direct_profile']) {
            $show_direct_profile = true;
        } elseif (isset($_GET['profile']) || strpos($_SERVER['REQUEST_URI'], '/profile/') !== false) {
            $show_direct_profile = true;
        }
        
        if ($show_direct_profile) {
            wp_enqueue_style(
                'hvac-profile-sharing',
                HVAC_PLUGIN_URL . 'assets/css/hvac-profile-sharing.css',
                ['hvac-find-trainer'],
                HVAC_VERSION
            );
            
            wp_enqueue_script(
                'hvac-profile-sharing',
                HVAC_PLUGIN_URL . 'assets/js/hvac-profile-sharing.js',
                ['jquery', 'hvac-find-trainer'],
                HVAC_VERSION,
                true
            );
            
            // Localize profile sharing script
            wp_localize_script('hvac-profile-sharing', 'hvac_sharing', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('hvac_profile_sharing'),
                'profile_id' => isset($_GET['profile']) ? intval($_GET['profile']) : 0
            ]);
        }
    }
    
    /**
     * Localize find trainer script with necessary data
     */
    private function localize_find_trainer_script() {
        // Get direct profile data if available
        $direct_profile_id = null;
        $show_direct_profile = false;
        
        if (class_exists('HVAC_QR_Generator')) {
            $qr_generator = HVAC_QR_Generator::instance();
            $direct_profile_id = $qr_generator->parse_profile_id_from_url();
            $show_direct_profile = !empty($direct_profile_id);
        }
        
        wp_localize_script('hvac-find-trainer', 'hvac_find_trainer', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_find_trainer'),
            'map_id' => '5872',
            'direct_profile_id' => $direct_profile_id,
            'show_direct_profile' => $show_direct_profile,
            'browser_info' => $this->browser_detection->get_browser_info(),
            'messages' => [
                'loading' => __('Loading...', 'hvac'),
                'error' => __('An error occurred. Please try again.', 'hvac'),
                'no_results' => __('No trainers found matching your criteria.', 'hvac'),
                'form_error' => __('Please check the form and try again.', 'hvac'),
                'form_success' => __('Your message has been sent! Check your inbox for more details.', 'hvac')
            ]
        ]);
    }
    
    /**
     * Add inline scripts in footer for MapGeo integration
     */
    public function add_find_trainer_inline_scripts() {
        if (!$this->is_find_trainer_page()) {
            return;
        }
        
        // Only add MapGeo integration if not showing direct profile
        $show_direct_profile = isset($GLOBALS['hvac_show_direct_profile']) && $GLOBALS['hvac_show_direct_profile'];
        
        if (!$show_direct_profile) {
            ?>
            <script type="text/javascript">
            // MapGeo Integration - Early Handler for Compatibility
            window.hvacPendingModalCalls = [];
            
            // Early function to queue calls before main script loads
            window.hvacShowTrainerModal = function(data) {
                console.log('MapGeo call queued:', data);
                window.hvacPendingModalCalls.push(data);
            };
            </script>
            <?php
        }
    }
    
    /**
     * Get browser compatibility info for debugging
     * 
     * @return array
     */
    public function get_compatibility_info() {
        return [
            'is_find_trainer_page' => $this->is_find_trainer_page(),
            'script_url' => $this->get_compatible_script_url(),
            'browser_info' => $this->browser_detection->get_browser_info(),
        ];
    }
}