<?php
/**
 * Settings Controller
 *
 * @package Freelance_Studio
 */

class FS_Settings_Controller {

    /**
     * Handle the request
     */
    public function handle_request() {
        // Start output buffering early for POST requests to prevent "headers already sent" errors
        // This captures any PHP warnings/notices that might be output before our redirect
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            ob_start();
        }
        
        $active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'business';
        
        // Note: Google Calendar OAuth callback is handled in FS_Admin::handle_gcal_oauth_callback() 
        // during admin_init, before any output is sent.
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Handle different form submissions based on tab
            // These methods will redirect and exit, so no need to continue
            if (isset($_POST['fs_settings_nonce'])) {
                $this->save_settings();
                return; // Shouldn't reach here due to redirect, but just in case
            } elseif (isset($_POST['fs_section_nonce'])) {
                $this->save_contract_section();
                return;
            } elseif (isset($_POST['fs_template_nonce'])) {
                $this->save_template();
                return;
            } elseif (isset($_POST['fs_deduction_nonce'])) {
                $this->save_annual_deduction();
                return;
            } elseif (isset($_POST['fs_copy_nonce'])) {
                $this->copy_deductions();
                return;
            } elseif (isset($_POST['fs_quarterly_nonce'])) {
                $this->save_quarterly_payments();
                return;
            } elseif (isset($_POST['fs_email_template_nonce'])) {
                $this->save_email_template();
                return;
            } elseif (isset($_POST['fs_tax_reminder_nonce'])) {
                $this->save_tax_reminder_settings();
                return;
            } elseif (isset($_POST['fs_gcal_nonce'])) {
                $this->save_gcal_credentials();
                return;
            } elseif (isset($_POST['fs_gcal_settings_nonce'])) {
                $this->save_gcal_settings();
                return;
            } elseif (isset($_POST['fs_gcal_disconnect_nonce'])) {
                $this->handle_gcal_disconnect();
                return;
            } elseif (isset($_POST['fs_deletion_nonce'])) {
                $this->save_deletion_setting();
                return;
            } elseif (isset($_POST['fs_external_cal_nonce'])) {
                $this->handle_external_calendar();
                return;
            }
            
            // If we got here, no POST handler matched - clean up buffer
            ob_end_clean();
        }
        
        $this->index();
    }

    /**
     * Display settings page
     */
    public function index() {
        $settings = $this->get_all_settings();
        $states = FS_Tax_Rates::get_states();
        $active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'business';
        // Calendar tab handles its own messages, so don't show the general one
        $show_success = isset($_GET['message']) && $_GET['message'] === 'saved' && $active_tab !== 'calendar';
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/settings/index.php';
    }

    /**
     * Save settings
     */
    /**
     * Save settings - handled by FS_Admin::early_save_settings() during admin_init.
     * This method exists as a fallback but should not normally be reached since
     * the early handler redirects and exits before the controller processes the request.
     */
    private function save_settings() {
        // Settings are saved by FS_Admin::early_save_settings() during admin_init
        // to prevent "headers already sent" errors. If we reach here, redirect back.
        $active_tab = isset($_POST['active_tab']) ? sanitize_text_field(wp_unslash($_POST['active_tab'])) : 'business';
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=' . $active_tab . '&message=saved'));
        exit;
    }

    /**
     * Save deletion setting (dedicated handler for reliability)
     */
    private function save_deletion_setting() {
        if (!wp_verify_nonce($_POST['fs_deletion_nonce'], 'fs_deletion_settings')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        // Explicitly set based on checkbox presence
        $delete_on_uninstall = isset($_POST['fs_delete_data_on_uninstall']) ? '1' : '0';
        
        // Update the option
        update_option('fs_delete_data_on_uninstall', $delete_on_uninstall);
        
        // Clean output buffer before redirect
        ob_end_clean();
        
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=tools&deletion_saved=1'));
        exit;
    }

    /**
     * Get all settings
     */
    private function get_all_settings() {
        // Guard against corrupted option values stored as arrays
        $payment_instructions = get_option('fs_payment_instructions', '');
        if (is_array($payment_instructions)) {
            $payment_instructions = implode("\n", array_filter($payment_instructions));
        }

        return array(
            // Business Information
            'business_name' => get_option('fs_business_name', ''),
            'business_email' => get_option('fs_business_email', ''),
            'business_phone' => get_option('fs_business_phone', ''),
            'business_website' => get_option('fs_business_website', ''),
            'booking_type' => get_option('fs_booking_type', 'external'),
            'booking_url' => get_option('fs_booking_url', ''),
            
            // Business Address
            'business_address' => (string) get_option('fs_business_address', ''),
            'business_city' => get_option('fs_business_city', ''),
            'business_state' => get_option('fs_business_state', ''),
            'business_zip' => get_option('fs_business_zip', ''),
            'business_country' => get_option('fs_business_country', 'United States'),
            
            // Branding
            'business_logo' => get_option('fs_business_logo', ''),
            'business_logo_light' => get_option('fs_business_logo_light', ''),
            'invoice_primary_color' => get_option('fs_invoice_primary_color', '#4173B0'),
            'invoice_primary_color_mode' => get_option('fs_invoice_primary_color_mode', 'solid'),
            'invoice_primary_color_2' => get_option('fs_invoice_primary_color_2', '#1a5276'),
            'invoice_gradient_direction' => get_option('fs_invoice_gradient_direction', '135'),
            
            // Contractor Signature
            'contractor_signature' => get_option('fs_contractor_signature', ''),
            'contractor_signer_name' => get_option('fs_contractor_signer_name', ''),
            'contractor_signer_title' => get_option('fs_contractor_signer_title', ''),
            
            // Default Rates
            'default_hourly_rate' => get_option('fs_default_hourly_rate', 75),
            'default_payment_terms' => get_option('fs_default_payment_terms', 30),
            'default_deposit_percentage' => get_option('fs_default_deposit_percentage', 50),
            
            // Invoice Settings
            'invoice_prefix' => get_option('fs_invoice_prefix', 'INV'),
            'payment_instructions' => (string) $payment_instructions,
            'payment_url' => get_option('fs_payment_url', '') ?: get_option('fs_payment_link', ''),
            
            // Tax Settings
            'tax_state' => get_option('fs_tax_state', ''),
            'federal_tax_bracket' => get_option('fs_federal_tax_bracket', 22),
            
            // Proposal Settings
            'proposal_prefix' => get_option('fs_proposal_prefix', 'PROP'),
            'proposal_validity_days' => get_option('fs_proposal_validity_days', 30),
            
            // Contract Settings
            'contract_prefix' => get_option('fs_contract_prefix', 'CON'),
            'freelancer_signature' => get_option('fs_freelancer_signature', ''),
            
            // Contract Placeholder Settings
            'contract_notice_days' => get_option('fs_contract_notice_days', 14),
            'contract_cure_days' => get_option('fs_contract_cure_days', 10),
            'contract_suspension_days' => get_option('fs_contract_suspension_days', 30),
            'contract_late_fee_percent' => get_option('fs_contract_late_fee_percent', 1.5),
            'contract_jurisdiction' => get_option('fs_contract_jurisdiction', ''),
            'contract_review_days' => get_option('fs_contract_review_days', 5),
        );
    }

    /**
     * Save contract section
     */
    private function save_contract_section() {
        if (!wp_verify_nonce($_POST['fs_section_nonce'], 'fs_save_contract_section')) {
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $section_id = isset($_POST['section_id']) ? intval($_POST['section_id']) : 0;
        
        $data = array(
            'title' => sanitize_text_field(wp_unslash($_POST['section_title'])),
            'content' => wp_kses_post($_POST['section_content']),
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
        );
        
        if ($section_id) {
            FS_Contract_Section::update($section_id, $data);
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=contracts&message=saved'));
        exit;
    }

    /**
     * Save project template
     */
    private function save_template() {
        if (!wp_verify_nonce($_POST['fs_template_nonce'], 'fs_save_project_template')) {
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $template_id = isset($_POST['template_id']) ? intval($_POST['template_id']) : 0;
        
        // Build milestones array
        $milestones = array();
        if (!empty($_POST['milestone_name'])) {
            foreach ($_POST['milestone_name'] as $index => $name) {
                if (empty($name)) continue;
                
                $milestones[] = array(
                    'name' => sanitize_text_field($name),
                    'description' => isset($_POST['milestone_description'][$index]) ? sanitize_textarea_field(wp_unslash($_POST['milestone_description'])[$index]) : '',
                    'days_offset' => isset($_POST['milestone_days_offset'][$index]) ? intval($_POST['milestone_days_offset'][$index]) : 0,
                    'invoice_percentage' => isset($_POST['milestone_percentage'][$index]) ? floatval($_POST['milestone_percentage'][$index]) : null,
                    'invoice_on_completion' => isset($_POST['milestone_invoice'][$index]) ? 1 : 0,
                );
            }
        }
        
        // Build tasks array
        $tasks = array();
        if (!empty($_POST['task_title'])) {
            foreach ($_POST['task_title'] as $index => $title) {
                if (empty($title)) continue;
                
                $tasks[] = array(
                    'title' => sanitize_text_field($title),
                    'description' => isset($_POST['task_description'][$index]) ? sanitize_textarea_field(wp_unslash($_POST['task_description'])[$index]) : '',
                    'priority' => isset($_POST['task_priority'][$index]) ? sanitize_text_field(wp_unslash($_POST['task_priority'])[$index]) : 'medium',
                    'days_offset' => isset($_POST['task_days_offset'][$index]) ? intval($_POST['task_days_offset'][$index]) : 0,
                    'estimated_hours' => isset($_POST['task_hours'][$index]) ? floatval($_POST['task_hours'][$index]) : null,
                    'milestone_index' => isset($_POST['task_milestone_index'][$index]) && $_POST['task_milestone_index'][$index] !== '' ? intval($_POST['task_milestone_index'][$index]) : null,
                );
            }
        }
        
        $data = array(
            'name' => sanitize_text_field(wp_unslash($_POST['name'])),
            'description' => sanitize_textarea_field(wp_unslash($_POST['description'] ?? '')),
            'default_billing_type' => sanitize_text_field(wp_unslash($_POST['default_billing_type'] ?? 'fixed')),
            'default_hourly_rate' => !empty($_POST['default_hourly_rate']) ? floatval($_POST['default_hourly_rate']) : null,
            'estimated_hours' => !empty($_POST['estimated_hours']) ? floatval($_POST['estimated_hours']) : null,
            'typical_price_min' => !empty($_POST['typical_price_min']) ? floatval($_POST['typical_price_min']) : null,
            'typical_price_max' => !empty($_POST['typical_price_max']) ? floatval($_POST['typical_price_max']) : null,
            'default_milestones' => $milestones,
            'default_tasks' => $tasks,
        );
        
        if ($template_id) {
            FS_Project_Template::update($template_id, $data);
        } else {
            $template_id = FS_Project_Template::create($data);
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=templates&message=saved'));
        exit;
    }

    /**
     * Save annual deduction
     */
    private function save_annual_deduction() {
        if (!wp_verify_nonce($_POST['fs_deduction_nonce'], 'fs_save_annual_deduction')) {
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $deduction_id = isset($_POST['deduction_id']) ? intval($_POST['deduction_id']) : 0;
        $year = isset($_POST['deduction_year']) ? intval($_POST['deduction_year']) : gmdate('Y');
        
        $data = array(
            'year' => $year,
            'name' => sanitize_text_field(wp_unslash($_POST['deduction_name'])),
            'category' => sanitize_text_field(wp_unslash($_POST['deduction_category'])),
            'annual_amount' => floatval($_POST['deduction_amount']),
            'deduction_percentage' => isset($_POST['deduction_percentage']) ? floatval($_POST['deduction_percentage']) : 100,
            'notes' => isset($_POST['deduction_notes']) ? sanitize_textarea_field(wp_unslash($_POST['deduction_notes'])) : '',
            'is_active' => isset($_POST['deduction_active']) ? 1 : (isset($_POST['add_deduction']) ? 1 : 0),
        );
        
        if ($deduction_id) {
            FS_Annual_Deduction::update($deduction_id, $data);
        } else {
            FS_Annual_Deduction::create($data);
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&year=' . $year . '&message=saved'));
        exit;
    }

    /**
     * Copy deductions from one year to another
     */
    private function copy_deductions() {
        if (!wp_verify_nonce($_POST['fs_copy_nonce'], 'fs_copy_deductions')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $from_year = isset($_POST['from_year']) ? intval($_POST['from_year']) : 0;
        $to_year = isset($_POST['to_year']) ? intval($_POST['to_year']) : gmdate('Y');
        
        if ($from_year && $to_year) {
            $copied = FS_Annual_Deduction::copy_to_year($from_year, $to_year);
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&year=' . $to_year . '&message=saved'));
        exit;
    }

    /**
     * Save quarterly tax payments
     */
    private function save_quarterly_payments() {
        if (!wp_verify_nonce($_POST['fs_quarterly_nonce'], 'fs_save_quarterly_payment')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $year = isset($_POST['payment_year']) ? intval($_POST['payment_year']) : gmdate('Y');
        $payments = isset($_POST['payments']) ? $_POST['payments'] : array();
        
        foreach ($payments as $quarter => $data) {
            $amount = isset($data['amount']) ? floatval($data['amount']) : 0;
            $date = isset($data['date']) && !empty($data['date']) ? sanitize_text_field($data['date']) : null;
            
            // Only save if amount is provided
            if ($amount > 0 || $date) {
                FS_Tax_Calculator::record_payment($year, $quarter, $amount, $date);
            }
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&year=' . $year . '&message=saved'));
        exit;
    }

    /**
     * Save email template
     */
    private function save_email_template() {
        if (!wp_verify_nonce($_POST['fs_email_template_nonce'], 'fs_save_email_template')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $template_type = isset($_POST['template_type']) ? sanitize_text_field(wp_unslash($_POST['template_type'])) : '';
        
        if (empty($template_type)) {
            ob_end_clean();
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=emails'));
            exit;
        }
        
        // Reset template
        if (isset($_POST['reset_email_template'])) {
            FS_Email_Template::reset($template_type);
            ob_end_clean();
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=emails&message=saved'));
            exit;
        }
        
        // Send test email
        if (isset($_POST['send_test_email'])) {
            $subject = isset($_POST['email_subject']) ? sanitize_text_field(wp_unslash($_POST['email_subject'])) : '';
            // Use wp_kses_post but also preserve the editor's formatting
            $body = isset($_POST['email_body']) ? $_POST['email_body'] : '';
            // Clean but preserve structure
            $body = wp_kses($body, array(
                'p' => array('style' => array()),
                'br' => array(),
                'strong' => array(),
                'b' => array(),
                'em' => array(),
                'i' => array(),
                'a' => array('href' => array(), 'style' => array(), 'target' => array()),
                'table' => array('style' => array(), 'cellpadding' => array(), 'cellspacing' => array(), 'border' => array()),
                'tr' => array(),
                'td' => array('style' => array()),
                'th' => array('style' => array()),
                'ul' => array('style' => array()),
                'ol' => array('style' => array()),
                'li' => array('style' => array()),
                'h1' => array('style' => array()),
                'h2' => array('style' => array()),
                'h3' => array('style' => array()),
                'h4' => array('style' => array()),
                'div' => array('style' => array()),
                'span' => array('style' => array()),
                'img' => array('src' => array(), 'alt' => array(), 'style' => array()),
            ));
            
            // Process variables with sample data
            $sample_data = array(
                '{client_name}' => 'Sample Client',
                '{invoice_number}' => 'INV-2025-001',
                '{amount}' => '$1,500.00',
                '{due_date}' => gmdate('F j, Y', strtotime('+7 days')),
                '{days_until_due}' => '7',
                '{days_overdue}' => '3',
                '{view_link}' => home_url(),
                '{business_name}' => get_option('fs_business_name', get_bloginfo('name')),
                '{proposal_title}' => 'Sample Proposal',
                '{contract_title}' => 'Sample Contract',
                '{expires_date}' => gmdate('F j, Y', strtotime('+30 days')),
                '{payment_date}' => gmdate('F j, Y'),
            );
            
            $processed_subject = FS_Email_Template::process_variables($subject, $sample_data);
            $processed_body = FS_Email_Template::process_variables($body, $sample_data);
            $html_body = FS_Email_Template::wrap_in_template($processed_body, 'Test email from Freelance Studio');
            
            $to = get_option('fs_business_email', get_option('admin_email'));
            $headers = array('Content-Type: text/html; charset=UTF-8');
            
            wp_mail($to, '[TEST] ' . $processed_subject, $html_body, $headers);
            
            ob_end_clean();
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=emails&edit_email=' . $template_type . '&message=test_sent'));
            exit;
        }
        
        // Save template
        $subject = isset($_POST['email_subject']) ? sanitize_text_field(wp_unslash($_POST['email_subject'])) : '';
        // Pass body without sanitization - save() function handles it
        $body = isset($_POST['email_body']) ? $_POST['email_body'] : '';
        
        FS_Email_Template::save($template_type, $subject, $body);
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=emails&message=saved'));
        exit;
    }

    /**
     * Save quarterly tax reminder settings
     */
    private function save_tax_reminder_settings() {
        if (!wp_verify_nonce($_POST['fs_tax_reminder_nonce'], 'fs_save_tax_reminder_settings')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $enabled = isset($_POST['quarterly_reminder_enabled']) ? 1 : 0;
        $days = isset($_POST['quarterly_reminder_days']) ? intval($_POST['quarterly_reminder_days']) : 7;
        $email = isset($_POST['quarterly_reminder_email']) ? sanitize_email(wp_unslash($_POST['quarterly_reminder_email'])) : '';
        
        update_option('fs_quarterly_reminder_enabled', $enabled);
        update_option('fs_quarterly_reminder_days', $days);
        update_option('fs_quarterly_reminder_email', $email);
        
        // Schedule or unschedule the cron job
        $timestamp = wp_next_scheduled('fs_quarterly_tax_reminder_check');
        
        if ($enabled && !$timestamp) {
            // Schedule daily check at 9 AM
            wp_schedule_event(strtotime('today 9:00'), 'daily', 'fs_quarterly_tax_reminder_check');
        } elseif (!$enabled && $timestamp) {
            wp_unschedule_event($timestamp, 'fs_quarterly_tax_reminder_check');
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-finances&tab=tax&message=saved'));
        exit;
    }

    /**
     * Handle Google Calendar OAuth callback
     */
    private function handle_gcal_oauth_callback() {
        // Verify state nonce
        if (!isset($_GET['state']) || !wp_verify_nonce($_GET['state'], 'fs_gcal_oauth')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        $code = sanitize_text_field($_GET['code']);
        
        ob_end_clean();
        if (FS_Google_Calendar_Service::exchange_code($code)) {
            // Check if we should create a new calendar
            $calendar_id = get_option('fs_gcal_calendar_id');
            if (empty($calendar_id)) {
                FS_Google_Calendar_Service::create_freelance_calendar();
            }
            
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=calendar&message=connected'));
        } else {
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=calendar&error=auth_failed'));
        }
        exit;
    }

    /**
     * Save Google Calendar credentials
     */
    private function save_gcal_credentials() {
        if (!wp_verify_nonce($_POST['fs_gcal_nonce'], 'fs_gcal_save_credentials')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        if (isset($_POST['gcal_client_id'])) {
            update_option('fs_gcal_client_id', sanitize_text_field(wp_unslash($_POST['gcal_client_id'])));
        }
        if (isset($_POST['gcal_client_secret'])) {
            update_option('fs_gcal_client_secret', sanitize_text_field(wp_unslash($_POST['gcal_client_secret'])));
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=calendar&message=saved'));
        exit;
    }

    /**
     * Save Google Calendar sync settings
     */
    private function save_gcal_settings() {
        if (!wp_verify_nonce($_POST['fs_gcal_settings_nonce'], 'fs_gcal_save_settings')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        // Enable/disable sync
        update_option('fs_gcal_enabled', isset($_POST['gcal_enabled']) ? '1' : '0');
        
        // Calendar selection
        $calendar_id = isset($_POST['gcal_calendar_id']) ? sanitize_text_field(wp_unslash($_POST['gcal_calendar_id'])) : '';
        if (empty($calendar_id)) {
            // Create new Freelance Studio calendar
            $calendar_id = FS_Google_Calendar_Service::create_freelance_calendar();
        }
        if ($calendar_id) {
            update_option('fs_gcal_calendar_id', $calendar_id);
        }
        
        // Sync options
        update_option('fs_gcal_sync_projects', isset($_POST['gcal_sync_projects']) ? '1' : '0');
        update_option('fs_gcal_sync_milestones', isset($_POST['gcal_sync_milestones']) ? '1' : '0');
        update_option('fs_gcal_sync_tasks', isset($_POST['gcal_sync_tasks']) ? '1' : '0');
        update_option('fs_gcal_sync_invoices', isset($_POST['gcal_sync_invoices']) ? '1' : '0');
        update_option('fs_gcal_sync_contracts', isset($_POST['gcal_sync_contracts']) ? '1' : '0');
        update_option('fs_gcal_sync_proposals', isset($_POST['gcal_sync_proposals']) ? '1' : '0');
        update_option('fs_gcal_sync_tax', isset($_POST['gcal_sync_tax']) ? '1' : '0');
        
        // Two-way sync settings
        $two_way_was_enabled = get_option('fs_gcal_two_way_sync', '0') === '1';
        $two_way_enabled = isset($_POST['gcal_two_way_sync']);
        update_option('fs_gcal_two_way_sync', $two_way_enabled ? '1' : '0');
        
        $old_frequency = get_option('fs_gcal_sync_frequency', 'fifteen_minutes');
        $new_frequency = isset($_POST['gcal_sync_frequency']) ? sanitize_text_field($_POST['gcal_sync_frequency']) : 'fifteen_minutes';
        update_option('fs_gcal_sync_frequency', $new_frequency);
        
        // Reschedule cron if two-way sync settings changed
        if ($two_way_enabled !== $two_way_was_enabled || $old_frequency !== $new_frequency) {
            // Unschedule existing
            $timestamp = wp_next_scheduled('fs_gcal_inbound_sync');
            if ($timestamp) {
                wp_unschedule_event($timestamp, 'fs_gcal_inbound_sync');
            }
            // Schedule new if enabled
            if ($two_way_enabled) {
                wp_schedule_event(time(), $new_frequency, 'fs_gcal_inbound_sync');
            }
        }
        
        // Weekly digest
        $digest_was_enabled = get_option('fs_gcal_weekly_digest_enabled', '0') === '1';
        $digest_enabled = isset($_POST['gcal_weekly_digest_enabled']);
        update_option('fs_gcal_weekly_digest_enabled', $digest_enabled ? '1' : '0');
        
        // Schedule or unschedule weekly digest cron
        $timestamp = wp_next_scheduled('fs_weekly_digest_email');
        if ($digest_enabled && !$timestamp) {
            // Schedule for Monday at 8 AM
            $next_monday = strtotime('next monday 8:00');
            wp_schedule_event($next_monday, 'weekly', 'fs_weekly_digest_email');
        } elseif (!$digest_enabled && $timestamp) {
            wp_unschedule_event($timestamp, 'fs_weekly_digest_email');
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=calendar&message=saved'));
        exit;
    }

    /**
     * Handle Google Calendar disconnect
     */
    private function handle_gcal_disconnect() {
        if (!wp_verify_nonce($_POST['fs_gcal_disconnect_nonce'], 'fs_gcal_disconnect')) {
            ob_end_clean();
            wp_die(esc_html__('Security check failed', 'freelance-studio'));
        }
        
        FS_Google_Calendar_Service::disconnect();
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=calendar&message=disconnected'));
        exit;
    }

    /**
     * Handle external calendar actions (add, sync, delete)
     */
    private function handle_external_calendar() {
        $action = isset($_POST['external_cal_action']) ? sanitize_text_field(wp_unslash($_POST['external_cal_action'])) : '';
        
        switch ($action) {
            case 'add':
                if (!wp_verify_nonce($_POST['fs_external_cal_nonce'], 'fs_add_external_calendar')) {
                    ob_end_clean();
                    wp_die(esc_html__('Security check failed', 'freelance-studio'));
                }
                
                $data = array(
                    'name' => sanitize_text_field(wp_unslash($_POST['ext_cal_name'])),
                    'url' => esc_url_raw($_POST['ext_cal_url']),
                    'color' => isset($_POST['ext_cal_color']) ? sanitize_hex_color($_POST['ext_cal_color']) : '#6b7280',
                    'is_active' => 1,
                    'affects_availability' => isset($_POST['ext_cal_affects_availability']) ? 1 : 0,
                );
                
                $result = FS_External_Calendar::create($data);
                $message = $result ? 'calendar_added' : 'calendar_error';
                break;
                
            case 'sync':
                if (!wp_verify_nonce($_POST['fs_external_cal_nonce'], 'fs_sync_external_calendar')) {
                    ob_end_clean();
                    wp_die(esc_html__('Security check failed', 'freelance-studio'));
                }
                
                $calendar_id = isset($_POST['calendar_id']) ? intval($_POST['calendar_id']) : 0;
                $result = FS_External_Calendar::sync_calendar($calendar_id);
                $message = $result ? 'calendar_synced' : 'calendar_sync_error';
                break;
                
            case 'delete':
                if (!wp_verify_nonce($_POST['fs_external_cal_nonce'], 'fs_delete_external_calendar')) {
                    ob_end_clean();
                    wp_die(esc_html__('Security check failed', 'freelance-studio'));
                }
                
                $calendar_id = isset($_POST['calendar_id']) ? intval($_POST['calendar_id']) : 0;
                $result = FS_External_Calendar::delete($calendar_id);
                $message = $result ? 'calendar_deleted' : 'calendar_error';
                break;
                
            default:
                $message = 'calendar_error';
        }
        
        ob_end_clean();
        FS_Admin::safe_redirect(admin_url('admin.php?page=fs-settings&tab=calendar&message=' . $message));
        exit;
    }
}
