<?php
/**
 * Settings View - Tabbed Interface
 *
 * @package Freelance_Studio
 */

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

$active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'business';

// For templates tab
$templates = array();
$template = null;
if ($active_tab === 'templates') {
    $templates = FS_Project_Template::get_all();
    if (isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id'])) {
        $template = FS_Project_Template::get(intval($_GET['id']));
    }
}

// For contract sections tab
$contract_sections = array();
$editing_section = null;
if ($active_tab === 'contracts') {
    $contract_sections = FS_Contract_Section::get_all();
    if (isset($_GET['edit'])) {
        $editing_section = FS_Contract_Section::get(intval($_GET['edit']));
    }
}
?>

<div class="wrap fs-wrap">
    <h1><?php esc_html_e('Settings', 'freelance-studio'); ?></h1>
    
    <?php if ($show_success): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php esc_html_e('Settings saved successfully.', 'freelance-studio'); ?></p>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['message']) && $_GET['message'] === 'activated'): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php esc_html_e('License activated successfully!', 'freelance-studio'); ?></p>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['message']) && $_GET['message'] === 'deactivated'): ?>
        <div class="notice notice-info is-dismissible">
            <p><?php esc_html_e('License deactivated.', 'freelance-studio'); ?></p>
        </div>
    <?php endif; ?>
    
    <!-- Mobile Tab Dropdown Navigation -->
    <div class="fs-tab-nav fs-settings-tab-nav fs-mobile-only">
        <a href="?page=fs-settings&tab=business" class="fs-tab <?php echo $active_tab === 'business' ? 'active' : ''; ?>"><?php esc_html_e('Business', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=documents" class="fs-tab <?php echo $active_tab === 'documents' ? 'active' : ''; ?>"><?php esc_html_e('Documents', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=invoices" class="fs-tab <?php echo $active_tab === 'invoices' ? 'active' : ''; ?>"><?php esc_html_e('Invoices', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=time" class="fs-tab <?php echo $active_tab === 'time' ? 'active' : ''; ?>"><?php esc_html_e('Time Tracking', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=emails" class="fs-tab <?php echo $active_tab === 'emails' ? 'active' : ''; ?>"><?php esc_html_e('Email Templates', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=email_delivery" class="fs-tab <?php echo $active_tab === 'email_delivery' ? 'active' : ''; ?>"><?php esc_html_e('Email Delivery', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=services" class="fs-tab <?php echo $active_tab === 'services' ? 'active' : ''; ?>"><?php esc_html_e('Services', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=templates" class="fs-tab <?php echo $active_tab === 'templates' ? 'active' : ''; ?>"><?php esc_html_e('Templates', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=contracts" class="fs-tab <?php echo $active_tab === 'contracts' ? 'active' : ''; ?>"><?php esc_html_e('Contract Sections', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=calendar" class="fs-tab <?php echo $active_tab === 'calendar' ? 'active' : ''; ?>"><?php esc_html_e('Calendar', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=import" class="fs-tab <?php echo $active_tab === 'import' ? 'active' : ''; ?>"><?php esc_html_e('Import', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=tools" class="fs-tab <?php echo $active_tab === 'tools' ? 'active' : ''; ?>"><?php esc_html_e('Tools', 'freelance-studio'); ?></a>
        <a href="?page=fs-settings&tab=about" class="fs-tab <?php echo $active_tab === 'about' ? 'active' : ''; ?>"><?php esc_html_e('Freelance Studio', 'freelance-studio'); ?></a>
    </div>
    
    <!-- Settings Layout - Vertical Tabs -->
    <div class="fs-settings-layout">
        <nav class="fs-settings-sidebar">
            <a href="?page=fs-settings&tab=business" class="fs-settings-nav-item <?php echo $active_tab === 'business' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-building"></span> <?php esc_html_e('Business', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=documents" class="fs-settings-nav-item <?php echo $active_tab === 'documents' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-media-document"></span> <?php esc_html_e('Documents', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=invoices" class="fs-settings-nav-item <?php echo $active_tab === 'invoices' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-money-alt"></span> <?php esc_html_e('Invoices', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=time" class="fs-settings-nav-item <?php echo $active_tab === 'time' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-clock"></span> <?php esc_html_e('Time Tracking', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=emails" class="fs-settings-nav-item <?php echo $active_tab === 'emails' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-email-alt"></span> <?php esc_html_e('Email Templates', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=email_delivery" class="fs-settings-nav-item <?php echo $active_tab === 'email_delivery' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-migrate"></span> <?php esc_html_e('Email Delivery', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=services" class="fs-settings-nav-item <?php echo $active_tab === 'services' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-clipboard"></span> <?php esc_html_e('Services', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=templates" class="fs-settings-nav-item <?php echo $active_tab === 'templates' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-portfolio"></span> <?php esc_html_e('Templates', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=contracts" class="fs-settings-nav-item <?php echo $active_tab === 'contracts' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-media-text"></span> <?php esc_html_e('Contract Sections', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=calendar" class="fs-settings-nav-item <?php echo $active_tab === 'calendar' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-calendar-alt"></span> <?php esc_html_e('Calendar', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=import" class="fs-settings-nav-item <?php echo $active_tab === 'import' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-database-import"></span> <?php esc_html_e('Import', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=tools" class="fs-settings-nav-item <?php echo $active_tab === 'tools' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-admin-tools"></span> <?php esc_html_e('Tools', 'freelance-studio'); ?>
            </a>
            <a href="?page=fs-settings&tab=about" class="fs-settings-nav-item fs-settings-nav-item--about <?php echo $active_tab === 'about' ? 'active' : ''; ?>">
                <span class="dashicons dashicons-info-outline"></span> <?php esc_html_e('Freelance Studio', 'freelance-studio'); ?>
            </a>
        </nav>
        
        <div class="fs-settings-content">
    
    <?php if (in_array($active_tab, array('business', 'documents', 'invoices', 'time'))): ?>
    <form method="post" action="" id="fs-settings-form">
        <?php wp_nonce_field('fs_save_settings', 'fs_settings_nonce'); ?>
        <input type="hidden" name="active_tab" value="<?php echo esc_attr($active_tab); ?>">
    <?php endif; ?>
        
        <!-- ============================================
             BUSINESS TAB
             ============================================ -->
        <?php if ($active_tab === 'business'): ?>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Business Information', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('This information will appear on your invoices and client-facing documents.', 'freelance-studio'); ?></p>
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="business_name"><?php esc_html_e('Business Name', 'freelance-studio'); ?> <span class="fs-required">*</span></label>
                    </th>
                    <td>
                        <input type="text" name="business_name" id="business_name" class="regular-text" value="<?php echo esc_attr($settings['business_name']); ?>" required>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="business_email"><?php esc_html_e('Email', 'freelance-studio'); ?> <span class="fs-required">*</span></label>
                    </th>
                    <td>
                        <input type="email" name="business_email" id="business_email" class="regular-text" value="<?php echo esc_attr($settings['business_email']); ?>" required>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="business_phone"><?php esc_html_e('Phone', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="text" name="business_phone" id="business_phone" class="regular-text" value="<?php echo esc_attr($settings['business_phone']); ?>">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="business_website"><?php esc_html_e('Website', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="url" name="business_website" id="business_website" class="regular-text" value="<?php echo esc_attr($settings['business_website']); ?>" placeholder="https://example.com">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="my_role"><?php esc_html_e('My Role', 'freelance-studio'); ?></label></th>
                    <td>
                        <?php $my_role = get_option('fs_my_role', 'freelancer'); ?>
                        <select name="my_role" id="my_role" class="regular-text">
                            <option value="freelancer" <?php selected($my_role, 'freelancer'); ?>><?php esc_html_e('Freelancer', 'freelance-studio'); ?></option>
                            <option value="designer" <?php selected($my_role, 'designer'); ?>><?php esc_html_e('Designer', 'freelance-studio'); ?></option>
                            <option value="developer" <?php selected($my_role, 'developer'); ?>><?php esc_html_e('Developer', 'freelance-studio'); ?></option>
                            <option value="project_manager" <?php selected($my_role, 'project_manager'); ?>><?php esc_html_e('Project Manager', 'freelance-studio'); ?></option>
                            <option value="consultant" <?php selected($my_role, 'consultant'); ?>><?php esc_html_e('Consultant', 'freelance-studio'); ?></option>
                            <option value="agency" <?php selected($my_role, 'agency'); ?>><?php esc_html_e('Agency', 'freelance-studio'); ?></option>
                        </select>
                        <p class="description"><?php esc_html_e('Your role will appear in task assignments as "Me (Role)".', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label><?php esc_html_e('Client Portal Booking', 'freelance-studio'); ?></label></th>
                    <td>
                        <?php $booking_type = isset($settings['booking_type']) ? $settings['booking_type'] : 'external'; ?>
                        <fieldset>
                            <label style="display: block; margin-bottom: 8px;">
                                <input type="radio" name="booking_type" value="none" <?php checked($booking_type, 'none'); ?>>
                                <?php esc_html_e('Disabled - Hide booking button in client portal', 'freelance-studio'); ?>
                            </label>
                            <label style="display: block; margin-bottom: 8px;">
                                <input type="radio" name="booking_type" value="internal" <?php checked($booking_type, 'internal'); ?>>
                                <?php esc_html_e('Use internal booking system', 'freelance-studio'); ?>
                                <span class="description" style="display: block; margin-left: 24px; margin-top: 2px;">
                                    <?php esc_html_e('Clients book through your built-in booking page. Configure in', 'freelance-studio'); ?>
                                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&tab=settings') ); ?>"><?php esc_html_e('Bookings → Settings', 'freelance-studio'); ?></a>
                                </span>
                            </label>
                            <label style="display: block; margin-bottom: 8px;">
                                <input type="radio" name="booking_type" value="external" <?php checked($booking_type, 'external'); ?>>
                                <?php esc_html_e('Use external booking link', 'freelance-studio'); ?>
                            </label>
                        </fieldset>
                        
                        <div id="fs-external-booking-url" style="margin-top: 10px; margin-left: 24px; <?php echo $booking_type !== 'external' ? 'display: none;' : ''; ?>">
                            <input type="url" name="booking_url" id="booking_url" class="regular-text" value="<?php echo esc_attr($settings['booking_url']); ?>" placeholder="https://tidycal.com/yourname">
                            <p class="description"><?php esc_html_e('Link to TidyCal, Calendly, or other scheduling service.', 'freelance-studio'); ?></p>
                        </div>
                    </td>
                </tr>
                <script>
                jQuery(document).ready(function($) {
                    $('input[name="booking_type"]').on('change', function() {
                        if ($(this).val() === 'external') {
                            $('#fs-external-booking-url').slideDown();
                        } else {
                            $('#fs-external-booking-url').slideUp();
                        }
                    });
                });
                </script>
            </table>
        </div>

        <div class="fs-settings-section">
            <h2><?php esc_html_e('Business Address', 'freelance-studio'); ?></h2>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="business_address"><?php esc_html_e('Street Address', 'freelance-studio'); ?></label></th>
                    <td>
                        <textarea name="business_address" id="business_address" rows="2" class="large-text"><?php echo esc_textarea(is_array($settings['business_address']) ? implode("\n", $settings['business_address']) : $settings['business_address']); ?></textarea>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="business_city"><?php esc_html_e('City', 'freelance-studio'); ?></label></th>
                    <td><input type="text" name="business_city" id="business_city" class="regular-text" value="<?php echo esc_attr($settings['business_city']); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="business_state"><?php esc_html_e('State/Province', 'freelance-studio'); ?></label></th>
                    <td><input type="text" name="business_state" id="business_state" class="regular-text" value="<?php echo esc_attr($settings['business_state']); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="business_zip"><?php esc_html_e('ZIP/Postal Code', 'freelance-studio'); ?></label></th>
                    <td><input type="text" name="business_zip" id="business_zip" class="regular-text" value="<?php echo esc_attr($settings['business_zip']); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="business_country"><?php esc_html_e('Country', 'freelance-studio'); ?></label></th>
                    <td><input type="text" name="business_country" id="business_country" class="regular-text" value="<?php echo esc_attr($settings['business_country']); ?>"></td>
                </tr>
            </table>
        </div>

        <div class="fs-settings-section">
            <h2><?php esc_html_e('Branding', 'freelance-studio'); ?></h2>
            
            <?php
                $logo_url = !empty($settings['business_logo']) ? $settings['business_logo'] : '';
                $logo_light_url = !empty($settings['business_logo_light']) ? $settings['business_logo_light'] : '';
                $primary_color_val = !empty($settings['invoice_primary_color']) ? $settings['invoice_primary_color'] : '#2271b1';
                $color_mode = !empty($settings['invoice_primary_color_mode']) ? $settings['invoice_primary_color_mode'] : 'solid';
                $color_2 = !empty($settings['invoice_primary_color_2']) ? $settings['invoice_primary_color_2'] : '#1a5276';
                $grad_dir = !empty($settings['invoice_gradient_direction']) ? $settings['invoice_gradient_direction'] : '135';
            ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="business_logo"><?php esc_html_e('Default Logo', 'freelance-studio'); ?></label>
                        <span class="fs-logo-variant-tag fs-logo-tag-dark"><?php esc_html_e('Dark', 'freelance-studio'); ?></span>
                    </th>
                    <td>
                        <div class="fs-logo-upload-wrapper">
                            <div class="fs-logo-preview fs-logo-preview-dark <?php echo $logo_url ? 'has-logo' : ''; ?>" id="business-logo-preview">
                                <?php if ($logo_url): ?>
                                    <img src="<?php echo esc_url($logo_url); ?>" alt="<?php esc_attr_e('Business logo', 'freelance-studio'); ?>">
                                <?php else: ?>
                                    <span class="fs-logo-placeholder">
                                        <span class="dashicons dashicons-format-image"></span>
                                    </span>
                                <?php endif; ?>
                            </div>
                            <div class="fs-logo-actions">
                                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="upload-business-logo-btn">
                                    <?php echo  esc_html( $logo_url ? __('Change Logo', 'freelance-studio') : __('Upload Logo', 'freelance-studio') ); ?>
                                </button>
                                <?php if ($logo_url): ?>
                                    <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-remove-logo-btn" id="remove-business-logo-btn">
                                        <?php esc_html_e('Remove', 'freelance-studio'); ?>
                                    </button>
                                <?php endif; ?>
                            </div>
                            <p class="description"><?php esc_html_e('Used on white/light backgrounds: client portal, booking pages, emails, and PDFs. PNG transparency supported.', 'freelance-studio'); ?></p>
                            <p class="description" style="margin-top: 4px;"><?php esc_html_e('Recommended: PNG or SVG, at least 600px wide, transparent background. Max display size is 200×60px.', 'freelance-studio'); ?></p>
                            <p class="description" style="margin-top: 4px;"><?php esc_html_e('Or enter a URL directly:', 'freelance-studio'); ?></p>
                            <input type="url" name="business_logo" id="business_logo" class="large-text" value="<?php echo esc_attr($logo_url); ?>" placeholder="https://example.com/logo-dark.png">
                        </div>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="business_logo_light"><?php esc_html_e('Light Logo', 'freelance-studio'); ?></label>
                        <span class="fs-logo-variant-tag fs-logo-tag-light"><?php esc_html_e('Light', 'freelance-studio'); ?></span>
                    </th>
                    <td>
                        <div class="fs-logo-upload-wrapper">
                            <div class="fs-logo-preview fs-logo-preview-light <?php echo $logo_light_url ? 'has-logo' : ''; ?>" id="business-logo-light-preview" style="background: <?php
                                if ($color_mode === 'gradient') {
                                    echo 'linear-gradient(' . intval($grad_dir) . 'deg, ' . esc_attr($primary_color_val) . ' 0%, ' . esc_attr($color_2) . ' 100%)';
                                } else {
                                    echo esc_attr($primary_color_val);
                                }
                            ?>;">
                                <?php if ($logo_light_url): ?>
                                    <img src="<?php echo esc_url($logo_light_url); ?>" alt="<?php esc_attr_e('Business logo (light)', 'freelance-studio'); ?>">
                                <?php else: ?>
                                    <span class="fs-logo-placeholder">
                                        <span class="dashicons dashicons-format-image"></span>
                                    </span>
                                <?php endif; ?>
                            </div>
                            <div class="fs-logo-actions">
                                <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="upload-business-logo-light-btn">
                                    <?php echo  esc_html( $logo_light_url ? __('Change Logo', 'freelance-studio') : __('Upload Logo', 'freelance-studio') ); ?>
                                </button>
                                <?php if ($logo_light_url): ?>
                                    <button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-remove-logo-btn" id="remove-business-logo-light-btn">
                                        <?php esc_html_e('Remove', 'freelance-studio'); ?>
                                    </button>
                                <?php endif; ?>
                            </div>
                            <p class="description"><?php esc_html_e('Used on your brand color background: invoice, proposal, contract headers, and client-facing emails. If not set, the default logo is used everywhere.', 'freelance-studio'); ?></p>
                            <p class="description" style="margin-top: 4px;"><?php esc_html_e('Recommended: PNG or SVG, at least 600px wide, transparent background. Use white or light-colored artwork for best contrast.', 'freelance-studio'); ?></p>
                            <p class="description" style="margin-top: 4px;"><?php esc_html_e('Or enter a URL directly:', 'freelance-studio'); ?></p>
                            <input type="url" name="business_logo_light" id="business_logo_light" class="large-text" value="<?php echo esc_attr($logo_light_url); ?>" placeholder="https://example.com/logo-light.png">
                        </div>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Header Color', 'freelance-studio'); ?></th>
                    <td>
                        <?php
                            $color_mode = !empty($settings['invoice_primary_color_mode']) ? $settings['invoice_primary_color_mode'] : 'solid';
                            $color_2 = !empty($settings['invoice_primary_color_2']) ? $settings['invoice_primary_color_2'] : '#1a5276';
                            $grad_dir = !empty($settings['invoice_gradient_direction']) ? $settings['invoice_gradient_direction'] : '135';
                        ?>
                        <div class="fs-color-mode-wrapper">
                            <div class="fs-color-mode-toggle">
                                <label class="fs-color-mode-option <?php echo $color_mode === 'solid' ? 'active' : ''; ?>">
                                    <input type="radio" name="invoice_primary_color_mode" value="solid" <?php checked($color_mode, 'solid'); ?>>
                                    <?php esc_html_e('Solid', 'freelance-studio'); ?>
                                </label>
                                <label class="fs-color-mode-option <?php echo $color_mode === 'gradient' ? 'active' : ''; ?>">
                                    <input type="radio" name="invoice_primary_color_mode" value="gradient" <?php checked($color_mode, 'gradient'); ?>>
                                    <?php esc_html_e('Gradient', 'freelance-studio'); ?>
                                </label>
                            </div>
                            
                            <div class="fs-color-pickers">
                                <div class="fs-color-picker-group">
                                    <label for="invoice_primary_color"><?php echo  esc_html( ($color_mode === 'gradient') ? __('Start Color', 'freelance-studio') : __('Color', 'freelance-studio') ); ?></label>
                                    <input type="color" name="invoice_primary_color" id="invoice_primary_color" value="<?php echo esc_attr($primary_color_val); ?>">
                                </div>
                                <div class="fs-color-picker-group fs-gradient-controls" id="fs-gradient-controls" style="<?php echo $color_mode === 'gradient' ? '' : 'display:none;'; ?>">
                                    <label for="invoice_primary_color_2"><?php esc_html_e('End Color', 'freelance-studio'); ?></label>
                                    <input type="color" name="invoice_primary_color_2" id="invoice_primary_color_2" value="<?php echo esc_attr($color_2); ?>">
                                </div>
                            </div>
                            
                            <div class="fs-gradient-controls fs-gradient-direction-wrapper" id="fs-gradient-direction-wrapper" style="<?php echo $color_mode === 'gradient' ? '' : 'display:none;'; ?>">
                                <label for="invoice_gradient_direction"><?php esc_html_e('Direction', 'freelance-studio'); ?></label>
                                <div class="fs-direction-presets">
                                    <?php
                                    $directions = array(
                                        '90'  => '→',
                                        '135' => '↘',
                                        '180' => '↓',
                                        '225' => '↙',
                                        '270' => '←',
                                        '45'  => '↗',
                                        '0'   => '↑',
                                        '315' => '↖',
                                    );
                                    foreach ($directions as $deg => $arrow): ?>
                                        <button type="button" class="fs-direction-btn <?php echo  esc_attr( $grad_dir == $deg ? 'active' : '' ); ?>" data-direction="<?php echo  esc_attr( $deg ); ?>" title="<?php echo  esc_attr( $deg ); ?>°"><?php echo  esc_attr( $arrow ); ?></button>
                                    <?php endforeach; ?>
                                </div>
                                <input type="hidden" name="invoice_gradient_direction" id="invoice_gradient_direction" value="<?php echo esc_attr($grad_dir); ?>">
                            </div>
                            
                            <div class="fs-color-swatch-preview" id="fs-color-swatch-preview" style="background: <?php
                                if ($color_mode === 'gradient') {
                                    echo 'linear-gradient(' . intval($grad_dir) . 'deg, ' . esc_attr($primary_color_val) . ' 0%, ' . esc_attr($color_2) . ' 100%)';
                                } else {
                                    echo esc_attr($primary_color_val);
                                }
                            ?>;">
                            </div>
                        </div>
                        <p class="description"><?php esc_html_e('Used for headers and accents on public invoices, proposals, and contracts.', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Header Preview', 'freelance-studio'); ?></th>
                    <td>
                        <div class="fs-header-preview-wrapper">
                            <div class="fs-header-preview-pair">
                                <!-- Document header preview (colored bg → light logo) -->
                                <div class="fs-header-preview-card">
                                    <span class="fs-header-preview-label"><?php esc_html_e('Invoices / Proposals / Contracts', 'freelance-studio'); ?> <span class="fs-logo-variant-tag fs-logo-tag-light"><?php esc_html_e('Light', 'freelance-studio'); ?></span></span>
                                    <div class="fs-header-preview" id="fs-header-preview-colored">
                                        <div class="fs-header-preview-bar" id="fs-header-preview-bar" style="background: <?php
                                            if ($color_mode === 'gradient') {
                                                echo 'linear-gradient(' . intval($grad_dir) . 'deg, ' . esc_attr($primary_color_val) . ' 0%, ' . esc_attr($color_2) . ' 100%)';
                                            } else {
                                                echo esc_attr($primary_color_val);
                                            }
                                        ?>;">
                                            <?php
                                                $colored_logo = $logo_light_url ?: $logo_url;
                                            ?>
                                            <span id="fs-header-preview-logo-wrap" style="<?php echo $colored_logo ? '' : 'display:none;'; ?>">
                                                <img src="<?php echo esc_url($colored_logo); ?>" alt="" class="fs-header-preview-logo" id="fs-header-preview-logo">
                                            </span>
                                            <span class="fs-header-preview-biz-name" id="fs-header-preview-biz-name"><?php echo esc_html($settings['business_name'] ?: __('Your Business Name', 'freelance-studio')); ?></span>
                                            <span class="fs-header-preview-title"><?php esc_html_e('Invoice', 'freelance-studio'); ?></span>
                                            <span class="fs-header-preview-subtitle">#INV-001</span>
                                        </div>
                                        <div class="fs-header-preview-body">
                                            <div class="fs-header-preview-body-line"></div>
                                            <div class="fs-header-preview-body-line"></div>
                                            <div class="fs-header-preview-body-line"></div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- White header preview (white bg → dark/default logo) -->
                                <div class="fs-header-preview-card">
                                    <span class="fs-header-preview-label"><?php esc_html_e('Client Portal / Booking / Emails', 'freelance-studio'); ?> <span class="fs-logo-variant-tag fs-logo-tag-dark"><?php esc_html_e('Dark', 'freelance-studio'); ?></span></span>
                                    <div class="fs-header-preview" id="fs-header-preview-white">
                                        <div class="fs-header-preview-bar fs-header-preview-bar-white" id="fs-header-preview-bar-white">
                                            <span id="fs-header-preview-logo-wrap-dark" style="<?php echo $logo_url ? '' : 'display:none;'; ?>">
                                                <img src="<?php echo esc_url($logo_url); ?>" alt="" class="fs-header-preview-logo" id="fs-header-preview-logo-dark">
                                            </span>
                                            <span class="fs-header-preview-biz-name" id="fs-header-preview-biz-name-dark"><?php echo esc_html($settings['business_name'] ?: __('Your Business Name', 'freelance-studio')); ?></span>
                                            <span class="fs-header-preview-title"><?php esc_html_e('Client Portal', 'freelance-studio'); ?></span>
                                        </div>
                                        <div class="fs-header-preview-body">
                                            <div class="fs-header-preview-body-line"></div>
                                            <div class="fs-header-preview-body-line"></div>
                                            <div class="fs-header-preview-body-line"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Where Each Logo Is Used', 'freelance-studio'); ?></th>
                    <td>
                        <div class="fs-logo-usage-map">
                            <div class="fs-logo-usage-group">
                                <span class="fs-logo-usage-heading"><span class="fs-logo-variant-tag fs-logo-tag-dark"><?php esc_html_e('Dark', 'freelance-studio'); ?></span> <?php esc_html_e('Default Logo — white/light backgrounds', 'freelance-studio'); ?></span>
                                <ul class="fs-logo-usage-list">
                                    <li><span class="dashicons dashicons-admin-users"></span> <?php esc_html_e('Client Portal header', 'freelance-studio'); ?></li>
                                    <li><span class="dashicons dashicons-calendar-alt"></span> <?php esc_html_e('Booking pages', 'freelance-studio'); ?></li>
                                    <li><span class="dashicons dashicons-email"></span> <?php esc_html_e('Email templates', 'freelance-studio'); ?></li>
                                    <li><span class="dashicons dashicons-pdf"></span> <?php esc_html_e('PDF exports', 'freelance-studio'); ?></li>
                                </ul>
                            </div>
                            <div class="fs-logo-usage-group">
                                <span class="fs-logo-usage-heading"><span class="fs-logo-variant-tag fs-logo-tag-light"><?php esc_html_e('Light', 'freelance-studio'); ?></span> <?php esc_html_e('Light Logo — brand color backgrounds', 'freelance-studio'); ?></span>
                                <ul class="fs-logo-usage-list">
                                    <li><span class="dashicons dashicons-media-text"></span> <?php esc_html_e('Invoice headers', 'freelance-studio'); ?></li>
                                    <li><span class="dashicons dashicons-format-aside"></span> <?php esc_html_e('Proposal headers', 'freelance-studio'); ?></li>
                                    <li><span class="dashicons dashicons-media-document"></span> <?php esc_html_e('Contract headers', 'freelance-studio'); ?></li>
                                </ul>
                            </div>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Internal Project Tracking', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Track admin tasks, internal projects, and non-client work separately from client projects.', 'freelance-studio'); ?></p>
            
            <?php 
            $internal_tracking_enabled = get_option('fs_internal_tracking_enabled', '0');
            $internal_client = FS_Client::get_internal_client();
            ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="internal_tracking_enabled"><?php esc_html_e('Enable Internal Tracking', 'freelance-studio'); ?></label></th>
                    <td>
                        <label class="fs-switch">
                            <input type="checkbox" name="internal_tracking_enabled" id="internal_tracking_enabled" value="1" <?php checked($internal_tracking_enabled, '1'); ?>>
                            <span class="fs-slider"></span>
                        </label>
                        <p class="description">
                            <?php esc_html_e('Creates an internal client for tracking business admin tasks, professional development, marketing, and other non-client work.', 'freelance-studio'); ?>
                        </p>
                    </td>
                </tr>
                <?php if ($internal_client): ?>
                <tr>
                    <th scope="row"><?php esc_html_e('Internal Client', 'freelance-studio'); ?></th>
                    <td>
                        <p>
                            <strong><?php echo esc_html($internal_client->company_name); ?></strong>
                            &nbsp;
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=edit&id=' . $internal_client->id) ); ?>" class="button button-small">
                                <?php esc_html_e('Edit', 'freelance-studio'); ?>
                            </a>
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-projects&action=new&client_id=' . $internal_client->id) ); ?>" class="button button-small button-primary">
                                <?php esc_html_e('New Internal Project', 'freelance-studio'); ?>
                            </a>
                        </p>
                        <p class="description">
                            <?php esc_html_e('Internal client data is excluded from dashboard client counts and can be filtered in reports.', 'freelance-studio'); ?>
                        </p>
                    </td>
                </tr>
                <?php endif; ?>
            </table>
        </div>
        
        <!-- Accessibility -->
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Accessibility', 'freelance-studio'); ?></h2>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('High Contrast Mode', 'freelance-studio'); ?></th>
                    <td>
                        <label class="fs-switch">
                            <input type="checkbox" name="high_contrast_mode" value="1" <?php checked(get_option('fs_high_contrast_mode', '0'), '1'); ?>>
                            <span class="fs-slider"></span>
                        </label>
                        <p class="description">
                            <?php esc_html_e('Increases contrast throughout the plugin for improved legibility. Status badges gain distinct shapes, text is darkened, and all elements meet WCAG AAA contrast standards.', 'freelance-studio'); ?>
                        </p>
                    </td>
                </tr>
            </table>
        </div>
        
        <?php endif; ?>
        <?php if ($active_tab === 'documents'): ?>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Your Signature', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Your signature will automatically appear on proposals and contracts.', 'freelance-studio'); ?></p>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label><?php esc_html_e('Signature Image', 'freelance-studio'); ?></label></th>
                    <td>
                        <div class="fs-signature-upload-container">
                            <?php if (!empty($settings['contractor_signature'])): ?>
                                <div class="fs-signature-preview" id="fs-contractor-signature-preview">
                                    <img src="<?php echo esc_attr($settings['contractor_signature']); ?>" alt="<?php esc_attr_e('Your Signature', 'freelance-studio'); ?>">
                                    <button type="button" class="button fs-clear-signature-btn" id="fs-clear-contractor-signature"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>
                                </div>
                            <?php else: ?>
                                <div class="fs-signature-preview" id="fs-contractor-signature-preview" style="display: none;">
                                    <img src="" alt=""><button type="button" class="button fs-clear-signature-btn" id="fs-clear-contractor-signature"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>
                                </div>
                            <?php endif; ?>
                            
                            <div class="fs-signature-input-wrapper" id="fs-signature-input-wrapper" <?php echo !empty($settings['contractor_signature']) ? 'style="display:none;"' : ''; ?>>
                                <div class="fs-signature-tabs">
                                    <button type="button" class="fs-signature-tab active" data-tab="draw"><?php esc_html_e('Draw Signature', 'freelance-studio'); ?></button>
                                    <button type="button" class="fs-signature-tab" data-tab="upload"><?php esc_html_e('Upload Image', 'freelance-studio'); ?></button>
                                </div>
                                <div class="fs-signature-tab-content active" id="fs-signature-tab-draw">
                                    <div class="fs-signature-pad-container">
                                        <canvas id="fs-contractor-signature-pad" class="fs-signature-pad" width="400" height="150"></canvas>
                                        <div class="fs-signature-pad-actions">
                                            <button type="button" class="button" id="fs-clear-signature-pad"><?php esc_html_e('Clear', 'freelance-studio'); ?></button>
                                            <button type="button" class="button button-primary" id="fs-save-signature"><?php esc_html_e('Save Signature', 'freelance-studio'); ?></button>
                                        </div>
                                    </div>
                                </div>
                                <div class="fs-signature-tab-content" id="fs-signature-tab-upload">
                                    <input type="file" id="fs-signature-file-input" accept="image/png,image/jpeg,image/gif" style="display:none;">
                                    <div class="fs-signature-dropzone" id="fs-signature-dropzone">
                                        <span class="dashicons dashicons-upload"></span>
                                        <p><?php esc_html_e('Drag & drop or', 'freelance-studio'); ?></p>
                                        <button type="button" class="button" id="fs-signature-browse-btn"><?php esc_html_e('Browse Files', 'freelance-studio'); ?></button>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" name="contractor_signature" id="contractor_signature" value="<?php echo esc_attr($settings['contractor_signature']); ?>">
                        </div>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="contractor_signer_name"><?php esc_html_e('Signer Name', 'freelance-studio'); ?></label></th>
                    <td><input type="text" name="contractor_signer_name" id="contractor_signer_name" class="regular-text" value="<?php echo esc_attr($settings['contractor_signer_name'] ?? $settings['business_name']); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="contractor_signer_title"><?php esc_html_e('Signer Title', 'freelance-studio'); ?></label></th>
                    <td><input type="text" name="contractor_signer_title" id="contractor_signer_title" class="regular-text" value="<?php echo esc_attr($settings['contractor_signer_title'] ?? ''); ?>" placeholder="<?php esc_attr_e('e.g., Owner, Principal Designer', 'freelance-studio'); ?>"></td>
                </tr>
            </table>
        </div>

        <div class="fs-settings-section">
            <h2><?php esc_html_e('Default Rates & Terms', 'freelance-studio'); ?></h2>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="default_hourly_rate"><?php esc_html_e('Default Hourly Rate', 'freelance-studio'); ?></label></th>
                    <td><input type="number" name="default_hourly_rate" id="default_hourly_rate" step="0.01" min="0" class="regular-text" value="<?php echo esc_attr($settings['default_hourly_rate']); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="default_payment_terms"><?php esc_html_e('Payment Terms (days)', 'freelance-studio'); ?></label></th>
                    <td><input type="number" name="default_payment_terms" id="default_payment_terms" min="0" class="regular-text" value="<?php echo esc_attr($settings['default_payment_terms']); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="default_deposit_percentage"><?php esc_html_e('Default Deposit %', 'freelance-studio'); ?></label></th>
                    <td><input type="number" name="default_deposit_percentage" id="default_deposit_percentage" min="0" max="100" class="regular-text" value="<?php echo esc_attr($settings['default_deposit_percentage']); ?>"></td>
                </tr>
            </table>
        </div>

        <div class="fs-settings-section">
            <h2><?php esc_html_e('Contract Defaults', 'freelance-studio'); ?></h2>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="contract_notice_days"><?php esc_html_e('Notice Period (days)', 'freelance-studio'); ?></label></th>
                    <td><input type="number" name="contract_notice_days" id="contract_notice_days" min="1" class="small-text" value="<?php echo esc_attr($settings['contract_notice_days'] ?? '14'); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="contract_cure_days"><?php esc_html_e('Cure Period (days)', 'freelance-studio'); ?></label></th>
                    <td><input type="number" name="contract_cure_days" id="contract_cure_days" min="1" class="small-text" value="<?php echo esc_attr($settings['contract_cure_days'] ?? '10'); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="contract_suspension_days"><?php esc_html_e('Suspension Period (days)', 'freelance-studio'); ?></label></th>
                    <td><input type="number" name="contract_suspension_days" id="contract_suspension_days" min="1" class="small-text" value="<?php echo esc_attr($settings['contract_suspension_days'] ?? '30'); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="contract_late_fee_percent"><?php esc_html_e('Late Payment Fee (%)', 'freelance-studio'); ?></label></th>
                    <td><input type="number" name="contract_late_fee_percent" id="contract_late_fee_percent" min="0" max="25" step="0.1" class="small-text" value="<?php echo esc_attr($settings['contract_late_fee_percent'] ?? '1.5'); ?>"> %</td>
                </tr>
                <tr>
                    <th scope="row"><label for="contract_jurisdiction"><?php esc_html_e('Governing Jurisdiction', 'freelance-studio'); ?></label></th>
                    <td><input type="text" name="contract_jurisdiction" id="contract_jurisdiction" class="regular-text" value="<?php echo esc_attr($settings['contract_jurisdiction'] ?? ''); ?>" placeholder="<?php esc_attr_e('e.g., Georgia, USA', 'freelance-studio'); ?>"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="contract_review_days"><?php esc_html_e('Review Period (days)', 'freelance-studio'); ?></label></th>
                    <td><input type="number" name="contract_review_days" id="contract_review_days" min="1" class="small-text" value="<?php echo esc_attr($settings['contract_review_days'] ?? '5'); ?>"></td>
                </tr>
            </table>
        </div>
        
        <?php endif; ?>
        
        <!-- ============================================
             INVOICES TAB
             ============================================ -->
        <?php if ($active_tab === 'invoices'): ?>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Invoice Settings', 'freelance-studio'); ?></h2>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="invoice_prefix"><?php esc_html_e('Invoice Number Prefix', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="text" name="invoice_prefix" id="invoice_prefix" class="regular-text" value="<?php echo esc_attr($settings['invoice_prefix']); ?>">
                        <p class="description"><?php esc_html_e('e.g., INV (format: PREFIX-YEAR-XXXX)', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="payment_instructions"><?php esc_html_e('Payment Instructions', 'freelance-studio'); ?></label></th>
                    <td>
                        <?php 
                        $pi_content = is_array($settings['payment_instructions']) ? implode("\n", $settings['payment_instructions']) : $settings['payment_instructions'];
                        wp_editor($pi_content, 'payment_instructions', array(
                            'textarea_name' => 'payment_instructions',
                            'textarea_rows' => 5,
                            'media_buttons' => false,
                            'teeny'         => true,
                            'quicktags'     => true,
                            'tinymce'       => array(
                                'toolbar1' => 'bold,italic,underline,link,unlink,bullist,numlist,undo,redo',
                                'toolbar2' => '',
                            ),
                        ));
                        ?>
                        <p class="description"><?php esc_html_e('This appears at the bottom of your invoices. You can add formatting, links, and lists.', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="payment_url"><?php esc_html_e('Payment Link', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="url" name="payment_url" id="payment_url" class="regular-text" value="<?php echo esc_attr($settings['payment_url']); ?>" placeholder="https://paypal.me/YourName">
                        <p class="description"><?php esc_html_e('Adds a "Pay Now" button to client-facing invoices. Accepts any payment URL.', 'freelance-studio'); ?></p>
                        <div style="margin-top: 10px; padding: 12px 16px; background: var(--fs-primary-xtralight, #e0f7f3); border-radius: 8px; font-size: 13px; line-height: 1.6; color: var(--fs-gray-700, #4B5563);">
                            <strong style="color: var(--fs-gray-800, #374151);"><?php esc_html_e('Smart amount pass-through', 'freelance-studio'); ?></strong><br>
                            <?php esc_html_e('PayPal.Me and Venmo links will automatically have the invoice balance and reference appended so your client sees the correct amount pre-filled — no manual entry needed.', 'freelance-studio'); ?>
                            <ul style="margin: 8px 0 0 18px; padding: 0; list-style: disc;">
                                <li><strong>PayPal.Me</strong> — <?php esc_html_e('e.g.', 'freelance-studio'); ?> <code style="font-size: 12px;">https://paypal.me/YourName</code></li>
                                <li><strong>Venmo</strong> — <?php esc_html_e('e.g.', 'freelance-studio'); ?> <code style="font-size: 12px;">https://venmo.com/YourUsername</code></li>
                            </ul>
                            <span style="font-size: 12px; color: var(--fs-gray-500, #9CA3AF);"><?php esc_html_e('Other links (Stripe, Wise, etc.) will still show the Pay Now button but the client may need to enter the amount manually.', 'freelance-studio'); ?></span>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="invoice_primary_color_invoices"><?php esc_html_e('Primary Color', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="color" name="invoice_primary_color" id="invoice_primary_color_invoices" value="<?php echo esc_attr($settings['invoice_primary_color']); ?>">
                        <p class="description"><?php esc_html_e('Used for buttons and accents on public invoices, proposals, and contracts.', 'freelance-studio'); ?></p>
                    </td>
                </tr>
            </table>
        </div>

        <div class="fs-settings-section">
            <h2><?php esc_html_e('Payment Reminders', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Automatically send email reminders for unpaid invoices.', 'freelance-studio'); ?></p>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="reminder_enabled"><?php esc_html_e('Enable Reminders', 'freelance-studio'); ?></label></th>
                    <td>
                        <label>
                            <input type="checkbox" name="reminder_enabled" id="reminder_enabled" value="1" <?php checked(get_option('fs_reminder_enabled', '1'), '1'); ?>>
                            <?php esc_html_e('Automatically send payment reminders', 'freelance-studio'); ?>
                        </label>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="reminder_before_due"><?php esc_html_e('Before Due Date', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="number" name="reminder_before_due" id="reminder_before_due" min="0" max="30" class="small-text" value="<?php echo esc_attr(get_option('fs_reminder_before_due', '3')); ?>">
                        <?php esc_html_e('days before due date', 'freelance-studio'); ?>
                        <p class="description"><?php esc_html_e('Set to 0 to disable', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Overdue Reminders', 'freelance-studio'); ?></th>
                    <td>
                        <div class="fs-reminder-schedule">
                            <div class="fs-reminder-row">
                                <strong><?php esc_html_e('1st Notice:', 'freelance-studio'); ?></strong>
                                <input type="number" name="reminder_after_due_1" min="0" max="90" class="small-text" value="<?php echo esc_attr(get_option('fs_reminder_after_due_1', '1')); ?>">
                                <?php esc_html_e('days after due date', 'freelance-studio'); ?>
                            </div>
                            <div class="fs-reminder-row">
                                <strong><?php esc_html_e('2nd Notice:', 'freelance-studio'); ?></strong>
                                <input type="number" name="reminder_after_due_2" min="0" max="90" class="small-text" value="<?php echo esc_attr(get_option('fs_reminder_after_due_2', '7')); ?>">
                                <?php esc_html_e('days after due date', 'freelance-studio'); ?>
                            </div>
                            <div class="fs-reminder-row">
                                <strong><?php esc_html_e('3rd Notice:', 'freelance-studio'); ?></strong>
                                <input type="number" name="reminder_after_due_3" min="0" max="90" class="small-text" value="<?php echo esc_attr(get_option('fs_reminder_after_due_3', '14')); ?>">
                                <?php esc_html_e('days after due date', 'freelance-studio'); ?>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="reminder_subject_before"><?php esc_html_e('Pre-Due Subject', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="text" name="reminder_subject_before" id="reminder_subject_before" class="large-text" value="<?php echo esc_attr(get_option('fs_reminder_subject_before', 'Friendly reminder: Invoice {invoice_number} due soon')); ?>">
                        <p class="description"><?php esc_html_e('Placeholders: {invoice_number}, {client_name}, {amount}, {due_date}', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="reminder_subject_overdue"><?php esc_html_e('Overdue Subject', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="text" name="reminder_subject_overdue" id="reminder_subject_overdue" class="large-text" value="<?php echo esc_attr(get_option('fs_reminder_subject_overdue', 'Invoice {invoice_number} is overdue')); ?>">
                    </td>
                </tr>
            </table>
        </div>
        
        <!-- Invoice Sales Tax Section -->
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Invoice Sales Tax', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Set a default sales tax rate to charge clients on invoices.', 'freelance-studio'); ?></p>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="default_sales_tax_rate"><?php esc_html_e('Default Sales Tax Rate', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="number" name="default_sales_tax_rate" id="default_sales_tax_rate" 
                               value="<?php echo esc_attr(get_option('fs_default_sales_tax_rate', '0')); ?>" 
                               step="0.001" min="0" max="25" class="small-text"> %
                        <p class="description"><?php esc_html_e('This rate will auto-populate on new invoices. You can adjust it per invoice as needed.', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Auto-apply Sales Tax', 'freelance-studio'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="auto_apply_sales_tax" value="1" <?php checked(get_option('fs_auto_apply_sales_tax', '0'), '1'); ?>>
                            <?php esc_html_e('Automatically apply default sales tax rate to new invoices', 'freelance-studio'); ?>
                        </label>
                    </td>
                </tr>
            </table>
        </div>
        
        <?php endif; ?>
        
        <!-- ============================================
             TIME TRACKING TAB
             ============================================ -->
        <?php if ($active_tab === 'time'): 
            $custom_activities = get_option('fs_custom_activities', array());
            if (!is_array($custom_activities)) $custom_activities = array();
        ?>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Timezone', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Set your local timezone for accurate time tracking.', 'freelance-studio'); ?></p>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="user_timezone"><?php esc_html_e('Your Timezone', 'freelance-studio'); ?></label></th>
                    <td>
                        <?php 
                        $user_timezone = get_option('fs_user_timezone', 'America/New_York');
                        $timezones = timezone_identifiers_list();
                        ?>
                        <select name="user_timezone" id="user_timezone" class="regular-text">
                            <?php foreach ($timezones as $tz): ?>
                                <option value="<?php echo esc_attr($tz); ?>" <?php selected($user_timezone, $tz); ?>><?php echo esc_html($tz); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <p class="description">
                            <?php 
                            $current_time = new DateTime('now', new DateTimeZone($user_timezone));
                            /* translators: 1. recipient name */
                            echo esc_html( sprintf( __( 'Current time in this timezone: %s', 'freelance-studio'), $current_time->format('g:i A, M j, Y')) );
                            ?>
                        </p>
                    </td>
                </tr>
            </table>
        </div>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Time Rounding', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Round time entries for cleaner billing. Applied when generating invoices.', 'freelance-studio'); ?></p>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="time_rounding"><?php esc_html_e('Round Time To', 'freelance-studio'); ?></label></th>
                    <td>
                        <select name="time_rounding" id="time_rounding">
                            <option value="0" <?php selected(get_option('fs_time_rounding', '0'), '0'); ?>><?php esc_html_e('No rounding (exact time)', 'freelance-studio'); ?></option>
                            <option value="1" <?php selected(get_option('fs_time_rounding', '0'), '1'); ?>><?php esc_html_e('Nearest 1 minute', 'freelance-studio'); ?></option>
                            <option value="5" <?php selected(get_option('fs_time_rounding', '0'), '5'); ?>><?php esc_html_e('Nearest 5 minutes', 'freelance-studio'); ?></option>
                            <option value="6" <?php selected(get_option('fs_time_rounding', '0'), '6'); ?>><?php esc_html_e('Nearest 6 minutes (0.1 hour)', 'freelance-studio'); ?></option>
                            <option value="15" <?php selected(get_option('fs_time_rounding', '0'), '15'); ?>><?php esc_html_e('Nearest 15 minutes (0.25 hour)', 'freelance-studio'); ?></option>
                            <option value="30" <?php selected(get_option('fs_time_rounding', '0'), '30'); ?>><?php esc_html_e('Nearest 30 minutes (0.5 hour)', 'freelance-studio'); ?></option>
                            <option value="60" <?php selected(get_option('fs_time_rounding', '0'), '60'); ?>><?php esc_html_e('Nearest hour', 'freelance-studio'); ?></option>
                        </select>
                        <p class="description"><?php esc_html_e('Time is rounded up to the nearest interval (e.g., 7 minutes → 15 minutes)', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="minimum_billable"><?php esc_html_e('Minimum Billable Time', 'freelance-studio'); ?></label></th>
                    <td>
                        <select name="minimum_billable" id="minimum_billable">
                            <option value="0" <?php selected(get_option('fs_minimum_billable', '0'), '0'); ?>><?php esc_html_e('No minimum', 'freelance-studio'); ?></option>
                            <option value="5" <?php selected(get_option('fs_minimum_billable', '0'), '5'); ?>><?php esc_html_e('5 minutes', 'freelance-studio'); ?></option>
                            <option value="6" <?php selected(get_option('fs_minimum_billable', '0'), '6'); ?>><?php esc_html_e('6 minutes (0.1 hour)', 'freelance-studio'); ?></option>
                            <option value="15" <?php selected(get_option('fs_minimum_billable', '0'), '15'); ?>><?php esc_html_e('15 minutes', 'freelance-studio'); ?></option>
                            <option value="30" <?php selected(get_option('fs_minimum_billable', '0'), '30'); ?>><?php esc_html_e('30 minutes', 'freelance-studio'); ?></option>
                            <option value="60" <?php selected(get_option('fs_minimum_billable', '0'), '60'); ?>><?php esc_html_e('1 hour', 'freelance-studio'); ?></option>
                        </select>
                        <p class="description"><?php esc_html_e('Any entry shorter than this will be rounded up to the minimum', 'freelance-studio'); ?></p>
                    </td>
                </tr>
            </table>
        </div>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Time Goals', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Set targets to track your productivity on the dashboard.', 'freelance-studio'); ?></p>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="weekly_goal"><?php esc_html_e('Weekly Goal', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="number" name="weekly_goal" id="weekly_goal" min="0" max="168" step="0.5" class="small-text" value="<?php echo esc_attr(get_option('fs_weekly_goal', '40')); ?>">
                        <?php esc_html_e('hours per week', 'freelance-studio'); ?>
                        <p class="description"><?php esc_html_e('Set to 0 to disable the weekly goal tracker', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="daily_goal"><?php esc_html_e('Daily Goal', 'freelance-studio'); ?></label></th>
                    <td>
                        <input type="number" name="daily_goal" id="daily_goal" min="0" max="24" step="0.5" class="small-text" value="<?php echo esc_attr(get_option('fs_daily_goal', '8')); ?>">
                        <?php esc_html_e('hours per day', 'freelance-studio'); ?>
                        <p class="description"><?php esc_html_e('Set to 0 to disable the daily goal tracker', 'freelance-studio'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Work Days', 'freelance-studio'); ?></th>
                    <td>
                        <?php 
                        $work_days = get_option('fs_work_days', array('1','2','3','4','5'));
                        if (!is_array($work_days)) $work_days = array('1','2','3','4','5');
                        $day_names = array(
                            '0' => __('Sunday', 'freelance-studio'),
                            '1' => __('Monday', 'freelance-studio'),
                            '2' => __('Tuesday', 'freelance-studio'),
                            '3' => __('Wednesday', 'freelance-studio'),
                            '4' => __('Thursday', 'freelance-studio'),
                            '5' => __('Friday', 'freelance-studio'),
                            '6' => __('Saturday', 'freelance-studio'),
                        );
                        ?>
                        <div class="fs-work-days-grid">
                            <?php foreach ($day_names as $value => $label): ?>
                            <label class="fs-work-day-checkbox">
                                <input type="checkbox" name="work_days[]" value="<?php echo  esc_attr( $value ); ?>" <?php checked(in_array($value, $work_days)); ?>>
                                <?php echo  esc_html( $label ); ?>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        <p class="description"><?php esc_html_e('Select which days count toward your weekly goal', 'freelance-studio'); ?></p>
                    </td>
                </tr>
            </table>
        </div>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Task Management', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Configure automatic task lifecycle behaviour.', 'freelance-studio'); ?></p>

            <table class="form-table">
                <tr>
                    <th scope="row"><label for="auto_archive_completed_tasks"><?php esc_html_e('Auto-archive Completed Tasks', 'freelance-studio'); ?></label></th>
                    <td>
                        <select name="auto_archive_completed_tasks" id="auto_archive_completed_tasks">
                            <option value="0" <?php selected(get_option('fs_auto_archive_completed_tasks', '0'), '0'); ?>><?php esc_html_e('Never (manual only)', 'freelance-studio'); ?></option>
                            <option value="7"  <?php selected(get_option('fs_auto_archive_completed_tasks', '0'), '7'); ?>><?php esc_html_e('After 7 days', 'freelance-studio'); ?></option>
                            <option value="14" <?php selected(get_option('fs_auto_archive_completed_tasks', '0'), '14'); ?>><?php esc_html_e('After 14 days', 'freelance-studio'); ?></option>
                            <option value="30" <?php selected(get_option('fs_auto_archive_completed_tasks', '0'), '30'); ?>><?php esc_html_e('After 30 days', 'freelance-studio'); ?></option>
                            <option value="60" <?php selected(get_option('fs_auto_archive_completed_tasks', '0'), '60'); ?>><?php esc_html_e('After 60 days', 'freelance-studio'); ?></option>
                        </select>
                        <p class="description"><?php esc_html_e('Completed tasks will be automatically moved to the Archived tab after the selected period. The daily cron job handles this sweep.', 'freelance-studio'); ?></p>
                    </td>
                </tr>
            </table>
        </div>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Activity Types', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Customize the activity categories for time entries.', 'freelance-studio'); ?></p>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="default_activity"><?php esc_html_e('Default Activity', 'freelance-studio'); ?></label></th>
                    <td>
                        <select name="default_activity" id="default_activity">
                            <?php 
                            $default_activity = get_option('fs_default_activity', 'development');
                            $activity_types = FS_Time_Entry::get_activity_types();
                            foreach ($activity_types as $key => $label): 
                            ?>
                            <option value="<?php echo esc_attr($key); ?>" <?php selected($default_activity, $key); ?>><?php echo esc_html($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label><?php esc_html_e('Custom Activities', 'freelance-studio'); ?></label></th>
                    <td>
                        <div id="fs-custom-activities">
                            <?php if (!empty($custom_activities)): ?>
                                <?php foreach ($custom_activities as $i => $activity): ?>
                                <div class="fs-custom-activity-row">
                                    <input type="text" name="custom_activities[]" value="<?php echo esc_attr($activity); ?>" placeholder="<?php esc_attr_e('Activity name', 'freelance-studio'); ?>">
                                    <button type="button" class="button fs-remove-activity"><span class="dashicons dashicons-no-alt"></span></button>
                                </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <button type="button" class="button" id="fs-add-activity">
                            <span class="dashicons dashicons-plus-alt2"></span> <?php esc_html_e('Add Activity', 'freelance-studio'); ?>
                        </button>
                        <p class="description"><?php esc_html_e('Add custom activity types in addition to the defaults', 'freelance-studio'); ?></p>
                    </td>
                </tr>
            </table>
        </div>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Timer Behavior', 'freelance-studio'); ?></h2>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('Long Timer Warning', 'freelance-studio'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="timer_warning_enabled" value="1" <?php checked(get_option('fs_timer_warning_enabled', '1'), '1'); ?>>
                            <?php esc_html_e('Show warning when timer exceeds', 'freelance-studio'); ?>
                        </label>
                        <input type="number" name="timer_warning_hours" min="1" max="24" class="small-text" value="<?php echo esc_attr(get_option('fs_timer_warning_hours', '8')); ?>">
                        <?php esc_html_e('hours', 'freelance-studio'); ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Keyboard Shortcuts', 'freelance-studio'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="keyboard_shortcuts" value="1" <?php checked(get_option('fs_keyboard_shortcuts', '1'), '1'); ?>>
                            <?php esc_html_e('Enable keyboard shortcuts for timer', 'freelance-studio'); ?>
                        </label>
                        <p class="description">
                            <?php esc_html_e('Shortcuts:', 'freelance-studio'); ?><br>
                            <code>Alt + S</code> (PC) / <code>Option + S</code> (Mac) - <?php esc_html_e('Start/Stop timer', 'freelance-studio'); ?><br>
                            <code>Alt + P</code> (PC) / <code>Option + P</code> (Mac) - <?php esc_html_e('Pause/Resume timer', 'freelance-studio'); ?><br>
                            <code>Alt + T</code> (PC) / <code>Option + T</code> (Mac) - <?php esc_html_e('Go to Time Tracking', 'freelance-studio'); ?><br>
                            <code>Alt + /</code> (PC) / <code>Option + /</code> (Mac) - <?php esc_html_e('Show shortcuts help', 'freelance-studio'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Browser Notifications', 'freelance-studio'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="browser_notifications" value="1" <?php checked(get_option('fs_browser_notifications', '1'), '1'); ?>>
                            <?php esc_html_e('Enable browser notifications for timer', 'freelance-studio'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Get notified when the timer has been running for a long time, or when you have a timer still running.', 'freelance-studio'); ?></p>
                        <button type="button" class="button" id="fs-test-notification"><?php esc_html_e('Test Notification', 'freelance-studio'); ?></button>
                    </td>
                </tr>
            </table>
        </div>
        
        <p class="submit">
            <button type="submit" class="button button-primary"><?php esc_html_e('Save Time Tracking Settings', 'freelance-studio'); ?></button>
        </p>
        
        <script>
        jQuery(document).ready(function($) {
            // Add custom activity
            $('#fs-add-activity').on('click', function() {
                var $row = $('<div class="fs-custom-activity-row">' +
                    '<input type="text" name="custom_activities[]" placeholder="<?php esc_attr_e('Activity name', 'freelance-studio'); ?>">' +
                    '<button type="button" class="button fs-remove-activity"><span class="dashicons dashicons-no-alt"></span></button>' +
                    '</div>');
                $('#fs-custom-activities').append($row);
            });
            
            // Remove custom activity
            $(document).on('click', '.fs-remove-activity', function() {
                $(this).closest('.fs-custom-activity-row').remove();
            });
            
            // Test notification button
            $('#fs-test-notification').on('click', function() {
                if (!('Notification' in window)) {
                    alert('<?php esc_html_e('Your browser does not support notifications.', 'freelance-studio'); ?>');
                    return;
                }
                
                if (Notification.permission === 'granted') {
                    new Notification('Freelance Studio', {
                        body: '<?php esc_html_e('Notifications are working! You will be notified about your timer.', 'freelance-studio'); ?>',
                        icon: '<?php echo  esc_url( plugins_url('admin/images/icon.png', dirname(dirname(__FILE__))) ); ?>'
                    });
                } else if (Notification.permission === 'denied') {
                    alert('<?php esc_html_e('Notifications are blocked. Please enable them in your browser settings.', 'freelance-studio'); ?>');
                } else {
                    Notification.requestPermission().then(function(permission) {
                        if (permission === 'granted') {
                            new Notification('Freelance Studio', {
                                body: '<?php esc_html_e('Notifications are now enabled!', 'freelance-studio'); ?>'
                            });
                        } else {
                            alert('<?php esc_html_e('You need to allow notifications for this feature to work.', 'freelance-studio'); ?>');
                        }
                    });
                }
            });
        });
        </script>
        
        <?php endif; ?>
        
        <!-- ============================================
             EMAIL TEMPLATES TAB
             ============================================ -->
        <?php if ($active_tab === 'emails'): 
            $template_types = FS_Email_Template::get_template_types();
            $editing_template = isset($_GET['edit_email']) ? sanitize_text_field($_GET['edit_email']) : null;
        ?>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Email Notifications', 'freelance-studio'); ?></h2>
            <p class="description mb-15"><?php esc_html_e('Get notified when a client views your documents for the first time.', 'freelance-studio'); ?></p>
            
            <table class="form-table fs-notification-toggles">
                <tr>
                    <th scope="row"><label><?php esc_html_e('Proposal viewed', 'freelance-studio'); ?></label></th>
                    <td>
                        <label class="fs-switch">
                            <input type="checkbox" name="notify_proposal_viewed" value="1" 
                                data-option="fs_notify_proposal_viewed"
                                <?php checked(get_option('fs_notify_proposal_viewed', '0'), '1'); ?>>
                            <span class="fs-slider"></span>
                        </label>
                        <span class="description"><?php esc_html_e('Email me when a proposal is opened for the first time', 'freelance-studio'); ?></span>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label><?php esc_html_e('Contract viewed', 'freelance-studio'); ?></label></th>
                    <td>
                        <label class="fs-switch">
                            <input type="checkbox" name="notify_contract_viewed" value="1"
                                data-option="fs_notify_contract_viewed"
                                <?php checked(get_option('fs_notify_contract_viewed', '0'), '1'); ?>>
                            <span class="fs-slider"></span>
                        </label>
                        <span class="description"><?php esc_html_e('Email me when a contract is opened for the first time', 'freelance-studio'); ?></span>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label><?php esc_html_e('Invoice viewed', 'freelance-studio'); ?></label></th>
                    <td>
                        <label class="fs-switch">
                            <input type="checkbox" name="notify_invoice_viewed" value="1"
                                data-option="fs_notify_invoice_viewed"
                                <?php checked(get_option('fs_notify_invoice_viewed', '0'), '1'); ?>>
                            <span class="fs-slider"></span>
                        </label>
                        <span class="description"><?php esc_html_e('Email me when an invoice is opened for the first time', 'freelance-studio'); ?></span>
                    </td>
                </tr>
            </table>
            
            <script>
            jQuery(function($) {
                $('.fs-notification-toggles input[type="checkbox"]').on('change', function() {
                    var $toggle = $(this);
                    var optionName = $toggle.data('option');
                    var value = $toggle.is(':checked') ? '1' : '0';
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'fs_auto_save_settings',
                            nonce: '<?php echo esc_attr( wp_create_nonce("fs_auto_save_settings") ); ?>',
                            field: optionName.replace('fs_', ''),
                            value: value
                        }
                    });
                });
            });
            </script>
        </div>
        
        <div class="fs-settings-section">
            <h2><?php esc_html_e('Email Templates', 'freelance-studio'); ?></h2>
            <div class="fs-email-template-mobile-notice">
                <span class="dashicons dashicons-desktop"></span>
                <?php esc_html_e('Email template editing is best used on a desktop browser for the full editor experience.', 'freelance-studio'); ?>
            </div>
            <div class="fs-email-templates-content">
            <p class="description mb-15"><?php esc_html_e('Customize the emails sent to clients. Use variables like {client_name} to personalize messages.', 'freelance-studio'); ?></p>
            
            <?php 
                // Get branding settings for email header preview
                $email_primary_color = get_option('fs_invoice_primary_color', '');
                if (empty($email_primary_color)) {
                    $email_primary_color = '#4173B0';
                }
                $email_logo_url = get_option('fs_business_logo_light', '');
                if (empty($email_logo_url)) {
                    $email_logo_url = get_option('fs_business_logo', '');
                }
                $email_business_name = get_option('fs_business_name', get_bloginfo('name'));
            ?>
            
            <?php if ($editing_template && isset($template_types[$editing_template])): 
                $template_info = $template_types[$editing_template];
                $template_data = FS_Email_Template::get($editing_template);
            ?>
                <!-- Edit Template Form -->
                <div class="fs-email-template-editor">
                    <div class="fs-editor-header">
                        <h3><?php echo esc_html($template_info['label']); ?></h3>
                        <p class="description"><?php echo esc_html($template_info['description']); ?></p>
                    </div>
                    
                    <form method="post" action="">
                        <?php wp_nonce_field('fs_save_email_template', 'fs_email_template_nonce'); ?>
                        <input type="hidden" name="template_type" value="<?php echo esc_attr($editing_template); ?>">
                        
                        <div class="fs-email-editor-split">
                            <!-- Left: Code Editor -->
                            <div class="fs-editor-code-panel">
                                <div class="fs-editor-toolbar">
                                    <span class="fs-toolbar-label"><?php esc_html_e('HTML Editor', 'freelance-studio'); ?></span>
                                    <div class="fs-toolbar-buttons">
                                        <button type="button" class="fs-toolbar-btn" data-insert="&lt;p&gt;" data-insert-end="&lt;/p&gt;" title="<?php esc_attr_e('Paragraph', 'freelance-studio'); ?>">¶ P</button>
                                        <button type="button" class="fs-toolbar-btn" data-insert="&lt;br&gt;" title="<?php esc_attr_e('Line Break', 'freelance-studio'); ?>">↵ BR</button>
                                        <button type="button" class="fs-toolbar-btn" data-insert="&lt;strong&gt;" data-insert-end="&lt;/strong&gt;" title="<?php esc_attr_e('Bold', 'freelance-studio'); ?>"><strong>B</strong></button>
                                        <button type="button" class="fs-toolbar-btn" data-insert="&lt;em&gt;" data-insert-end="&lt;/em&gt;" title="<?php esc_attr_e('Italic', 'freelance-studio'); ?>"><em>I</em></button>
                                        <button type="button" class="fs-toolbar-btn" data-insert="&lt;a href=&quot;&quot;&gt;" data-insert-end="&lt;/a&gt;" title="<?php esc_attr_e('Link', 'freelance-studio'); ?>">🔗</button>
                                    </div>
                                </div>
                                
                                <table class="form-table" style="margin-top: 0;">
                                    <tr>
                                        <th scope="row" style="width: 100px;">
                                            <label for="email_subject"><?php esc_html_e('Subject', 'freelance-studio'); ?></label>
                                        </th>
                                        <td>
                                            <input type="text" name="email_subject" id="email_subject" class="large-text" value="<?php echo esc_attr($template_data['subject']); ?>">
                                        </td>
                                    </tr>
                                </table>
                                
                                <label for="email_body" class="screen-reader-text"><?php esc_html_e('Email Body', 'freelance-studio'); ?></label>
                                <div class="fs-syntax-editor-wrapper">
                                    <pre class="fs-syntax-highlight" id="syntax-highlight" aria-hidden="true"></pre>
                                    <textarea name="email_body" id="email_body" class="fs-code-editor" rows="20" spellcheck="false"><?php echo esc_textarea($template_data['body']); ?></textarea>
                                </div>
                                
                                <div class="fs-editor-actions">
                                    <input type="submit" name="save_email_template" class="fs-btn fs-btn-primary" value="<?php esc_attr_e('Save Template', 'freelance-studio'); ?>">
                                    <button type="submit" name="send_test_email" class="fs-btn fs-btn-secondary"><?php esc_html_e('Send Test Email', 'freelance-studio'); ?></button>
                                    <a href="?page=fs-settings&tab=emails" class="fs-btn fs-btn-secondary"><?php esc_html_e('Cancel', 'freelance-studio'); ?></a>
                                    <?php if ($template_data['is_custom']): ?>
                                        <input type="submit" name="reset_email_template" class="fs-btn fs-btn-danger" value="<?php esc_attr_e('Reset to Default', 'freelance-studio'); ?>" onclick="return confirm('<?php esc_html_e('Are you sure you want to reset this template to the default?', 'freelance-studio'); ?>');" style="margin-left: auto;">
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Right: Live Preview -->
                            <div class="fs-editor-preview-panel">
                                <div class="fs-preview-header">
                                    <span class="fs-toolbar-label"><?php esc_html_e('Live Preview', 'freelance-studio'); ?></span>
                                </div>
                                <div class="fs-preview-email-wrapper">
                                    <div class="fs-preview-email-frame" id="email-preview-frame">
                                        <!-- Preview content injected by JavaScript -->
                                    </div>
                                </div>
                                
                                <div class="fs-variables-panel">
                                    <h4><?php esc_html_e('Available Variables', 'freelance-studio'); ?> <small>(<?php esc_html_e('click to insert', 'freelance-studio'); ?>)</small></h4>
                                    <div class="fs-variables-grid">
                                        <?php foreach ($template_info['variables'] as $var => $desc): ?>
                                            <code class="fs-variable-tag" data-variable="<?php echo esc_attr($var); ?>" title="<?php echo esc_attr($desc); ?>"><?php echo esc_html($var); ?></code>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <script>
                        jQuery(document).ready(function($) {
                            var $editor = $('#email_body');
                            var $highlight = $('#syntax-highlight');
                            var $preview = $('#email-preview-frame');
                            var $subject = $('#email_subject');
                            
                            // Sample data for preview
                            var sampleData = {
                                '{client_name}': 'Sample Client',
                                '{invoice_number}': 'INV-2025-001',
                                '{amount}': '$1,500.00',
                                '{due_date}': '<?php echo  esc_html( gmdate('F j, Y', strtotime('+7 days')) ); ?>',
                                '{days_until_due}': '7',
                                '{days_overdue}': '3',
                                '{view_link}': '<?php echo  esc_url( home_url() ); ?>',
                                '{business_name}': '<?php echo esc_js(get_option('fs_business_name', get_bloginfo('name'))); ?>',
                                '{proposal_title}': 'Sample Proposal',
                                '{contract_title}': 'Sample Contract',
                                '{expires_date}': '<?php echo  esc_html( gmdate('F j, Y', strtotime('+30 days')) ); ?>',
                                '{payment_date}': '<?php echo  esc_html( gmdate('F j, Y') ); ?>',
                                '{project_name}': 'Sample Project',
                                '{current_month}': '<?php echo  esc_html( gmdate('F') ); ?>'
                            };
                            
                            // Syntax highlighting function
                            function highlightSyntax(code) {
                                var result = '';
                                var i = 0;
                                var len = code.length;
                                
                                while (i < len) {
                                    // Check for HTML tag
                                    if (code[i] === '<') {
                                        var tagEnd = code.indexOf('>', i);
                                        if (tagEnd !== -1) {
                                            var tag = code.substring(i, tagEnd + 1);
                                            result += highlightTag(tag);
                                            i = tagEnd + 1;
                                            continue;
                                        }
                                    }
                                    
                                    // Check for variable {name}
                                    if (code[i] === '{') {
                                        var varEnd = code.indexOf('}', i);
                                        if (varEnd !== -1 && varEnd - i < 30) { // reasonable variable length
                                            var varName = code.substring(i, varEnd + 1);
                                            if (/^\{[a-z_]+\}$/i.test(varName)) {
                                                result += '<span class="hl-variable">' + escapeHtml(varName) + '</span>';
                                                i = varEnd + 1;
                                                continue;
                                            }
                                        }
                                    }
                                    
                                    // Regular character - escape and add
                                    result += escapeHtml(code[i]);
                                    i++;
                                }
                                
                                // Highlight URLs in the result (but not inside tags)
                                result = result.replace(/(?<!="|'|&quot;)(https?:\/\/[^\s<&]+)/g, '<span class="hl-url">$1</span>');
                                
                                return result + '\n';
                            }
                            
                            function escapeHtml(text) {
                                return text
                                    .replace(/&/g, '&amp;')
                                    .replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/"/g, '&quot;');
                            }
                            
                            function highlightTag(tag) {
                                // Check if closing tag
                                var closingMatch = tag.match(/^<\/(\w+)>$/);
                                if (closingMatch) {
                                    return '<span class="hl-punctuation">&lt;/</span>' +
                                           '<span class="hl-tag">' + closingMatch[1] + '</span>' +
                                           '<span class="hl-punctuation">&gt;</span>';
                                }
                                
                                // Opening tag - parse it
                                var match = tag.match(/^<(\w+)([\s\S]*)>$/);
                                if (!match) {
                                    return escapeHtml(tag);
                                }
                                
                                var tagName = match[1];
                                var attrsStr = match[2];
                                
                                var result = '<span class="hl-punctuation">&lt;</span>';
                                result += '<span class="hl-tag">' + tagName + '</span>';
                                
                                // Parse attributes
                                if (attrsStr) {
                                    // Match attributes: name="value" or name='value'
                                    var attrRegex = /(\s+)([\w-]+)(=)("[^"]*"|'[^']*')/g;
                                    var lastIndex = 0;
                                    var attrMatch;
                                    
                                    while ((attrMatch = attrRegex.exec(attrsStr)) !== null) {
                                        // Add any text before this attribute
                                        if (attrMatch.index > lastIndex) {
                                            result += escapeHtml(attrsStr.substring(lastIndex, attrMatch.index));
                                        }
                                        
                                        result += attrMatch[1]; // whitespace
                                        result += '<span class="hl-attr-name">' + attrMatch[2] + '</span>';
                                        result += '<span class="hl-punctuation">' + attrMatch[3] + '</span>';
                                        result += '<span class="hl-attr-value">' + escapeHtml(attrMatch[4]) + '</span>';
                                        
                                        lastIndex = attrMatch.index + attrMatch[0].length;
                                    }
                                    
                                    // Add remaining text
                                    if (lastIndex < attrsStr.length) {
                                        result += escapeHtml(attrsStr.substring(lastIndex));
                                    }
                                }
                                
                                result += '<span class="hl-punctuation">&gt;</span>';
                                return result;
                            }
                            
                            function updateHighlight() {
                                var code = $editor.val();
                                $highlight.html(highlightSyntax(code));
                            }
                            
                            function updatePreview() {
                                var content = $editor.val();
                                
                                // Replace variables with sample data
                                for (var key in sampleData) {
                                    content = content.split(key).join(sampleData[key]);
                                }
                                
                                // Build full email preview with header and footer
                                var primaryColor = <?php echo wp_json_encode($email_primary_color); ?>;
                                var logoUrl = <?php echo wp_json_encode($email_logo_url); ?>;
                                var businessName = <?php echo wp_json_encode($email_business_name); ?>;
                                
                                var headerContent = '';
                                if (logoUrl) {
                                    headerContent = '<img src="' + logoUrl + '" alt="' + businessName + '" style="max-width: 180px; max-height: 60px;">';
                                } else {
                                    headerContent = '<span style="margin: 0; color: #ffffff; font-size: 20px; font-weight: 600;">' + businessName + '</span>';
                                }
                                
                                var html = '<div style="background-color: #f3f4f6; padding: 20px; border-radius: 8px;">'
                                    + '<div style="max-width: 100%; background-color: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">'
                                    + '<div style="padding: 24px; text-align: center; background-color: ' + primaryColor + ';">'
                                    + headerContent
                                    + '</div>'
                                    + '<div style="padding: 28px 24px; color: #374151; font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif; font-size: 14px; line-height: 1.6;">'
                                    + content
                                    + '</div>'
                                    + '<div style="padding: 16px 24px; background-color: #f9fafb; border-top: 1px solid #e5e7eb;">'
                                    + '<p style="margin: 0; color: #9ca3af; font-size: 11px; text-align: center;">' + businessName + '</p>'
                                    + '</div>'
                                    + '</div>'
                                    + '</div>';
                                
                                $preview.html(html);
                            }
                            
                            function syncScroll() {
                                $highlight.scrollTop($editor.scrollTop());
                                $highlight.scrollLeft($editor.scrollLeft());
                            }
                            
                            // Update both highlight and preview on input
                            $editor.on('input keyup', function() {
                                updateHighlight();
                                updatePreview();
                            });
                            
                            // Sync scrolling
                            $editor.on('scroll', syncScroll);
                            
                            // Initial update
                            updateHighlight();
                            updatePreview();
                            
                            // Toolbar button handling
                            $('.fs-toolbar-btn').on('click', function(e) {
                                e.preventDefault();
                                var insertStart = $(this).data('insert') || '';
                                var insertEnd = $(this).data('insert-end') || '';
                                
                                var textarea = $editor[0];
                                var start = textarea.selectionStart;
                                var end = textarea.selectionEnd;
                                var text = textarea.value;
                                var selectedText = text.substring(start, end);
                                
                                var newText = text.substring(0, start) + insertStart + selectedText + insertEnd + text.substring(end);
                                textarea.value = newText;
                                
                                // Set cursor position
                                var newPos = start + insertStart.length + selectedText.length + insertEnd.length;
                                textarea.setSelectionRange(newPos, newPos);
                                textarea.focus();
                                
                                updateHighlight();
                                updatePreview();
                            });
                            
                            // Variable click to insert
                            $('.fs-variable-tag').on('click', function() {
                                var variable = $(this).data('variable');
                                var textarea = $editor[0];
                                var start = textarea.selectionStart;
                                var text = textarea.value;
                                
                                textarea.value = text.substring(0, start) + variable + text.substring(start);
                                textarea.setSelectionRange(start + variable.length, start + variable.length);
                                textarea.focus();
                                
                                updateHighlight();
                                updatePreview();
                            });
                        });
                        </script>
                    </form>
                </div>
            <?php else: ?>
                <!-- Email Header Preview -->
                <div class="fs-email-header-preview">
                    <h4><?php esc_html_e('Email Header', 'freelance-studio'); ?></h4>
                    <p class="description"><?php esc_html_e('All client-facing emails include this header. To change your logo or brand color, visit', 'freelance-studio'); ?> <a href="?page=fs-settings&tab=business#branding"><?php esc_html_e('Business → Branding', 'freelance-studio'); ?></a>.</p>
                    <div class="fs-email-header-demo">
                        <div class="fs-email-header-demo-bar" style="background-color: <?php echo esc_attr($email_primary_color); ?>; padding: 20px; text-align: center; border-radius: 8px 8px 0 0;">
                            <?php if (!empty($email_logo_url)): ?>
                                <img src="<?php echo esc_url($email_logo_url); ?>" alt="<?php echo esc_attr($email_business_name); ?>" style="max-width: 180px; max-height: 60px;">
                            <?php else: ?>
                                <span style="color: #ffffff; font-size: 20px; font-weight: 600;"><?php echo esc_html($email_business_name); ?></span>
                            <?php endif; ?>
                        </div>
                        <div style="padding: 16px 20px; border: 1px solid var(--fs-gray-200); border-top: 0; color: var(--fs-gray-500); font-size: 13px; font-style: italic; border-radius: 0 0 8px 8px; background: #fff;">
                            <?php esc_html_e('Your email body content appears here...', 'freelance-studio'); ?>
                        </div>
                    </div>
                </div>
                
                <!-- Template List -->
                <table class="fs-table widefat">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Template', 'freelance-studio'); ?></th>
                            <th><?php esc_html_e('Description', 'freelance-studio'); ?></th>
                            <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($template_types as $type => $info): 
                            $template_data = FS_Email_Template::get($type);
                        ?>
                            <tr>
                                <td><strong><?php echo esc_html($info['label']); ?></strong></td>
                                <td class="text-muted"><?php echo esc_html($info['description']); ?></td>
                                <td>
                                    <?php if ($template_data['is_custom']): ?>
                                        <span class="fs-badge fs-badge-success"><?php esc_html_e('Customized', 'freelance-studio'); ?></span>
                                    <?php else: ?>
                                        <span class="fs-badge fs-badge-secondary"><?php esc_html_e('Default', 'freelance-studio'); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td class="column-actions">
                                    <a href="?page=fs-settings&tab=emails&edit_email=<?php echo esc_attr($type); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <div class="fs-email-tips">
                    <h4><?php esc_html_e('Email Delivery Tips', 'freelance-studio'); ?></h4>
                    <ul>
                        <li><?php
                            printf(
                                /* translators: %s: link to email delivery settings */
                                esc_html__( 'For reliable delivery, set up a delivery provider in %s.', 'freelance-studio' ),
                                '<a href="?page=fs-settings&tab=email_delivery">' . esc_html__( 'Email Delivery settings', 'freelance-studio' ) . '</a>'
                            );
                        ?></li>
                        <li><?php esc_html_e('Your business logo and brand color are automatically included in the email header.', 'freelance-studio'); ?></li>
                        <li><?php esc_html_e('Test your templates by sending yourself a test email after editing.', 'freelance-studio'); ?></li>
                    </ul>
                </div>
            <?php endif; ?>
        </div><!-- /.fs-email-templates-content -->
        </div>
        
        <?php endif; ?>
        
        <!-- ============================================
    <?php if (in_array($active_tab, array('business', 'documents', 'invoices', 'time'))): ?>
        <?php if ($active_tab !== 'time'): // Time tab has its own save button ?>
        <p class="submit">
            <input type="submit" name="submit" id="submit" class="button button-primary" value="<?php esc_attr_e('Save Settings', 'freelance-studio'); ?>">
        </p>
        <?php endif; ?>
    </form>
    <?php endif; ?>
    
    <!-- ============================================
         EMAIL DELIVERY TAB
         ============================================ -->
    <?php if ($active_tab === 'email_delivery'):
        include JEEB_FS_PLUGIN_DIR . 'includes/views/settings/email-delivery.php';
    endif; ?>
    
    <!-- ============================================
         SERVICES TAB
         ============================================ -->
    <?php if ($active_tab === 'services'): ?>
    
    <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
    <div class="fs-settings-section fs-pro-overlay-wrapper" style="min-height: 200px;">
        <div class="fs-pro-overlay">
            <div class="fs-pro-overlay-content">
                <span class="fs-upgrade-badge">PRO</span>
                <h3><?php esc_html_e( 'Preset Services', 'freelance-studio' ); ?></h3>
                <p><?php esc_html_e( 'Define reusable services that can be quickly added to projects and proposals. Available with Freelance Studio Pro.', 'freelance-studio' ); ?></p>
                <a href="<?php echo function_exists( 'freelance_studio_fs' ) ? esc_url( freelance_studio_fs()->get_upgrade_url() ) : '#'; ?>" class="fs-btn fs-btn-primary fs-btn-small">
                    <?php esc_html_e( 'Upgrade to Pro', 'freelance-studio' ); ?>
                </a>
            </div>
        </div>
        <div aria-hidden="true" style="opacity:0.5; pointer-events:none;">
            <div class="fs-section-header">
                <h2><?php esc_html_e('Preset Services', 'freelance-studio'); ?></h2>
                <span class="button button-primary"><?php esc_html_e('Add Service', 'freelance-studio'); ?></span>
            </div>
            <p class="description"><?php esc_html_e('Define reusable services that can be quickly added to projects and proposals.', 'freelance-studio'); ?></p>
            <table class="widefat fs-table" style="margin-top:15px;">
                <thead><tr><th><?php esc_html_e('Service Name', 'freelance-studio'); ?></th><th><?php esc_html_e('Rate', 'freelance-studio'); ?></th><th><?php esc_html_e('Type', 'freelance-studio'); ?></th></tr></thead>
                <tbody><tr><td colspan="3" style="text-align:center;padding:20px;" class="text-muted"><?php esc_html_e('No preset services yet.', 'freelance-studio'); ?></td></tr></tbody>
            </table>
        </div>
    </div>
    <?php else: ?>
    <div class="fs-settings-section">
        <div class="fs-section-header">
            <h2><?php esc_html_e('Preset Services', 'freelance-studio'); ?></h2>
            <button type="button" class="button button-primary" id="fs-add-preset-service"><?php esc_html_e('Add Service', 'freelance-studio'); ?></button>
        </div>
        <p class="description"><?php esc_html_e('Define reusable services that can be quickly added to projects and proposals.', 'freelance-studio'); ?></p>
        
        <div id="fs-preset-services-list">
            <div class="fs-loading"><?php esc_html_e('Loading services...', 'freelance-studio'); ?></div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Preset Service Modal -->
    <div id="fs-preset-service-modal" class="fs-modal" style="display: none;">
        <div class="fs-modal-content">
            <div class="fs-modal-header">
                <h3 id="fs-preset-service-modal-title"><?php esc_html_e('Add Service', 'freelance-studio'); ?></h3>
                <button type="button" class="fs-modal-close">&times;</button>
            </div>
            <div class="fs-modal-body">
                <form id="fs-preset-service-form">
                    <input type="hidden" id="preset-service-id" name="id" value="">
                    
                    <div class="fs-form-group">
                        <label for="preset-service-name"><?php esc_html_e('Service Name', 'freelance-studio'); ?> *</label>
                        <input type="text" id="preset-service-name" name="name" required>
                    </div>
                    
                    <div class="fs-form-group">
                        <label for="preset-service-description"><?php esc_html_e('Description', 'freelance-studio'); ?></label>
                        <textarea id="preset-service-description" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="fs-form-row">
                        <div class="fs-form-group">
                            <label for="preset-service-pricing-type"><?php esc_html_e('Pricing Type', 'freelance-studio'); ?></label>
                            <select id="preset-service-pricing-type" name="pricing_type">
                                <option value="fixed"><?php esc_html_e('Flat Fee', 'freelance-studio'); ?></option>
                                <option value="hourly"><?php esc_html_e('Hourly', 'freelance-studio'); ?></option>
                            </select>
                        </div>
                        
                        <div class="fs-form-group">
                            <label for="preset-service-rate"><?php esc_html_e('Default Rate', 'freelance-studio'); ?></label>
                            <input type="number" id="preset-service-rate" name="default_rate" step="0.01" min="0" value="0">
                        </div>
                        
                        <div class="fs-form-group">
                            <label for="preset-service-quantity"><?php esc_html_e('Default Quantity', 'freelance-studio'); ?></label>
                            <input type="number" id="preset-service-quantity" name="default_quantity" step="0.01" min="0" value="1">
                        </div>
                    </div>
                </form>
            </div>
            <div class="fs-modal-footer">
                <button type="button" class="fs-btn fs-btn-secondary fs-modal-cancel"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
                <button type="button" class="fs-btn fs-btn-primary" id="fs-save-preset-service"><?php esc_html_e('Save Service', 'freelance-studio'); ?></button>
            </div>
        </div>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        var services = [];
        
        // Load services
        function loadServices() {
            $.ajax({
                url: fs_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'fs_get_preset_services',
                    nonce: fs_ajax.nonce
                },
                success: function(response) {
                    if (response.success) {
                        services = response.data.services;
                        renderServices();
                    }
                }
            });
        }
        
        // Render services list
        function renderServices() {
            var $list = $('#fs-preset-services-list');
            
            if (services.length === 0) {
                $list.html('<div class="fs-empty-state"><p><?php esc_html_e('No preset services yet. Add your first service to speed up project setup.', 'freelance-studio'); ?></p></div>');
                return;
            }
            
            var html = '<table class="fs-table widefat"><thead><tr>';
            html += '<th><?php esc_html_e('Service Name', 'freelance-studio'); ?></th>';
            html += '<th><?php esc_html_e('Description', 'freelance-studio'); ?></th>';
            html += '<th><?php esc_html_e('Pricing', 'freelance-studio'); ?></th>';
            html += '<th><?php esc_html_e('Default Rate', 'freelance-studio'); ?></th>';
            html += '<th></th>';
            html += '</tr></thead><tbody>';
            
            services.forEach(function(service) {
                html += '<tr data-id="' + service.id + '">';
                html += '<td><strong>' + escapeHtml(service.name) + '</strong></td>';
                html += '<td>' + escapeHtml(service.description || '-') + '</td>';
                html += '<td>' + (service.pricing_type === 'hourly' ? '<?php esc_html_e('Hourly', 'freelance-studio'); ?>' : '<?php esc_html_e('Flat Fee', 'freelance-studio'); ?>') + '</td>';
                html += '<td>' + formatCurrency(service.default_rate) + '</td>';
                html += '<td class="column-actions">';
                html += '<button type="button" class="button button-small fs-edit-service" data-id="' + service.id + '"><?php esc_html_e('Edit', 'freelance-studio'); ?></button> ';
                html += '<button type="button" class="button button-small fs-delete-service" data-id="' + service.id + '"><?php esc_html_e('Delete', 'freelance-studio'); ?></button>';
                html += '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
            $list.html(html);
        }
        
        function escapeHtml(text) {
            if (!text) return '';
            return $('<div>').text(text).html();
        }
        
        function formatCurrency(amount) {
            return '$' + parseFloat(amount || 0).toFixed(2);
        }
        
        // Add new service
        $('#fs-add-preset-service').on('click', function() {
            $('#fs-preset-service-modal-title').text('<?php esc_html_e('Add Service', 'freelance-studio'); ?>');
            $('#fs-preset-service-form')[0].reset();
            $('#preset-service-id').val('');
            $('#fs-preset-service-modal').show();
        });
        
        // Edit service
        $(document).on('click', '.fs-edit-service', function() {
            var id = $(this).data('id');
            var service = services.find(function(s) { return s.id == id; });
            
            if (service) {
                $('#fs-preset-service-modal-title').text('<?php esc_html_e('Edit Service', 'freelance-studio'); ?>');
                $('#preset-service-id').val(service.id);
                $('#preset-service-name').val(service.name);
                $('#preset-service-description').val(service.description);
                $('#preset-service-pricing-type').val(service.pricing_type);
                $('#preset-service-rate').val(service.default_rate);
                $('#preset-service-quantity').val(service.default_quantity);
                $('#fs-preset-service-modal').show();
            }
        });
        
        // Delete service
        $(document).on('click', '.fs-delete-service', function() {
            if (!confirm('<?php esc_html_e('Are you sure you want to delete this service?', 'freelance-studio'); ?>')) {
                return;
            }
            
            var id = $(this).data('id');
            
            $.ajax({
                url: fs_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'fs_delete_preset_service',
                    nonce: fs_ajax.nonce,
                    id: id
                },
                success: function(response) {
                    if (response.success) {
                        loadServices();
                    } else {
                        alert(response.data.message);
                    }
                }
            });
        });
        
        // Save service
        $('#fs-save-preset-service').on('click', function() {
            var $form = $('#fs-preset-service-form');
            var data = {
                action: 'fs_save_preset_service',
                nonce: fs_ajax.nonce,
                id: $('#preset-service-id').val(),
                name: $('#preset-service-name').val(),
                description: $('#preset-service-description').val(),
                pricing_type: $('#preset-service-pricing-type').val(),
                default_rate: $('#preset-service-rate').val(),
                default_quantity: $('#preset-service-quantity').val()
            };
            
            if (!data.name) {
                alert('<?php esc_html_e('Service name is required', 'freelance-studio'); ?>');
                return;
            }
            
            $.ajax({
                url: fs_ajax.ajax_url,
                type: 'POST',
                data: data,
                success: function(response) {
                    if (response.success) {
                        $('#fs-preset-service-modal').hide();
                        loadServices();
                    } else {
                        alert(response.data.message);
                    }
                }
            });
        });
        
        // Close modal
        $('.fs-modal-close, .fs-modal-cancel').on('click', function() {
            $('#fs-preset-service-modal').hide();
        });
        
        // Load on init
        loadServices();
    });
    </script>
    
    <?php endif; ?>
    
    <!-- ============================================
         TEMPLATES TAB
         ============================================ -->
    <?php if ($active_tab === 'templates'): ?>
    
    <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
    <div class="fs-settings-section fs-pro-overlay-wrapper" style="min-height: 250px;">
        <div class="fs-pro-overlay">
            <div class="fs-pro-overlay-content">
                <span class="fs-upgrade-badge">PRO</span>
                <h3><?php esc_html_e( 'Project Templates', 'freelance-studio' ); ?></h3>
                <p><?php esc_html_e( 'Create reusable project templates with predefined milestones, tasks, and services. Available with Freelance Studio Pro.', 'freelance-studio' ); ?></p>
                <a href="<?php echo function_exists( 'freelance_studio_fs' ) ? esc_url( freelance_studio_fs()->get_upgrade_url() ) : '#'; ?>" class="fs-btn fs-btn-primary fs-btn-small">
                    <?php esc_html_e( 'Upgrade to Pro', 'freelance-studio' ); ?>
                </a>
            </div>
        </div>
        <div aria-hidden="true" style="opacity:0.5; pointer-events:none;">
            <div class="fs-section-header">
                <h2><?php esc_html_e('Project Templates', 'freelance-studio'); ?></h2>
                <div class="fs-header-actions">
                    <span class="fs-btn fs-btn-secondary"><?php esc_html_e('Template Library', 'freelance-studio'); ?></span>
                    <span class="fs-btn fs-btn-primary"><?php esc_html_e('New Template', 'freelance-studio'); ?></span>
                </div>
            </div>
            <p class="description"><?php esc_html_e('Create reusable templates with predefined milestones and tasks.', 'freelance-studio'); ?></p>
            <div class="fs-empty-state" style="margin-top:15px;">
                <p><?php esc_html_e('No templates yet. Create your first template to speed up project setup.', 'freelance-studio'); ?></p>
            </div>
        </div>
    </div>
    <?php else: ?>
    <div class="fs-settings-section">
        <div class="fs-section-header">
            <h2><?php esc_html_e('Project Templates', 'freelance-studio'); ?></h2>
            <div class="fs-header-actions">
                <button type="button" class="fs-btn fs-btn-secondary" id="fs-open-template-library">
                    <span class="dashicons dashicons-download"></span> <?php esc_html_e('Template Library', 'freelance-studio'); ?>
                </button>
                <a href="?page=fs-settings&tab=templates&action=add" class="fs-btn fs-btn-primary"><?php esc_html_e('New Template', 'freelance-studio'); ?></a>
            </div>
        </div>
        <p class="description"><?php esc_html_e('Create reusable templates with predefined milestones and tasks. Import pre-built templates from the library or create your own.', 'freelance-studio'); ?></p>
        
        <?php if (isset($_GET['action']) && in_array($_GET['action'], array('add', 'edit'))): ?>
            <?php include JEEB_FS_PLUGIN_DIR . 'includes/views/project-templates/form.php'; ?>
        <?php else: ?>
            <?php if (empty($templates)): ?>
                <div class="fs-empty-state">
                    <p><?php esc_html_e('No templates yet. Create your first template to speed up project setup.', 'freelance-studio'); ?></p>
                </div>
            <?php else: ?>
                <table class="fs-table widefat">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Template Name', 'freelance-studio'); ?></th>
                            <th><?php esc_html_e('Description', 'freelance-studio'); ?></th>
                            <th><?php esc_html_e('Milestones', 'freelance-studio'); ?></th>
                            <th><?php esc_html_e('Tasks', 'freelance-studio'); ?></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($templates as $template): 
                            $milestone_count = is_array($template->default_milestones) ? count($template->default_milestones) : 0;
                            $task_count = is_array($template->default_tasks) ? count($template->default_tasks) : 0;
                        ?>
                            <tr>
                                <td><strong><?php echo esc_html($template->name); ?></strong></td>
                                <td><?php echo esc_html($template->description ?: '-'); ?></td>
                                <td><?php echo  intval( $milestone_count ); ?></td>
                                <td><?php echo  intval( $task_count ); ?></td>
                                <td class="column-actions">
                                    <a href="?page=fs-settings&tab=templates&action=edit&id=<?php echo  intval( $template->id ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a> |
                                    <a href="#" class="fs-delete-btn text-danger" data-type="project_template" data-id="<?php echo  intval( $template->id ); ?>"><?php esc_html_e('Delete', 'freelance-studio'); ?></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        <?php endif; ?>
    </div>
    
    <!-- Template Library Modal -->
    <div id="fs-template-library-modal" class="fs-modal" style="display: none;">
        <div class="fs-modal-content fs-modal-large">
            <div class="fs-modal-header">
                <h2><?php esc_html_e('Template Library', 'freelance-studio'); ?></h2>
                <button type="button" class="fs-modal-close">&times;</button>
            </div>
            <div class="fs-modal-body">
                <p class="description" style="margin-bottom: 20px;"><?php esc_html_e('Select templates to import. These pre-built templates include milestones and tasks to help you get started quickly.', 'freelance-studio'); ?></p>
                
                <?php 
                $library_templates = FS_Template_Library::get_templates();
                $imported_status = FS_Template_Library::get_imported_status();
                ?>
                
                <div class="fs-template-library-grid">
                    <?php foreach ($library_templates as $slug => $lib_template): 
                        $is_imported = $imported_status[$slug];
                        $milestone_count = count($lib_template['milestones']);
                        $task_count = count($lib_template['tasks']);
                    ?>
                    <div class="fs-library-template-card <?php echo $is_imported ? 'is-imported' : ''; ?>">
                        <label>
                            <input type="checkbox" name="import_templates[]" value="<?php echo esc_attr($slug); ?>" <?php disabled($is_imported); ?>>
                            <div class="fs-library-template-content">
                                <div class="fs-library-template-header">
                                    <h4><?php echo esc_html($lib_template['name']); ?></h4>
                                    <?php if ($is_imported): ?>
                                        <span class="fs-imported-badge"><?php esc_html_e('Imported', 'freelance-studio'); ?></span>
                                    <?php endif; ?>
                                </div>
                                <p class="fs-library-template-desc"><?php echo esc_html($lib_template['description']); ?></p>
                                <div class="fs-library-template-meta">
                                    <span><strong><?php echo  intval( $milestone_count ); ?></strong> <?php esc_html_e('milestones', 'freelance-studio'); ?></span>
                                    <span><strong><?php echo  intval( $task_count ); ?></strong> <?php esc_html_e('tasks', 'freelance-studio'); ?></span>
                                    <span><strong><?php echo  esc_html( $lib_template['estimated_hours'] ); ?></strong> <?php esc_html_e('hours', 'freelance-studio'); ?></span>
                                    <span>$<?php echo number_format($lib_template['typical_price_min']); ?> - $<?php echo number_format($lib_template['typical_price_max']); ?></span>
                                </div>
                            </div>
                        </label>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="fs-modal-footer">
                <button type="button" class="fs-btn fs-btn-secondary fs-modal-close-btn"><?php esc_html_e('Cancel', 'freelance-studio'); ?></button>
                <button type="button" class="fs-btn fs-btn-primary" id="fs-import-templates-btn"><?php esc_html_e('Import Selected', 'freelance-studio'); ?></button>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php endif; ?>
    
    <!-- ============================================
         CONTRACT SECTIONS TAB
         ============================================ -->
    <?php if ($active_tab === 'contracts'): ?>
    
    <div class="fs-settings-section">
        <h2><?php esc_html_e('Contract Sections', 'freelance-studio'); ?></h2>
        <p class="description mb-15"><?php esc_html_e('Customize the terms and conditions that appear in your contracts.', 'freelance-studio'); ?></p>
        
        <?php if ($editing_section): ?>
            <form method="post" action="">
                <?php wp_nonce_field('fs_save_contract_section', 'fs_section_nonce'); ?>
                <input type="hidden" name="section_id" value="<?php echo  intval( $editing_section->id ); ?>">
                
                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="section_title"><?php esc_html_e('Section Title', 'freelance-studio'); ?></label></th>
                        <td><input type="text" name="section_title" id="section_title" class="large-text" value="<?php echo esc_attr($editing_section->title); ?>" required></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="section_content"><?php esc_html_e('Content', 'freelance-studio'); ?></label></th>
                        <td><textarea name="section_content" id="section_content" rows="10" class="large-text"><?php echo esc_textarea($editing_section->content); ?></textarea></td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                        <td>
                            <label><input type="checkbox" name="is_active" value="1" <?php checked($editing_section->is_active, 1); ?>> <?php esc_html_e('Active (available for use in contracts)', 'freelance-studio'); ?></label>
                        </td>
                    </tr>
                </table>
                
                <p class="submit">
                    <input type="submit" class="button button-primary" value="<?php esc_attr_e('Save Section', 'freelance-studio'); ?>">
                    <a href="?page=fs-settings&tab=contracts" class="button"><?php esc_html_e('Cancel', 'freelance-studio'); ?></a>
                </p>
            </form>
        <?php else: ?>
            <table class="fs-table widefat">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Section', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Category', 'freelance-studio'); ?></th>
                        <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($contract_sections as $section): ?>
                        <tr>
                            <td>
                                <strong><?php echo esc_html($section->title); ?></strong>
                                <?php if ($section->is_required): ?><span class="fs-badge fs-badge-info"><?php esc_html_e('Required', 'freelance-studio'); ?></span><?php endif; ?>
                            </td>
                            <td><?php echo esc_html(ucfirst($section->category)); ?></td>
                            <td>
                                <?php if ($section->is_active): ?>
                                    <span class="fs-badge fs-badge-success"><?php esc_html_e('Active', 'freelance-studio'); ?></span>
                                <?php else: ?>
                                    <span class="fs-badge fs-badge-secondary"><?php esc_html_e('Inactive', 'freelance-studio'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="column-actions">
                                <a href="?page=fs-settings&tab=contracts&edit=<?php echo  intval( $section->id ); ?>"><?php esc_html_e('Edit', 'freelance-studio'); ?></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    
    <?php endif; ?>
    
    <!-- ============================================
         CALENDAR TAB
         ============================================ -->
    <?php if ($active_tab === 'calendar'): ?>
        <?php if ( function_exists( 'fs_studio_is_free_plan' ) && fs_studio_is_free_plan() ): ?>
            <div class="fs-settings-section fs-pro-overlay-wrapper" style="min-height: 200px;">
                <div class="fs-pro-overlay">
                    <div class="fs-pro-overlay-content">
                        <span class="fs-upgrade-badge">PRO</span>
                        <h3><?php esc_html_e( 'Google Calendar Integration', 'freelance-studio' ); ?></h3>
                        <p><?php esc_html_e( 'Two-way sync your project dates, invoice due dates, and bookings with Google Calendar.', 'freelance-studio' ); ?></p>
                        <a href="<?php echo function_exists( 'freelance_studio_fs' ) ? esc_url( freelance_studio_fs()->get_upgrade_url() ) : '#'; ?>" class="fs-btn fs-btn-primary fs-btn-small">
                            <?php esc_html_e( 'Upgrade to Pro', 'freelance-studio' ); ?>
                        </a>
                    </div>
                </div>
                <div aria-hidden="true" style="opacity:0.5; pointer-events:none;">
                    <h2><?php esc_html_e( 'Google Calendar Integration', 'freelance-studio' ); ?></h2>
                    <div class="fs-form-group">
                        <label><?php esc_html_e('Client ID', 'freelance-studio'); ?></label>
                        <input type="text" disabled placeholder="your-client-id.apps.googleusercontent.com" class="regular-text">
                    </div>
                    <div class="fs-form-group">
                        <label><?php esc_html_e('Client Secret', 'freelance-studio'); ?></label>
                        <input type="text" disabled placeholder="••••••••••••••••" class="regular-text">
                    </div>
                    <div class="fs-form-group">
                        <span class="fs-btn fs-btn-secondary" style="pointer-events:none;"><?php esc_html_e('Connect Google Calendar', 'freelance-studio'); ?></span>
                    </div>
                </div>
            </div>
        <?php elseif ( function_exists( 'fs_studio_can_use_premium' ) && fs_studio_can_use_premium() && file_exists( JEEB_FS_PLUGIN_DIR . 'includes/views/settings/calendar.php' ) ): ?>
            <?php include JEEB_FS_PLUGIN_DIR . 'includes/views/settings/calendar.php'; ?>
        <?php endif; ?>
    <?php endif; ?>
    
    <!-- ============================================
         TOOLS TAB
         ============================================ -->
    <?php if ($active_tab === 'import'): ?>
    <?php include JEEB_FS_PLUGIN_DIR . 'includes/views/settings/import.php'; ?>
    <?php endif; /* import */ ?>

    <?php if ($active_tab === 'tools'): ?>
    
    <div class="fs-settings-section">
        <h2><?php esc_html_e('Repair Tools', 'freelance-studio'); ?></h2>
        <p class="description"><?php esc_html_e('Use these tools to fix common issues with your Freelance Studio installation.', 'freelance-studio'); ?></p>
        
        <?php
        // Handle database repair action
        if (isset($_POST['fs_repair_database']) && wp_verify_nonce($_POST['fs_tools_nonce'], 'fs_tools_action')) {
            // Clear the version to force full migration
            delete_option('fs_version');
            update_option('fs_force_schema_check', '1');
            
            // Run migrations
            require_once JEEB_FS_PLUGIN_DIR . 'includes/class-fs-migrator.php';
            FS_Migrator::run();
            
            echo wp_kses_post( '<div class="notice notice-success"><p>' . __('Database schema has been verified and repaired. Missing columns have been added.', 'freelance-studio') . '</p></div>' );        }
        
        // Handle URL repair action (via form POST as backup)
        if (isset($_POST['fs_repair_urls']) && wp_verify_nonce($_POST['fs_tools_nonce'], 'fs_tools_action')) {
            flush_rewrite_rules(true);
            echo wp_kses_post( '<div class="notice notice-success"><p>' . __('URLs have been repaired. Booking pages, client portal, and public links should now work correctly.', 'freelance-studio') . '</p></div>' );        }
        ?>
        
        <form method="post" action="">
            <?php wp_nonce_field('fs_tools_action', 'fs_tools_nonce'); ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('Repair URLs', 'freelance-studio'); ?></th>
                    <td>
                        <p class="description" style="margin-bottom: 10px;">
                            <?php esc_html_e('If booking pages, client portal, proposals, contracts, or invoices show a 404 error, click this button to repair the URL routing. This flushes WordPress rewrite rules.', 'freelance-studio'); ?>
                        </p>
                        <button type="button" class="button fs-repair-urls" id="fs-repair-urls-btn">
                            <span class="dashicons dashicons-admin-links" style="margin-top: 4px;"></span>
                            <?php esc_html_e('Repair URLs', 'freelance-studio'); ?>
                        </button>
                        <noscript>
                            <input type="submit" name="fs_repair_urls" class="button" value="<?php esc_attr_e('Repair URLs', 'freelance-studio'); ?>">
                        </noscript>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Repair Database', 'freelance-studio'); ?></th>
                    <td>
                        <p class="description" style="margin-bottom: 10px;">
                            <?php esc_html_e('If you\'re experiencing errors about missing columns or database issues, click this button to verify and repair the database schema. This will add any missing columns without affecting your existing data.', 'freelance-studio'); ?>
                        </p>
                        <input type="submit" name="fs_repair_database" class="button" value="<?php esc_attr_e('Repair Database Schema', 'freelance-studio'); ?>" onclick="return confirm('<?php esc_html_e('This will verify and repair the database schema. Your data will not be affected. Continue?', 'freelance-studio'); ?>');">
                    </td>
                </tr>
            </table>
        </form>
    </div>
    
    <div class="fs-settings-section">
        <h2><?php esc_html_e('Data Management', 'freelance-studio'); ?></h2>
        <p class="description"><?php esc_html_e('Export your data or control what happens when the plugin is deleted.', 'freelance-studio'); ?></p>
        
        <table class="form-table">
            <tr>
                <th scope="row"><?php esc_html_e('Export All Data', 'freelance-studio'); ?></th>
                <td>
                    <p class="description" style="margin-bottom: 12px;">
                        <?php esc_html_e('Download a complete backup of all your Freelance Studio data including clients, projects, invoices, proposals, contracts, time entries, expenses, tasks, and more.', 'freelance-studio'); ?>
                    </p>
                    <div style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;">
                        <button type="button" id="fs-export-json-btn" class="fs-btn fs-btn-primary">
                            <span class="dashicons dashicons-download" style="margin-right: 6px; line-height: 1.3;"></span>
                            <?php esc_html_e('Export as JSON', 'freelance-studio'); ?>
                        </button>
                        <button type="button" id="fs-export-csv-btn" class="fs-btn fs-btn-secondary">
                            <span class="dashicons dashicons-media-spreadsheet" style="margin-right: 6px; line-height: 1.3;"></span>
                            <?php esc_html_e('Export as CSV', 'freelance-studio'); ?>
                        </button>
                        <span id="fs-export-status" style="display: none;"></span>
                    </div>
                    <p class="description" style="margin-top: 10px; color: var(--fs-gray-500);">
                        <?php esc_html_e('JSON: Single file, best for backup/migration. CSV: ZIP with separate files per table, opens in Excel/Sheets.', 'freelance-studio'); ?>
                    </p>
                </td>
            </tr>
        </table>
    </div>
    
    <div class="fs-settings-section">
        <h2><?php esc_html_e('Data Deletion', 'freelance-studio'); ?></h2>
        <p class="description"><?php esc_html_e('Control what happens to your data when the plugin is deleted.', 'freelance-studio'); ?></p>
        
        <?php 
        // Show save confirmation
        if (isset($_GET['deletion_saved'])) {
            $current_val = get_option('fs_delete_data_on_uninstall', '0');
            ?>
            <div class="notice notice-success" style="margin: 15px 0;">
                <p>
                    <?php if ($current_val === '1'): ?>
                        <strong><?php esc_html_e('Setting saved!', 'freelance-studio'); ?></strong> 
                        <?php esc_html_e('Data WILL be deleted when the plugin is removed.', 'freelance-studio'); ?>
                    <?php else: ?>
                        <strong><?php esc_html_e('Setting saved!', 'freelance-studio'); ?></strong> 
                        <?php esc_html_e('Data will be preserved when the plugin is removed.', 'freelance-studio'); ?>
                    <?php endif; ?>
                </p>
            </div>
            <?php
        }
        ?>
        
        <form method="post" action="">
            <?php wp_nonce_field('fs_deletion_settings', 'fs_deletion_nonce'); ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('Plugin Deletion', 'freelance-studio'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="fs_delete_data_on_uninstall" value="1" <?php checked(get_option('fs_delete_data_on_uninstall', '0'), '1'); ?>>
                            <?php esc_html_e('Delete all Freelance Studio data when the plugin is deleted', 'freelance-studio'); ?>
                        </label>
                        <p class="description" style="margin-top: 8px; color: var(--fs-danger);">
                            <span class="dashicons dashicons-warning" style="font-size: 14px; width: 14px; height: 14px; margin-top: 2px;"></span>
                            <?php esc_html_e('When checked, deleting this plugin from the WordPress Plugins page will permanently remove ALL Freelance Studio data including clients, projects, invoices, contracts, proposals, time entries, expenses, and settings. This cannot be undone. Leave unchecked to preserve your data.', 'freelance-studio'); ?>
                        </p>
                        <p class="description" style="margin-top: 8px;">
                            <strong><?php esc_html_e('Current status:', 'freelance-studio'); ?></strong>
                            <?php 
                            $current_setting = get_option('fs_delete_data_on_uninstall', '0');
                            if ($current_setting === '1') {
                                echo wp_kses_post( '<span style="color: var(--fs-danger )">' . __('Data WILL be deleted on uninstall', 'freelance-studio') . '</span>' );                            } else {
                                echo wp_kses_post( '<span style="color: var(--fs-primary )">' . __('Data will be preserved on uninstall', 'freelance-studio') . '</span>' );                            }
                            ?>
                        </p>
                    </td>
                </tr>
            </table>
            
            <p class="submit">
                <input type="submit" class="fs-btn fs-btn-primary" value="<?php esc_attr_e('Save Setting', 'freelance-studio'); ?>">
            </p>
        </form>
    </div>
    
    <div class="fs-settings-section">
        <h2><?php esc_html_e('Debug Information', 'freelance-studio'); ?></h2>
        
        <table class="form-table">
            <tr>
                <th scope="row"><?php esc_html_e('Plugin Version', 'freelance-studio'); ?></th>
                <td><code><?php echo  esc_html( JEEB_FS_VERSION ); ?></code></td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Database Version', 'freelance-studio'); ?></th>
                <td><code><?php echo  esc_html( get_option('fs_version', 'Not set') ); ?></code></td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('PHP Version', 'freelance-studio'); ?></th>
                <td><code><?php echo PHP_VERSION; ?></code></td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('WordPress Version', 'freelance-studio'); ?></th>
                <td><code><?php echo  esc_html( get_bloginfo('version') ); ?></code></td>
            </tr>
        </table>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        $('#fs-repair-urls-btn').on('click', function() {
            var $btn = $(this);
            $btn.prop('disabled', true).find('.dashicons').removeClass('dashicons-admin-links').addClass('dashicons-update fs-spin');
            
            $.post(ajaxurl, {
                action: 'fs_repair_booking_urls',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_repair_booking_urls') ); ?>'
            }, function(response) {
                if (response.success) {
                    $btn.find('.dashicons').removeClass('dashicons-update fs-spin').addClass('dashicons-yes');
                    $('<div class="notice notice-success"><p><?php echo esc_js(__('URLs repaired successfully! Booking pages, client portal, and public links should now work correctly.', 'freelance-studio')); ?></p></div>').insertAfter('.fs-settings-section h2:first');
                } else {
                    $btn.find('.dashicons').removeClass('dashicons-update fs-spin').addClass('dashicons-no');
                    alert('<?php echo esc_js(__('Failed to repair URLs. Please try saving your Permalinks in Settings > Permalinks.', 'freelance-studio')); ?>');
                }
                setTimeout(function() {
                    $btn.prop('disabled', false).find('.dashicons').removeClass('dashicons-yes dashicons-no').addClass('dashicons-admin-links');
                }, 3000);
            }).fail(function() {
                $btn.prop('disabled', false).find('.dashicons').removeClass('dashicons-update fs-spin').addClass('dashicons-admin-links');
                alert('<?php echo esc_js(__('Request failed. Please try again.', 'freelance-studio')); ?>');
            });
        });
    });
    </script>
    
    <style>
    .dashicons.fs-spin {
        animation: fs-tools-spin 1s linear infinite;
    }
    @keyframes fs-tools-spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
    </style>
    
    <script>
    jQuery(document).ready(function($) {
        var $status = $('#fs-export-status');
        
        // JSON Export button
        $('#fs-export-json-btn').on('click', function() {
            var $btn = $(this);
            var originalHtml = $btn.html();
            
            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update fs-spin" style="margin-right: 6px; line-height: 1.3;"></span> <?php esc_html_e('Exporting...', 'freelance-studio'); ?>');
            $status.hide();
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_export_all_data',
                    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        var blob = new Blob([JSON.stringify(response.data.export, null, 2)], {type: 'application/json'});
                        var url = window.URL.createObjectURL(blob);
                        var a = document.createElement('a');
                        a.href = url;
                        a.download = response.data.filename;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);
                        
                        $status.html('<span style="color: var(--fs-primary);">✓ <?php esc_html_e('JSON export downloaded', 'freelance-studio'); ?></span>').show();
                    } else {
                        $status.html('<span style="color: var(--fs-danger);">✗ ' + (response.data || '<?php esc_html_e('Export failed', 'freelance-studio'); ?>') + '</span>').show();
                    }
                },
                error: function() {
                    $status.html('<span style="color: var(--fs-danger);">✗ <?php esc_html_e('Export failed - server error', 'freelance-studio'); ?></span>').show();
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalHtml);
                }
            });
        });
        
        // CSV Export button
        $('#fs-export-csv-btn').on('click', function() {
            var $btn = $(this);
            var originalHtml = $btn.html();
            
            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update fs-spin" style="margin-right: 6px; line-height: 1.3;"></span> <?php esc_html_e('Exporting...', 'freelance-studio'); ?>');
            $status.hide();
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fs_export_csv_zip',
                    nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        // Decode base64 and create blob
                        var byteCharacters = atob(response.data.zip_data);
                        var byteNumbers = new Array(byteCharacters.length);
                        for (var i = 0; i < byteCharacters.length; i++) {
                            byteNumbers[i] = byteCharacters.charCodeAt(i);
                        }
                        var byteArray = new Uint8Array(byteNumbers);
                        var blob = new Blob([byteArray], {type: 'application/zip'});
                        
                        var url = window.URL.createObjectURL(blob);
                        var a = document.createElement('a');
                        a.href = url;
                        a.download = response.data.filename;
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(a);
                        
                        $status.html('<span style="color: var(--fs-primary);">✓ <?php esc_html_e('CSV export downloaded', 'freelance-studio'); ?> (' + response.data.file_count + ' <?php esc_html_e('files', 'freelance-studio'); ?>)</span>').show();
                    } else {
                        $status.html('<span style="color: var(--fs-danger);">✗ ' + (response.data || '<?php esc_html_e('Export failed', 'freelance-studio'); ?>') + '</span>').show();
                    }
                },
                error: function() {
                    $status.html('<span style="color: var(--fs-danger);">✗ <?php esc_html_e('Export failed - server error', 'freelance-studio'); ?></span>').show();
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalHtml);
                }
            });
        });
    });
    </script>
    
    <?php endif; /* tools */ ?>

    <?php if ($active_tab === 'about'): ?>
    <?php include JEEB_FS_PLUGIN_DIR . 'includes/views/settings/about.php'; ?>
    <?php endif; ?>

        </div><!-- .fs-settings-content -->
    </div><!-- .fs-settings-layout -->
</div>
<?php if (in_array($active_tab, array('business', 'documents', 'invoices', 'time'))): ?>
<!-- Auto-save Status Indicator -->
<div id="fs-save-status" class="fs-save-status">
    <span class="fs-save-status-text"></span>
</div>

<style>
.fs-save-status {
    position: fixed;
    top: 42px;
    right: 20px;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 13px;
    z-index: 99999;
    opacity: 0;
    transform: translateY(-10px);
    transition: opacity 0.2s ease, transform 0.2s ease;
    pointer-events: none;
}
.fs-save-status.is-visible {
    opacity: 1;
    transform: translateY(0);
}
.fs-save-status.is-saving {
    background: #f0f0f1;
    color: #50575e;
}
.fs-save-status.is-saved {
    background: #00a32a;
    color: #fff;
}
.fs-save-status.is-error {
    background: #d63638;
    color: #fff;
}
.fs-save-status .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
    vertical-align: middle;
    margin-right: 4px;
}
@media screen and (max-width: 782px) {
    .fs-save-status {
        top: 56px;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    var saveTimeout = null;
    var $saveStatus = $('#fs-save-status');
    var $saveStatusText = $saveStatus.find('.fs-save-status-text');
    var hideStatusTimeout = null;
    
    // Fields to watch for auto-save (within the main settings form)
    var autoSaveFields = [
        // Business tab
        'business_name', 'business_email', 'business_phone', 'business_website',
        'my_role', 'booking_type', 'booking_url',
        'business_address', 'business_city', 'business_state', 'business_zip', 'business_country',
        'business_logo', 'business_logo_light', 'invoice_primary_color',
        'invoice_primary_color_mode', 'invoice_primary_color_2', 'invoice_gradient_direction',
        'internal_tracking_enabled',
        // Documents tab
        'proposal_expiry_days', 'contract_expiry_days',
        // Invoices tab
        'invoice_prefix', 'invoice_due_days', 'invoice_tax_rate', 'invoice_tax_label',
        'invoice_footer_text', 'invoice_payment_instructions', 'payment_instructions', 'payment_url',
        // Tax tab
        'tax_entity_type', 'tax_filing_status', 'tax_state',
        'tax_estimate_federal_rate', 'tax_estimate_state_rate', 'tax_estimate_self_employment_rate',
        // Time tab
        'default_hourly_rate', 'time_rounding', 'week_start'
    ];
    
    function showSaveStatus(status, message) {
        clearTimeout(hideStatusTimeout);
        
        $saveStatus.removeClass('is-saving is-saved is-error');
        
        if (status === 'saving') {
            $saveStatusText.html('<span class="dashicons dashicons-update-alt"></span> ' + message);
            $saveStatus.addClass('is-saving');
        } else if (status === 'saved') {
            $saveStatusText.html('<span class="dashicons dashicons-yes-alt"></span> ' + message);
            $saveStatus.addClass('is-saved');
            // Hide after 2 seconds
            hideStatusTimeout = setTimeout(function() {
                $saveStatus.removeClass('is-visible');
            }, 2000);
        } else if (status === 'error') {
            $saveStatusText.html('<span class="dashicons dashicons-warning"></span> ' + message);
            $saveStatus.addClass('is-error');
            // Hide after 4 seconds
            hideStatusTimeout = setTimeout(function() {
                $saveStatus.removeClass('is-visible');
            }, 4000);
        }
        
        $saveStatus.addClass('is-visible');
    }
    
    function autoSaveField(fieldName, fieldValue) {
        showSaveStatus('saving', '<?php esc_html_e('Saving...', 'freelance-studio'); ?>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_auto_save_settings',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_auto_save_settings') ); ?>',
                field: fieldName,
                value: fieldValue
            },
            success: function(response) {
                if (response.success) {
                    showSaveStatus('saved', '<?php esc_html_e('Saved', 'freelance-studio'); ?>');
                } else {
                    showSaveStatus('error', response.data.message || '<?php esc_html_e('Error saving', 'freelance-studio'); ?>');
                }
            },
            error: function() {
                showSaveStatus('error', '<?php esc_html_e('Connection error', 'freelance-studio'); ?>');
            }
        });
    }
    
    // Bind to text inputs and textareas (debounced)
    $('#fs-settings-form').on('input', 'input[type="text"], input[type="email"], input[type="url"], input[type="number"], textarea', function() {
        var $field = $(this);
        var fieldName = $field.attr('name');
        
        if (!fieldName || autoSaveFields.indexOf(fieldName) === -1) {
            return;
        }
        
        clearTimeout(saveTimeout);
        
        saveTimeout = setTimeout(function() {
            autoSaveField(fieldName, $field.val());
        }, 1500); // 1.5 second debounce
    });
    
    // Bind to TinyMCE WYSIWYG editors (debounced)
    $(document).on('tinymce-editor-init', function(event, editor) {
        var fieldName = editor.id; // editor id matches textarea name
        if (autoSaveFields.indexOf(fieldName) === -1) return;
        
        editor.on('change keyup', function() {
            clearTimeout(saveTimeout);
            saveTimeout = setTimeout(function() {
                editor.save(); // sync to textarea
                autoSaveField(fieldName, editor.getContent());
            }, 1500);
        });
    });
    
    // Bind to select dropdowns (immediate save)
    $('#fs-settings-form').on('change', 'select', function() {
        var $field = $(this);
        var fieldName = $field.attr('name');
        
        if (!fieldName || autoSaveFields.indexOf(fieldName) === -1) {
            return;
        }
        
        clearTimeout(saveTimeout);
        autoSaveField(fieldName, $field.val());
    });
    
    // Bind to radio buttons (immediate save)
    $('#fs-settings-form').on('change', 'input[type="radio"]', function() {
        var $field = $(this);
        var fieldName = $field.attr('name');
        
        if (!fieldName || autoSaveFields.indexOf(fieldName) === -1) {
            return;
        }
        
        clearTimeout(saveTimeout);
        autoSaveField(fieldName, $field.val());
    });
    
    // Bind to checkboxes (immediate save)
    $('#fs-settings-form').on('change', 'input[type="checkbox"]', function() {
        var $field = $(this);
        var fieldName = $field.attr('name');
        
        if (!fieldName || autoSaveFields.indexOf(fieldName) === -1) {
            return;
        }
        
        clearTimeout(saveTimeout);
        autoSaveField(fieldName, $field.is(':checked') ? '1' : '0');
    });
    
    // Color input change (HTML5 color picker)
    $('#fs-settings-form').on('change', 'input[type="color"]', function() {
        var $field = $(this);
        var fieldName = $field.attr('name');
        
        if (!fieldName || autoSaveFields.indexOf(fieldName) === -1) {
            return;
        }
        
        clearTimeout(saveTimeout);
        autoSaveField(fieldName, $field.val());
    });
    
    // Color picker change (if using WordPress color picker)
    $(document).on('change', '.fs-color-picker', function() {
        var $field = $(this);
        var fieldName = $field.attr('name');
        
        if (!fieldName || autoSaveFields.indexOf(fieldName) === -1) {
            return;
        }
        
        clearTimeout(saveTimeout);
        autoSaveField(fieldName, $field.val());
    });
    
    // Media library selection (for logo)
    $(document).on('fs_media_selected', function(e, fieldName, value) {
        if (autoSaveFields.indexOf(fieldName) !== -1) {
            autoSaveField(fieldName, value);
        }
    });
    
    // --- Generic Logo Uploader Factory ---
    function setupLogoUploader(opts) {
        var uploader;
        
        $(opts.uploadBtn).on('click', function(e) {
            e.preventDefault();
            if (uploader) { uploader.open(); return; }
            
            uploader = wp.media({
                title: opts.title,
                button: { text: opts.buttonText },
                multiple: false,
                library: { type: 'image' }
            });
            
            uploader.on('select', function() {
                var attachment = uploader.state().get('selection').first().toJSON();
                var imgUrl = attachment.sizes && attachment.sizes.medium ? attachment.sizes.medium.url : attachment.url;
                
                $(opts.preview).addClass('has-logo').html('<img src="' + imgUrl + '" alt="' + opts.altText + '">');
                $(opts.input).val(attachment.url);
                $(opts.uploadBtn).text('<?php esc_html_e('Change Logo', 'freelance-studio'); ?>');
                
                if ($(opts.removeBtn).length === 0) {
                    $(opts.uploadBtn).after('<button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-remove-logo-btn" id="' + opts.removeBtnId + '"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>');
                }
                
                $(document).trigger('fs_media_selected', [opts.fieldName, attachment.url]);
            });
            
            uploader.open();
        });
        
        // Remove handler
        $(document).on('click', opts.removeBtn, function(e) {
            e.preventDefault();
            $(opts.input).val('');
            $(opts.preview).removeClass('has-logo').html('<span class="fs-logo-placeholder"><span class="dashicons dashicons-format-image"></span></span>');
            $(opts.uploadBtn).text('<?php esc_html_e('Upload Logo', 'freelance-studio'); ?>');
            $(this).remove();
            $(document).trigger('fs_media_selected', [opts.fieldName, '']);
        });
        
        // URL manual change
        $(opts.input).on('change', function() {
            var url = $(this).val();
            if (url) {
                $(opts.preview).addClass('has-logo').html('<img src="' + url + '" alt="' + opts.altText + '">');
                $(opts.uploadBtn).text('<?php esc_html_e('Change Logo', 'freelance-studio'); ?>');
                if ($(opts.removeBtn).length === 0) {
                    $(opts.uploadBtn).after('<button type="button" class="fs-btn fs-btn-secondary fs-btn-small fs-remove-logo-btn" id="' + opts.removeBtnId + '"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>');
                }
            } else {
                $(opts.preview).removeClass('has-logo').html('<span class="fs-logo-placeholder"><span class="dashicons dashicons-format-image"></span></span>');
                $(opts.uploadBtn).text('<?php esc_html_e('Upload Logo', 'freelance-studio'); ?>');
                $(opts.removeBtn).remove();
            }
            updateHeaderPreview();
        });
    }
    
    // Default (dark) logo uploader
    setupLogoUploader({
        uploadBtn: '#upload-business-logo-btn',
        removeBtn: '#remove-business-logo-btn',
        removeBtnId: 'remove-business-logo-btn',
        preview: '#business-logo-preview',
        input: '#business_logo',
        fieldName: 'business_logo',
        title: '<?php esc_html_e('Select Default Logo (Dark)', 'freelance-studio'); ?>',
        buttonText: '<?php esc_html_e('Use as Logo', 'freelance-studio'); ?>',
        altText: '<?php esc_html_e('Business logo', 'freelance-studio'); ?>'
    });
    
    // Light logo uploader
    setupLogoUploader({
        uploadBtn: '#upload-business-logo-light-btn',
        removeBtn: '#remove-business-logo-light-btn',
        removeBtnId: 'remove-business-logo-light-btn',
        preview: '#business-logo-light-preview',
        input: '#business_logo_light',
        fieldName: 'business_logo_light',
        title: '<?php esc_html_e('Select Light Logo', 'freelance-studio'); ?>',
        buttonText: '<?php esc_html_e('Use as Logo', 'freelance-studio'); ?>',
        altText: '<?php esc_html_e('Business logo (light)', 'freelance-studio'); ?>'
    });
    
    // --- Header Preview Logic ---
    function getColorBackground() {
        var color1 = $('#invoice_primary_color').val() || '#2271b1';
        var color2 = $('#invoice_primary_color_2').val() || color1;
        var mode = $('input[name="invoice_primary_color_mode"]:checked').val() || 'solid';
        var dir = $('#invoice_gradient_direction').val() || '135';
        
        if (mode === 'gradient') {
            return 'linear-gradient(' + dir + 'deg, ' + color1 + ' 0%, ' + color2 + ' 100%)';
        }
        return color1;
    }
    
    function updateHeaderPreview() {
        var darkLogoUrl = $('#business_logo').val();
        var lightLogoUrl = $('#business_logo_light').val();
        var bg = getColorBackground();
        var color1 = $('#invoice_primary_color').val() || '#2271b1';
        
        // Colored header preview — uses gradient or solid
        var coloredLogo = lightLogoUrl || darkLogoUrl;
        $('#fs-header-preview-bar').css('background', bg);
        if (coloredLogo) {
            $('#fs-header-preview-logo').attr('src', coloredLogo);
            $('#fs-header-preview-logo-wrap').show();
        } else {
            $('#fs-header-preview-logo-wrap').hide();
        }
        
        // White header preview — uses dark/default logo
        if (darkLogoUrl) {
            $('#fs-header-preview-logo-dark').attr('src', darkLogoUrl);
            $('#fs-header-preview-logo-wrap-dark').show();
        } else {
            $('#fs-header-preview-logo-wrap-dark').hide();
        }
        
        // Update light logo thumbnail background
        var mode = $('input[name="invoice_primary_color_mode"]:checked').val() || 'solid';
        if (mode === 'gradient') {
            $('#business-logo-light-preview').css('background', bg);
        } else {
            $('#business-logo-light-preview').css('background-color', color1);
            $('#business-logo-light-preview').css('background-image', 'none');
        }
        
        // Update swatch preview
        $('#fs-color-swatch-preview').css('background', bg);
    }
    
    // Color picker changes
    $('#invoice_primary_color, #invoice_primary_color_2').on('input change', function() {
        updateHeaderPreview();
    });
    
    // Gradient mode toggle
    $('input[name="invoice_primary_color_mode"]').on('change', function() {
        var mode = $(this).val();
        $('.fs-color-mode-option').removeClass('active');
        $(this).closest('.fs-color-mode-option').addClass('active');
        
        if (mode === 'gradient') {
            $('.fs-gradient-controls').show();
            $('.fs-color-picker-group:first-child label').text('<?php esc_html_e('Start Color', 'freelance-studio'); ?>');
        } else {
            $('.fs-gradient-controls').hide();
            $('.fs-color-picker-group:first-child label').text('<?php esc_html_e('Color', 'freelance-studio'); ?>');
        }
        
        updateHeaderPreview();
        autoSaveField('invoice_primary_color_mode', mode);
    });
    
    // Gradient direction buttons
    $('.fs-direction-btn').on('click', function() {
        var dir = $(this).data('direction');
        $('#invoice_gradient_direction').val(dir);
        $('.fs-direction-btn').removeClass('active');
        $(this).addClass('active');
        updateHeaderPreview();
        autoSaveField('invoice_gradient_direction', dir);
    });
    
    // Update header preview when any logo is uploaded/removed
    $(document).on('fs_media_selected', function(e, fieldName, value) {
        if (fieldName === 'business_logo' || fieldName === 'business_logo_light') {
            updateHeaderPreview();
        }
    });
});
</script>
<?php endif; ?>
