<?php
/**
 * Main Plugin Class for HVAC Community Events
 *
 * @package HVAC_Community_Events
 * @since 1.0.0
 */

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

/**
 * HVAC_Plugin class
 */
class HVAC_Plugin {
    
    /**
     * Plugin instance
     * 
     * @var HVAC_Plugin
     */
    private static $instance = null;
    
    /**
     * Get plugin instance
     * 
     * @return HVAC_Plugin
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        $this->define_constants();
        $this->includes();
        $this->init_hooks();
        
        // Initialize Astra theme integration if Astra is active
        add_action('after_setup_theme', function() {
            if (defined('ASTRA_THEME_VERSION')) {
                require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-astra-integration.php';
            }
        });
    }
    
    /**
     * Define plugin constants
     * 
     * @return void
     */
    private function define_constants() {
        if (!defined('HVAC_PLUGIN_VERSION')) {
            define('HVAC_PLUGIN_VERSION', '2.0.0');
        }
        if (!defined('HVAC_VERSION')) {
            define('HVAC_VERSION', '2.0.0');
        }
        if (!defined('HVAC_PLUGIN_FILE')) {
            define('HVAC_PLUGIN_FILE', dirname(__DIR__) . '/hvac-community-events.php');
        }
        if (!defined('HVAC_PLUGIN_DIR')) {
            define('HVAC_PLUGIN_DIR', plugin_dir_path(HVAC_PLUGIN_FILE));
        }
        if (!defined('HVAC_PLUGIN_URL')) {
            define('HVAC_PLUGIN_URL', plugin_dir_url(HVAC_PLUGIN_FILE));
        }
        if (!defined('HVAC_PLUGIN_BASENAME')) {
            define('HVAC_PLUGIN_BASENAME', plugin_basename(HVAC_PLUGIN_FILE));
        }
    }
    
    /**
     * Include required files
     * 
     * @return void
     */
    private function includes() {
        // Safari request debugger - load first to catch all requests
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-safari-request-debugger.php';
        
        // Safari script blocker - DISABLED (was causing Safari hanging issues)
        // require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-safari-script-blocker.php';
        
        // Core includes
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-logger.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-activator.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-deactivator.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-page-manager.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-template-loader.php';
        // DISABLED - Using TEC Community Events 5.x instead
        // require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-community-events.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-secure-storage.php';
        
        // Check which roles manager exists
        if (file_exists(HVAC_PLUGIN_DIR . 'includes/class-hvac-roles-manager.php')) {
            require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-roles-manager.php';
        } elseif (file_exists(HVAC_PLUGIN_DIR . 'includes/class-hvac-roles.php')) {
            require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-roles.php';
        }
        
        // Core architecture includes
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-browser-detection.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-find-trainer-assets.php';
        
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-safari-debugger.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-shortcodes.php';
        // DISABLED - Using TEC Community Events 5.x instead
        // require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-edit-event-shortcode.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-scripts-styles.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-route-manager.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-menu-system.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-role-consolidator.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-welcome-popup.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-background-jobs.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-query-monitor.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-health-monitor.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-error-recovery.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-security-monitor.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-performance-monitor.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-backup-manager.php';
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-cache-optimizer.php';
        
        // TEC Integration - Load early for proper routing
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-tec-integration.php';
        
        // Event Edit Fixes for TEC Community Events
        if (file_exists(HVAC_PLUGIN_DIR . 'includes/class-hvac-event-edit-fix.php')) {
            require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-event-edit-fix.php';
        }
        if (file_exists(HVAC_PLUGIN_DIR . 'includes/class-hvac-event-edit-comprehensive.php')) {
            require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-event-edit-comprehensive.php';
        }
        
        // Custom Event Edit Form (PHP-based, no JavaScript dependencies)
        if (file_exists(HVAC_PLUGIN_DIR . 'includes/class-hvac-custom-event-edit.php')) {
            require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-custom-event-edit.php';
        }
        
        // Feature includes - check if files exist before including
        $feature_includes = [
            'class-hvac-trainer-status.php',
            'class-hvac-access-control.php',
            'class-hvac-registration.php',
            'class-hvac-venues.php',
            'class-hvac-trainer-profile-manager.php',
            'class-hvac-profile-sync-handler.php',
            'class-hvac-geocoding-service.php',
            'class-hvac-trainer-profile-settings.php',
            'class-hvac-geocoding-ajax.php',
            'class-hvac-qr-generator.php',
            'class-hvac-organizers.php',
            'class-hvac-trainer-navigation.php',
            'class-hvac-breadcrumbs.php',
            'class-hvac-template-integration.php',
            'class-hvac-training-leads.php',
            // DISABLED - Using TEC Community Events 5.x instead
            // 'class-hvac-manage-event.php',
            // 'class-hvac-event-edit-fix.php',
            // 'class-hvac-event-edit-comprehensive.php',
            // 'class-hvac-event-summary.php',
            'class-hvac-trainer-profile.php',
            'class-hvac-master-dashboard.php',
            'class-hvac-master-dashboard-data.php',
            'class-hvac-settings.php',
            'class-hvac-dashboard.php',
            'class-hvac-dashboard-data.php',
            'class-hvac-approval-workflow.php',
            'class-hvac-event-navigation.php',
            'class-hvac-event-manage-header.php',
            'class-hvac-help-system.php',
            'class-hvac-documentation-content.php',
            'class-event-form-handler.php',
            'class-event-author-fixer.php',
            'class-attendee-profile.php',
            'class-hvac-page-content-fixer.php',
        ];
        
        // Find a Trainer feature includes
        $find_trainer_includes = [
            'database/class-hvac-contact-submissions-table.php',
            'find-trainer/class-hvac-find-trainer-page.php',
            'find-trainer/class-hvac-mapgeo-integration.php',
            'find-trainer/class-hvac-contact-form-handler.php',
            'find-trainer/class-hvac-trainer-directory-query.php',
        ];
        
        foreach ($feature_includes as $file) {
            $file_path = HVAC_PLUGIN_DIR . 'includes/' . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }
        
        // Include Find a Trainer feature files
        foreach ($find_trainer_includes as $file) {
            $file_path = HVAC_PLUGIN_DIR . 'includes/' . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }
        
        // Community includes
        if (file_exists(HVAC_PLUGIN_DIR . 'includes/community/class-login-handler.php')) {
            require_once HVAC_PLUGIN_DIR . 'includes/community/class-login-handler.php';
            // Initialize Login_Handler to register shortcode
            new \HVAC_Community_Events\Community\Login_Handler();
        }
        if (file_exists(HVAC_PLUGIN_DIR . 'includes/community/class-event-handler.php')) {
            require_once HVAC_PLUGIN_DIR . 'includes/community/class-event-handler.php';
        }
        
        // Certificate system
        $certificate_files = [
            'certificates/class-certificate-security.php',
            'certificates/class-certificate-installer.php',
            'certificates/class-certificate-manager.php',
            'certificates/class-certificate-generator.php',
            'certificates/class-certificate-url-handler.php',
        ];
        
        foreach ($certificate_files as $file) {
            $file_path = HVAC_PLUGIN_DIR . 'includes/' . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }
        
        // Admin includes
        $admin_files = [
            'admin/class-zoho-admin.php',
            'admin/class-admin-dashboard.php',
            'admin/class-hvac-enhanced-settings.php',
        ];
        
        foreach ($admin_files as $file) {
            $file_path = HVAC_PLUGIN_DIR . 'includes/' . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }
        
        // Google Sheets integration
        $google_files = [
            'google-sheets/class-google-sheets-auth.php',
            'google-sheets/class-google-sheets-admin.php',
        ];
        
        foreach ($google_files as $file) {
            $file_path = HVAC_PLUGIN_DIR . 'includes/' . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }
        
        // Communication system
        $communication_files = [
            'communication/class-communication-installer.php',
            'communication/class-communication-scheduler.php',
            'communication/class-communication-templates.php',
        ];
        
        foreach ($communication_files as $file) {
            $file_path = HVAC_PLUGIN_DIR . 'includes/' . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }
        
        // Helper includes
        if (file_exists(HVAC_PLUGIN_DIR . 'includes/helpers/attendee-profile-link.php')) {
            require_once HVAC_PLUGIN_DIR . 'includes/helpers/attendee-profile-link.php';
        }
        
        // Legacy support
        $this->include_legacy_files();
    }
    
    /**
     * Include legacy files for backward compatibility
     * 
     * @return void
     */
    private function include_legacy_files() {
        // Include legacy functions if they exist
        $legacy_files = [
            'includes/hvac-ce-functions.php',
            'includes/hvac-ce-admin.php',
            'includes/hvac-ce-certificates.php'
        ];
        
        foreach ($legacy_files as $file) {
            $file_path = HVAC_PLUGIN_DIR . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }
    }
    
    /**
     * Initialize hooks
     * 
     * @return void
     */
    private function init_hooks() {
        // Activation/Deactivation hooks
        register_activation_hook(HVAC_PLUGIN_FILE, [$this, 'activate']);
        register_deactivation_hook(HVAC_PLUGIN_FILE, [$this, 'deactivate']);
        
        // Init hook
        add_action('init', [$this, 'init'], 0);
        
        // Plugin loaded
        add_action('plugins_loaded', [$this, 'plugins_loaded']);
        
        // Admin init
        add_action('admin_init', [$this, 'admin_init']);
        add_action('admin_menu', [$this, 'add_admin_menus']);
        
        // Initialize Find a Trainer feature
        add_action('init', [$this, 'initialize_find_trainer'], 20);
        
        // AJAX handlers
        add_action('wp_ajax_hvac_master_dashboard_events', [$this, 'ajax_master_dashboard_events']);
        add_action('wp_ajax_nopriv_hvac_master_dashboard_events', [$this, 'ajax_master_dashboard_events']);
        
        // Safari debugging AJAX handler
        add_action('wp_ajax_hvac_safari_debug', [$this, 'ajax_safari_debug']);
        add_action('wp_ajax_nopriv_hvac_safari_debug', [$this, 'ajax_safari_debug']);
        
        // Theme integration filters
        add_filter('body_class', [$this, 'add_hvac_body_classes']);
        add_filter('post_class', [$this, 'add_hvac_post_classes']);
        
        // Astra theme specific filters for layout
        add_filter('astra_page_layout', [$this, 'force_full_width_layout']);
        add_filter('astra_get_content_layout', [$this, 'force_full_width_layout']);
        
        // Admin action to manually update pages
        add_action('admin_init', [$this, 'check_for_page_updates']);
        
        // Check if pages need update after activation
        add_action('init', [$this, 'check_page_update_flag'], 99);
    }
    
    /**
     * Plugin activation
     * 
     * @return void
     */
    public function activate() {
        HVAC_Activator::activate();
    }
    
    /**
     * Plugin deactivation
     * 
     * @return void
     */
    public function deactivate() {
        HVAC_Deactivator::deactivate();
    }
    
    /**
     * Init hook
     * 
     * @return void
     */
    public function init() {
        // Initialize core architecture components
        HVAC_Shortcodes::instance();
        HVAC_Scripts_Styles::instance();
        HVAC_Find_Trainer_Assets::instance();
        HVAC_Safari_Debugger::instance();
        HVAC_Route_Manager::instance();
        
        // Initialize template loader
        HVAC_Template_Loader::init();
        
        // Initialize access control
        new HVAC_Access_Control();
        
        // TEMPORARILY DISABLED - troubleshooting segfaults
        // Initialize background job system
        // HVAC_Background_Jobs::init();
        
        // Initialize query monitoring
        HVAC_Query_Monitor::init();
        
        // Initialize health monitoring
        // HVAC_Health_Monitor::init();
        
        // Initialize error recovery system
        // HVAC_Error_Recovery::init();
        
        // Initialize security monitoring
        // HVAC_Security_Monitor::init();
        
        // Initialize performance monitoring
        // HVAC_Performance_Monitor::init();
        
        // Initialize backup management
        // HVAC_Backup_Manager::init();
        
        // Initialize cache optimization
        // HVAC_Cache_Optimizer::init();
        
        // Initialize other components
        $this->init_components();
        
        // Ensure registration page access
        add_action('template_redirect', [$this, 'ensure_registration_access'], 5);
    }
    
    /**
     * Initialize plugin components with lazy loading to prevent Safari cascade overload
     * Components are loaded on-demand rather than all at init to prevent browser hanging
     * 
     * @return void
     */
    private function init_components() {
        // Initialize only critical core components immediately
        if (class_exists('HVAC_Community_Events')) {
            // DISABLED - Using TEC Community Events 5.x instead
            // HVAC_Community_Events::instance();
        }
        
        // Schedule non-critical components for lazy loading
        add_action('wp_loaded', [$this, 'init_secondary_components'], 5);
        add_action('admin_init', [$this, 'init_admin_components'], 5);
    }
    
    /**
     * Initialize secondary components with lazy loading (wp_loaded hook)
     * This prevents Safari cascade overload by spreading initialization
     * 
     * @return void
     */
    public function init_secondary_components() {
        // Initialize registration if class exists
        if (class_exists('HVAC_Registration')) {
            new HVAC_Registration();
        }
        
        // Initialize venues management
        if (class_exists('HVAC_Venues')) {
            new HVAC_Venues();
        }
        
        // Initialize trainer profile manager
        if (class_exists('HVAC_Trainer_Profile_Manager')) {
            HVAC_Trainer_Profile_Manager::get_instance();
        }
        
        // Initialize profile sync handler
        if (class_exists('HVAC_Profile_Sync_Handler')) {
            HVAC_Profile_Sync_Handler::get_instance();
        }
        
        // Initialize geocoding service
        if (class_exists('HVAC_Geocoding_Service')) {
            HVAC_Geocoding_Service::get_instance();
        }
        
        // Initialize trainer profile settings
        if (class_exists('HVAC_Trainer_Profile_Settings')) {
            HVAC_Trainer_Profile_Settings::get_instance();
        }
        
        // Initialize organizers management
        if (class_exists('HVAC_Organizers')) {
            new HVAC_Organizers();
        }
        
        // Initialize training leads management
        if (class_exists('HVAC_Training_Leads')) {
            HVAC_Training_Leads::get_instance();
        }
        
        // REMOVED: HVAC_Trainer_Navigation - Using HVAC_Menu_System as single navigation system
        
        // Initialize breadcrumbs
        if (class_exists('HVAC_Breadcrumbs')) {
            new HVAC_Breadcrumbs();
        }
        
        // Initialize event management
        if (class_exists('HVAC_Manage_Event')) {
            new HVAC_Manage_Event();
        }
        if (class_exists('HVAC_Event_Summary')) {
            new HVAC_Event_Summary();
        }
        
        // Initialize event edit field population fixes
        if (class_exists('HVAC_Event_Edit_Fix')) {
            HVAC_Event_Edit_Fix::instance();
        }
        if (class_exists('HVAC_Event_Edit_Comprehensive')) {
            HVAC_Event_Edit_Comprehensive::instance();
        }
        
        // Initialize custom event edit form (PHP-based solution)
        if (class_exists('HVAC_Custom_Event_Edit')) {
            HVAC_Custom_Event_Edit::instance();
        }
        
        // Initialize trainer profile
        if (class_exists('HVAC_Trainer_Profile')) {
            new HVAC_Trainer_Profile();
        }
        
        // Initialize dashboards
        if (class_exists('HVAC_Dashboard')) {
            new HVAC_Dashboard();
        }
        if (class_exists('HVAC_Master_Dashboard')) {
            new HVAC_Master_Dashboard();
        }
        
        // Initialize settings
        if (class_exists('HVAC_Settings')) {
            new HVAC_Settings();
        }
        
        // Initialize approval workflow
        if (class_exists('HVAC_Approval_Workflow')) {
            new HVAC_Approval_Workflow();
        }
        
        // Initialize event navigation
        if (class_exists('HVAC_Event_Navigation')) {
            new HVAC_Event_Navigation();
        }
        
        // Initialize help system
        if (class_exists('HVAC_Help_System')) {
            HVAC_Help_System::instance();
        }
        
        // Initialize certificate security
        if (class_exists('HVAC_Certificate_Security')) {
            HVAC_Certificate_Security::instance();
        }
        
        // Initialize certificate URL handler
        if (class_exists('HVAC_Certificate_URL_Handler')) {
            HVAC_Certificate_URL_Handler::instance();
        }
        
        // Initialize attendee profile
        if (class_exists('HVAC_Attendee_Profile')) {
            HVAC_Attendee_Profile::instance();
        }
        
        // Initialize Google Sheets
        if (class_exists('HVAC_Google_Sheets_Auth')) {
            new HVAC_Google_Sheets_Auth();
        }
        if (class_exists('HVAC_Google_Sheets_Admin')) {
            new HVAC_Google_Sheets_Admin();
        }
        
        // Initialize communication system
        if (class_exists('HVAC_Communication_Installer')) {
            HVAC_Communication_Installer::maybe_update();
        }
        if (class_exists('HVAC_Communication_Scheduler')) {
            hvac_communication_scheduler();
        }
    }
    
    /**
     * Initialize admin components separately (admin_init hook)
     * Prevents loading admin components on frontend
     * 
     * @return void
     */
    public function init_admin_components() {
        // Initialize admin components only when needed
        if (class_exists('HVAC_Zoho_Admin')) {
            HVAC_Zoho_Admin::instance();
        }
        if (class_exists('HVAC_Admin_Dashboard')) {
            new HVAC_Admin_Dashboard();
        }
        if (class_exists('HVAC_Enhanced_Settings')) {
            HVAC_Enhanced_Settings::instance();
        }
    }
    
    /**
     * Initialize Find a Trainer feature
     * 
     * @return void
     */
    public function initialize_find_trainer() {
        // Initialize Find a Trainer page
        if (class_exists('HVAC_Find_Trainer_Page')) {
            HVAC_Find_Trainer_Page::get_instance();
        }
        
        // Initialize MapGeo integration
        if (class_exists('HVAC_MapGeo_Integration')) {
            HVAC_MapGeo_Integration::get_instance();
        }
        
        // Initialize contact form handler
        if (class_exists('HVAC_Contact_Form_Handler')) {
            HVAC_Contact_Form_Handler::get_instance();
        }
        
        // Initialize trainer directory query
        if (class_exists('HVAC_Trainer_Directory_Query')) {
            HVAC_Trainer_Directory_Query::get_instance();
        }
    }
    
    /**
     * Plugins loaded hook
     * 
     * @return void
     */
    public function plugins_loaded() {
        // Load text domain
        load_plugin_textdomain('hvac-community-events', false, dirname(HVAC_PLUGIN_BASENAME) . '/languages');
    }
    
    /**
     * Admin init hook
     * 
     * @return void
     */
    public function admin_init() {
        // Check for plugin updates
        $this->check_plugin_updates();
    }
    
    /**
     * Add admin menu items
     * 
     * @return void
     */
    public function add_admin_menus() {
        // Add event seeder page
        add_submenu_page(
            'tools.php',  // Parent menu
            'HVAC Event Seeder',  // Page title
            'HVAC Event Seeder',  // Menu title
            'manage_options',  // Capability
            'hvac-seed-events',  // Menu slug
            [$this, 'render_seed_events_page']  // Callback
        );
    }
    
    /**
     * Render the seed events admin page
     * 
     * @return void
     */
    public function render_seed_events_page() {
        require_once HVAC_PLUGIN_DIR . 'admin/seed-events-direct.php';
    }
    
    
    
    /**
     * Check for plugin updates
     * 
     * @return void
     */
    private function check_plugin_updates() {
        $current_version = get_option('hvac_plugin_version', '0.0.0');
        
        if (version_compare($current_version, HVAC_PLUGIN_VERSION, '<')) {
            // Run upgrade routines
            $this->upgrade($current_version);
            
            // Update version
            update_option('hvac_plugin_version', HVAC_PLUGIN_VERSION);
        }
    }
    
    /**
     * Run upgrade routines
     * 
     * @param string $from_version Version upgrading from
     * @return void
     */
    private function upgrade($from_version) {
        HVAC_Logger::info("Upgrading from version {$from_version} to " . HVAC_PLUGIN_VERSION, 'Upgrade');
        
        // Version-specific upgrades can be added here
    }
    
    
    /**
     * Ensure trainer registration page is publicly accessible
     * 
     * @return void
     */
    public function ensure_registration_access() {
        // If we're on the trainer registration page, don't apply any authentication checks
        if (is_page('trainer/registration')) {
            // Remove any potential authentication hooks that might be added by other code
            remove_all_actions('template_redirect', 10);
        }
    }
    
    /**
     * Handle AJAX request for master dashboard events table
     * 
     * @return void
     */
    public function ajax_master_dashboard_events() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'hvac_master_dashboard_nonce')) {
            wp_die('Security check failed');
        }
        
        // Check permissions
        if (!current_user_can('view_master_dashboard') && !current_user_can('view_all_trainer_data') && !current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        // Load master dashboard data class if needed
        if (!class_exists('HVAC_Master_Dashboard_Data')) {
            $data_file = HVAC_PLUGIN_DIR . 'includes/class-hvac-master-dashboard-data.php';
            if (file_exists($data_file)) {
                require_once $data_file;
            }
        }
        
        if (!class_exists('HVAC_Master_Dashboard_Data')) {
            wp_send_json_error('Master dashboard data class not found');
        }
        
        // Initialize data handler
        $master_data = new HVAC_Master_Dashboard_Data();
        
        // Get table data with filters
        $args = array(
            'status' => sanitize_text_field($_POST['status'] ?? 'all'),
            'search' => sanitize_text_field($_POST['search'] ?? ''),
            'orderby' => sanitize_text_field($_POST['orderby'] ?? 'date'),
            'order' => sanitize_text_field($_POST['order'] ?? 'DESC'),
            'page' => absint($_POST['page'] ?? 1),
            'per_page' => absint($_POST['per_page'] ?? 10),
            'date_from' => sanitize_text_field($_POST['date_from'] ?? ''),
            'date_to' => sanitize_text_field($_POST['date_to'] ?? ''),
            'trainer_id' => absint($_POST['trainer_id'] ?? 0),
        );
        
        $table_data = $master_data->get_events_table_data($args);
        wp_send_json_success($table_data);
    }
    
    /**
     * Handle AJAX request for Safari debugging logs
     * 
     * @return void
     */
    public function ajax_safari_debug() {
        // Get the log entry from POST data
        $log_data = isset($_POST['log']) ? $_POST['log'] : '';
        
        if (empty($log_data)) {
            wp_send_json_error('No log data provided');
            return;
        }
        
        // Decode the log entry
        $log_entry = json_decode(stripslashes($log_data), true);
        
        if (!$log_entry) {
            wp_send_json_error('Invalid log data format');
            return;
        }
        
        // Create a safe log entry for WordPress
        $safe_log_entry = array(
            'timestamp' => isset($log_entry['time']) ? sanitize_text_field($log_entry['time']) : current_time('Y-m-d H:i:s'),
            'message' => isset($log_entry['message']) ? sanitize_text_field($log_entry['message']) : '',
            'user_agent' => isset($log_entry['userAgent']) ? sanitize_text_field($log_entry['userAgent']) : '',
            'data' => isset($log_entry['data']) ? wp_json_encode($log_entry['data']) : null,
            'error_info' => isset($log_entry['error']) ? sanitize_text_field($log_entry['error']) : null,
            'stack_trace' => isset($log_entry['stack']) ? sanitize_textarea_field($log_entry['stack']) : null
        );
        
        // Log to WordPress debug log if WP_DEBUG_LOG is enabled
        if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
            $log_message = sprintf(
                '[SAFARI-DEBUG] %s | %s | UA: %s',
                $safe_log_entry['timestamp'],
                $safe_log_entry['message'],
                $safe_log_entry['user_agent']
            );
            
            if ($safe_log_entry['data']) {
                $log_message .= ' | Data: ' . $safe_log_entry['data'];
            }
            
            if ($safe_log_entry['error_info']) {
                $log_message .= ' | Error: ' . $safe_log_entry['error_info'];
            }
            
            error_log($log_message);
        }
        
        // Also store in database for easier retrieval (optional)
        $log_option_key = 'hvac_safari_debug_logs_' . date('Y_m_d');
        $existing_logs = get_option($log_option_key, array());
        $existing_logs[] = $safe_log_entry;
        
        // Keep only last 100 log entries per day to prevent database bloat
        if (count($existing_logs) > 100) {
            $existing_logs = array_slice($existing_logs, -100);
        }
        
        update_option($log_option_key, $existing_logs, false);
        
        wp_send_json_success(array('logged' => true));
    }
    
    /**
     * Add HVAC-specific body classes
     * 
     * @param array $classes Body classes
     * @return array Modified body classes
     */
    public function add_hvac_body_classes($classes) {
        // Check if we're on a plugin page
        if (defined('HVAC_IN_PAGE_TEMPLATE') && HVAC_IN_PAGE_TEMPLATE) {
            $classes[] = 'hvac-page';
            $classes[] = 'hvac-plugin-active';
            
            // Add solid header class to prevent transparency
            $classes[] = 'ast-header-without-transparency';
            $classes[] = 'header-main-layout-standard';
            
            // Add Astra full-width layout classes
            $classes[] = 'ast-no-sidebar';
            $classes[] = 'single';
            $classes[] = 'ast-single-post';
            $classes[] = 'ast-full-width-layout';
        }
        
        // Check URL for plugin pages
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        if (strpos($current_path, 'trainer/') !== false || strpos($current_path, 'master-trainer/') !== false) {
            $classes[] = 'hvac-trainer-page';
            $classes[] = 'ast-header-without-transparency';
            
            // Ensure full-width for all trainer pages
            $classes[] = 'ast-no-sidebar';
            $classes[] = 'ast-full-width-layout';
        }
        
        // Add specific page classes
        if (is_page_template('page-trainer-dashboard.php')) {
            $classes[] = 'hvac-trainer-dashboard';
        }
        if (is_page_template('page-certificate-reports.php')) {
            $classes[] = 'hvac-certificate-reports';
        }
        if (is_page_template('page-trainer-profile.php')) {
            $classes[] = 'hvac-trainer-profile';
        }
        
        // Remove any sidebar classes that might have been added
        $classes = array_diff($classes, array(
            'ast-right-sidebar',
            'ast-left-sidebar',
            'ast-separate-container'
        ));
        
        return $classes;
    }
    
    /**
     * Add HVAC-specific post classes
     * 
     * @param array $classes Post classes
     * @return array Modified post classes
     */
    public function add_hvac_post_classes($classes) {
        // Add classes for HVAC pages
        global $post;
        if ($post && strpos($post->post_name, 'trainer') !== false) {
            $classes[] = 'hvac-post';
        }
        
        return $classes;
    }
    
    /**
     * Force full-width layout for HVAC pages in Astra theme
     * 
     * @param string $layout Current layout
     * @return string Modified layout
     */
    public function force_full_width_layout($layout) {
        // Check if we're on a plugin page
        if (defined('HVAC_IN_PAGE_TEMPLATE') && HVAC_IN_PAGE_TEMPLATE) {
            return 'no-sidebar';
        }
        
        // Check URL for plugin pages
        $current_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        if (strpos($current_path, 'trainer/') !== false || strpos($current_path, 'master-trainer/') !== false) {
            return 'no-sidebar';
        }
        
        // Check by page template
        if (is_page_template()) {
            $template = get_page_template_slug();
            if (strpos($template, 'page-trainer') !== false || 
                strpos($template, 'page-master') !== false ||
                strpos($template, 'page-certificate') !== false ||
                strpos($template, 'page-generate') !== false ||
                strpos($template, 'page-manage-event') !== false) {
                return 'no-sidebar';
            }
        }
        
        return $layout;
    }
    
    /**
     * Check for manual page update request
     * 
     * @return void
     */
    public function check_for_page_updates() {
        // Only allow admins to trigger updates
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Check for update trigger
        if (isset($_GET['hvac_update_pages']) && $_GET['hvac_update_pages'] === 'true') {
            require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-page-manager.php';
            
            // Update all page layouts and templates
            HVAC_Page_Manager::update_existing_page_layouts();
            
            // Add admin notice
            add_action('admin_notices', function() {
                echo '<div class="notice notice-success is-dismissible">';
                echo '<p>HVAC pages have been updated with correct templates and layouts.</p>';
                echo '</div>';
            });
            
            // Redirect to remove the parameter
            wp_redirect(remove_query_arg('hvac_update_pages'));
            exit;
        }
    }
    
    /**
     * Check if pages need update after activation
     * 
     * @return void
     */
    public function check_page_update_flag() {
        if (get_option('hvac_pages_need_update', false)) {
            require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-page-manager.php';
            
            // Update all page layouts and templates
            HVAC_Page_Manager::update_existing_page_layouts();
            
            // Remove the flag
            delete_option('hvac_pages_need_update');
            
            HVAC_Logger::info('Pages updated after activation', 'HVAC Plugin');
        }
    }
}