<?php
/**
 * Plugin Activator for HVAC Community Events
 *
 * Handles plugin activation tasks
 *
 * @package HVAC_Community_Events
 * @since 1.0.0
 */

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

/**
 * HVAC_Activator class
 */
class HVAC_Activator {
    
    /**
     * Activate the plugin
     * 
     * @return void
     */
    public static function activate() {
        HVAC_Logger::info('Starting plugin activation', 'Activator');
        
        // Create database tables
        self::create_tables();
        
        // Create roles and capabilities
        self::setup_roles();
        
        // Setup user meta fields
        self::setup_user_meta_fields();
        
        // Create pages
        self::create_pages();
        
        // Set default options
        self::set_default_options();
        
        // Schedule cron jobs
        self::schedule_cron_jobs();
        
        // Activate announcements system
        if (class_exists('HVAC_Announcements_Manager')) {
            HVAC_Announcements_Manager::activate();
        }
        
        // Register routes before flushing
        if (class_exists('HVAC_Route_Manager')) {
            $route_manager = HVAC_Route_Manager::instance();
            $route_manager->register_rewrite_rules();
        }
        
        // Install default communication templates
        self::install_default_communication_templates();
        
        // Flush rewrite rules
        flush_rewrite_rules();
        
        HVAC_Logger::info('Plugin activation completed', 'Activator');
    }
    
    /**
     * Create database tables
     * 
     * @return void
     */
    private static function create_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // Create event_history table
        $table_name = $wpdb->prefix . 'event_history';
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            event_id bigint(20) NOT NULL,
            created_by bigint(20) NOT NULL,
            event_date date NOT NULL,
            attendees int NOT NULL DEFAULT 0,
            certificates_issued int NOT NULL DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY event_id (event_id),
            KEY created_by (created_by),
            KEY event_date (event_date)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        
        // Create contact submissions table for Find a Trainer feature
        if (class_exists('HVAC_Contact_Submissions_Table')) {
            HVAC_Contact_Submissions_Table::create_table();
        }
        
        HVAC_Logger::info('Database tables created', 'Activator');
    }
    
    /**
     * Setup roles and capabilities
     * 
     * @return void
     */
    private static function setup_roles() {
        // Use the roles manager to create roles
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-roles.php';
        
        $roles_manager = new HVAC_Roles();
        
        // Create trainer role
        $trainer_role = $roles_manager->create_trainer_role();
        if ($trainer_role) {
            HVAC_Logger::info('Successfully created hvac_trainer role', 'Activator');
        }
        
        // Create master trainer role
        $master_role = $roles_manager->create_master_trainer_role();
        if ($master_role) {
            HVAC_Logger::info('Successfully created hvac_master_trainer role', 'Activator');
        }
        
        // Grant admin access
        $admin_access = $roles_manager->grant_admin_dashboard_access();
        if ($admin_access) {
            HVAC_Logger::info('Successfully granted admin dashboard access', 'Activator');
        }
    }
    
    /**
     * Setup user meta fields
     * 
     * @return void
     */
    private static function setup_user_meta_fields() {
        global $wpdb;
        
        // Define all custom meta fields used by the plugin with their default values
        $meta_fields_defaults = array(
            // Core fields
            'role' => 'member',
            'account_status' => 'pending',
            
            // Certification fields (admin/master trainer editable only)
            'date_certified' => '',
            'certification_type' => '',
            'certification_status' => '',
            
            // Personal information
            'user_linkedin' => '',
            'personal_accreditation' => '',
            'user_phone' => '',
            
            // Location fields
            'user_city' => '',
            'user_state' => '',
            'user_country' => '',
            'user_zip' => '',
            
            // Business/Organization information
            'business_name' => '',
            'business_phone' => '',
            'business_email' => '',
            'business_website' => '',
            'business_description' => '',
            'business_type' => '',
            
            // Organization headquarters
            'org_headquarters_city' => '',
            'org_headquarters_state' => '',
            'org_headquarters_country' => '',
            
            // Training capabilities
            'training_audience' => array(),
            'training_formats' => array(),
            'training_locations' => array(),
            'training_resources' => array(),
            'annual_revenue_target' => '',
            
            // Venue information
            'create_venue' => 'No',
            'venue_name' => '',
            'venue_address' => '',
            'venue_phone' => '',
            'venue_website' => '',
            
            // Profile and application
            'application_details' => '',
            'profile_photo_id' => '',
            'profile_image_id' => '',
            'trainer_certifications' => '',
            'years_experience' => '',
            
            // Related post IDs
            'hvac_organizer_id' => '',
            'hvac_venue_id' => '',
            'organizer_id' => ''
        );
        
        // Get all users to process
        $users = get_users(array('fields' => 'ID'));
        
        foreach ($users as $user_id) {
            $user_obj = get_userdata($user_id);
            if (!$user_obj) continue;
            
            // Process each meta field
            foreach ($meta_fields_defaults as $meta_key => $default_value) {
                $existing_value = get_user_meta($user_id, $meta_key, true);
                
                // Only set default if the field doesn't exist or is empty
                if ($existing_value === '' || $existing_value === false) {
                    
                    // Special handling for role field based on user capabilities
                    if ($meta_key === 'role') {
                        if ($user_obj->has_cap('hvac_trainer') || $user_obj->has_cap('hvac_master_trainer')) {
                            $default_value = 'trainer';
                        } elseif ($user_obj->has_cap('administrator')) {
                            $default_value = 'administrator';
                        } else {
                            $default_value = 'member';
                        }
                    }
                    
                    // Special handling for account_status based on user role
                    if ($meta_key === 'account_status') {
                        if ($user_obj->has_cap('hvac_trainer') || $user_obj->has_cap('hvac_master_trainer')) {
                            $default_value = 'approved';
                        } elseif ($user_obj->has_cap('administrator')) {
                            $default_value = 'approved';
                        } else {
                            $default_value = 'pending';
                        }
                    }
                    
                    update_user_meta($user_id, $meta_key, $default_value);
                }
            }
        }
        
        HVAC_Logger::info('User meta fields setup completed for ' . count($users) . ' users', 'Activator');
    }
    
    /**
     * Create plugin pages
     * 
     * @return void
     */
    private static function create_pages() {
        // Use the page manager to create pages
        require_once HVAC_PLUGIN_DIR . 'includes/class-hvac-page-manager.php';
        
        HVAC_Page_Manager::create_pages();
        
        // Update existing pages with proper layout settings
        HVAC_Page_Manager::update_existing_page_layouts();
        
        // Set flag to force page update on next load
        update_option('hvac_pages_need_update', true);
    }
    
    /**
     * Set default plugin options
     * 
     * @return void
     */
    private static function set_default_options() {
        // General settings
        add_option('hvac_support_email', 'joe@upskillhvac.com');
        add_option('hvac_trainer_approval_required', true);
        add_option('hvac_inactive_days_threshold', 180);
        
        // Email templates
        $email_templates = [
            'trainer_approved' => [
                'subject' => 'Your HVAC Trainer Account Has Been Approved!',
                'content' => 'Congratulations! Your trainer account has been approved. You can now log in and start creating training events.'
            ],
            'trainer_rejected' => [
                'subject' => 'Update on Your HVAC Trainer Application',
                'content' => 'Thank you for your interest in becoming an HVAC trainer. Unfortunately, we are unable to approve your application at this time.'
            ],
            'trainer_disabled' => [
                'subject' => 'Your HVAC Trainer Account Status',
                'content' => 'Your trainer account has been temporarily disabled. Please contact support for more information.'
            ],
            'new_trainer_notification' => [
                'subject' => 'New Trainer Registration: {trainer_name}',
                'content' => 'A new trainer has registered and is awaiting approval.\n\nName: {trainer_name}\nEmail: {trainer_email}\nBusiness: {business_name}'
            ]
        ];
        
        foreach ($email_templates as $key => $template) {
            add_option('hvac_email_template_' . $key, $template);
        }
        
        // Feature flags
        add_option('hvac_enable_google_sheets', false);
        add_option('hvac_enable_zoho_crm', false);
        
        HVAC_Logger::info('Default options set', 'Activator');
    }
    
    /**
     * Schedule cron jobs
     * 
     * @return void
     */
    private static function schedule_cron_jobs() {
        // Schedule daily trainer status check
        if (!wp_next_scheduled('hvac_daily_trainer_status_check')) {
            wp_schedule_event(time(), 'daily', 'hvac_daily_trainer_status_check');
            HVAC_Logger::info('Scheduled daily trainer status check', 'Activator');
        }
        
        // Schedule weekly cleanup
        if (!wp_next_scheduled('hvac_weekly_cleanup')) {
            wp_schedule_event(time(), 'weekly', 'hvac_weekly_cleanup');
            HVAC_Logger::info('Scheduled weekly cleanup', 'Activator');
        }
    }
    
    /**
     * Install default communication templates
     * 
     * @return void
     */
    private static function install_default_communication_templates() {
        if (class_exists('HVAC_Trainer_Communication_Templates')) {
            $templates_manager = HVAC_Trainer_Communication_Templates::instance();
            $templates_manager->install_default_templates();
            HVAC_Logger::info('Default communication templates installed', 'Activator');
        }
    }
}