<?php
/**
 * Calendar Settings Tab View
 * Google Calendar Integration Settings
 *
 * @package Freelance_Studio
 */

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

$is_connected = FS_Google_Calendar_Service::is_connected();
$is_enabled = FS_Google_Calendar_Service::is_enabled();
$user_email = get_option('fs_gcal_user_email', '');
$calendars = array();
$calendar_error = '';

if ($is_connected) {
    $calendars = FS_Google_Calendar_Service::get_calendars();
    if (empty($calendars)) {
        $calendar_error = __('Unable to fetch calendars. Please check your connection or try disconnecting and reconnecting.', 'freelance-studio');
    }
}

$selected_calendar = get_option('fs_gcal_calendar_id', '');

// Show any messages
if (isset($_GET['message'])) {
    $message = sanitize_text_field($_GET['message']);
    if ($message === 'connected') {
        echo wp_kses_post( '<div class="notice notice-success is-dismissible"><p>' . __('Successfully connected to Google Calendar!', 'freelance-studio') . '</p></div>' );    } elseif ($message === 'disconnected') {
        echo wp_kses_post( '<div class="notice notice-info is-dismissible"><p>' . __('Disconnected from Google Calendar.', 'freelance-studio') . '</p></div>' );    } elseif ($message === 'saved') {
        echo wp_kses_post( '<div class="notice notice-success is-dismissible"><p>' . __('Settings saved.', 'freelance-studio') . '</p></div>' );    }
}

if (isset($_GET['error'])) {
    $error = sanitize_text_field($_GET['error']);
    if ($error === 'auth_failed') {
        echo wp_kses_post( '<div class="notice notice-error is-dismissible"><p>' . __('Failed to connect to Google Calendar. Please check your credentials and try again.', 'freelance-studio') . '</p></div>' );    }
}
?>

<div class="fs-settings-section">
    <h2><?php esc_html_e('Google Calendar Integration', 'freelance-studio'); ?></h2>
    <p class="description mb-15"><?php esc_html_e('Sync your projects, deadlines, invoices, and more with Google Calendar for a unified view of your schedule.', 'freelance-studio'); ?></p>
    
    <!-- Connection Status -->
    <div class="fs-gcal-status-card <?php echo $is_connected ? 'connected' : 'disconnected'; ?>">
        <div class="fs-gcal-status-icon">
            <?php if ($is_connected): ?>
                <span class="dashicons dashicons-yes-alt"></span>
            <?php else: ?>
                <span class="dashicons dashicons-warning"></span>
            <?php endif; ?>
        </div>
        <div class="fs-gcal-status-info">
            <h3>
                <?php if ($is_connected): ?>
                    <?php esc_html_e('Connected to Google Calendar', 'freelance-studio'); ?>
                <?php else: ?>
                    <?php esc_html_e('Not Connected', 'freelance-studio'); ?>
                <?php endif; ?>
            </h3>
            <?php if ($is_connected && $user_email): ?>
                <p><?php echo esc_html($user_email); ?></p>
            <?php elseif (!$is_connected): ?>
                <p><?php esc_html_e('Connect your Google account to sync calendar events.', 'freelance-studio'); ?></p>
            <?php endif; ?>
        </div>
    </div>
    
    <?php 
    // Show diagnostic info when connected but calendars not loading
    if ($is_connected && isset($_GET['debug'])): 
        $access_token = get_option('fs_gcal_access_token');
        $refresh_token = get_option('fs_gcal_refresh_token');
        $token_expires = get_option('fs_gcal_token_expires');
        $current_token = FS_Google_Calendar_Service::get_access_token();
    ?>
    <div class="notice notice-info" style="margin: 15px 0; padding: 15px;">
        <h4 style="margin-top: 0;">🔧 Connection Diagnostics</h4>
        <table class="widefat" style="max-width: 600px;">
            <tr><td><strong>Access Token:</strong></td><td><?php echo  esc_html( $access_token ? '✅ Present (' . strlen($access_token) . ' chars)' : '❌ Missing' ); ?></td></tr>
            <tr><td><strong>Refresh Token:</strong></td><td><?php echo  esc_html( $refresh_token ? '✅ Present (' . strlen($refresh_token) . ' chars)' : '❌ Missing' ); ?></td></tr>
            <tr><td><strong>Token Expires:</strong></td><td><?php echo  esc_html( $token_expires ? gmdate('Y-m-d H:i:s', $token_expires) . ($token_expires < time() ? ' ⚠️ EXPIRED' : ' ✅ Valid') : '❌ Not set' ); ?></td></tr>
            <tr><td><strong>Current Token:</strong></td><td><?php echo $current_token ? '✅ Got valid token' : '❌ Failed to get token'; ?></td></tr>
            <tr><td><strong>Calendars Found:</strong></td><td><?php echo count($calendars); ?></td></tr>
        </table>
        
        <?php
        // Try to make a test API call
        if ($current_token) {
            $test_response = wp_remote_get('https://www.googleapis.com/calendar/v3/users/me/calendarList?maxResults=1', array(
                'headers' => array(
                    'Authorization' => 'Bearer ' . $current_token,
                ),
                'timeout' => 30,
            ));
            
            echo '<h4>API Test Result:</h4>';
            if (is_wp_error($test_response)) {
                echo '<p style="color: red;">❌ Error: ' . esc_html($test_response->get_error_message()) . '</p>';
            } else {
                $code = wp_remote_retrieve_response_code($test_response);
                $body = wp_remote_retrieve_body($test_response);
                echo wp_kses_post( '<p><strong>HTTP Code:</strong> ' . $code . '</p>' );                echo '<pre style="background: #f5f5f5; padding: 10px; overflow: auto; max-height: 200px;">' . esc_html(substr($body, 0, 1000)) . '</pre>';
            }
        }
        ?>
    </div>
    <?php endif; ?>
    
    <?php if ($is_connected && empty($calendars)): ?>
    <div class="notice notice-warning" style="margin: 15px 0;">
        <p>
            <strong><?php esc_html_e('Unable to fetch calendars.', 'freelance-studio'); ?></strong>
            <?php esc_html_e('This could be a temporary issue or a permission problem.', 'freelance-studio'); ?>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fs-settings&tab=calendar&debug=1')); ?>" class="button button-secondary" style="margin-left: 10px;">
                <?php esc_html_e('Run Diagnostics', 'freelance-studio'); ?>
            </a>
        </p>
    </div>
    <?php endif; ?>
    
    <?php if (!$is_connected): ?>
    
    <!-- Setup Instructions -->
    <div class="fs-gcal-setup-box">
        <h3><?php esc_html_e('Setup Instructions', 'freelance-studio'); ?></h3>
        
        <div class="fs-gcal-setup-steps">
            <div class="fs-gcal-step">
                <div class="step-number">1</div>
                <div class="step-content">
                    <h4><?php esc_html_e('Create Google Cloud Project', 'freelance-studio'); ?></h4>
                    <p><?php esc_html_e('Go to the Google Cloud Console and create a new project (or select an existing one).', 'freelance-studio'); ?></p>
                    <a href="https://console.cloud.google.com/projectcreate" target="_blank" class="button button-secondary">
                        <?php esc_html_e('Open Google Cloud Console', 'freelance-studio'); ?> <span class="dashicons dashicons-external" style="margin-top: 4px;"></span>
                    </a>
                </div>
            </div>
            
            <div class="fs-gcal-step">
                <div class="step-number">2</div>
                <div class="step-content">
                    <h4><?php esc_html_e('Enable Google Calendar API', 'freelance-studio'); ?></h4>
                    <p><?php esc_html_e('In your project, go to "APIs & Services" → "Library" and search for "Google Calendar API". Click to enable it.', 'freelance-studio'); ?></p>
                    <a href="https://console.cloud.google.com/apis/library/calendar-json.googleapis.com" target="_blank" class="button button-secondary">
                        <?php esc_html_e('Enable Calendar API', 'freelance-studio'); ?> <span class="dashicons dashicons-external" style="margin-top: 4px;"></span>
                    </a>
                </div>
            </div>
            
            <div class="fs-gcal-step">
                <div class="step-number">3</div>
                <div class="step-content">
                    <h4><?php esc_html_e('Configure OAuth Consent Screen', 'freelance-studio'); ?></h4>
                    <p><?php esc_html_e('Before creating credentials, you must configure the OAuth consent screen. Go to "APIs & Services" → "OAuth consent screen".', 'freelance-studio'); ?></p>
                    <ul>
                        <li><?php echo wp_kses_post(__('User Type: Select <strong>External</strong> (unless you have a Google Workspace account)', 'freelance-studio')); ?></li>
                        <li><?php echo wp_kses_post(__('App name: <strong>Freelance Studio</strong> (or any name you prefer)', 'freelance-studio')); ?></li>
                        <li><?php esc_html_e('User support email: Your email address', 'freelance-studio'); ?></li>
                        <li><?php esc_html_e('Developer contact: Your email address', 'freelance-studio'); ?></li>
                        <li><?php echo wp_kses_post(__('Scopes: Click "Add or Remove Scopes" and add <strong>Google Calendar API .../auth/calendar</strong>', 'freelance-studio')); ?></li>
                        <li><?php esc_html_e('Test users: Add your Google email address as a test user', 'freelance-studio'); ?></li>
                    </ul>
                    <a href="https://console.cloud.google.com/apis/credentials/consent" target="_blank" class="button button-secondary">
                        <?php esc_html_e('Configure Consent Screen', 'freelance-studio'); ?> <span class="dashicons dashicons-external" style="margin-top: 4px;"></span>
                    </a>
                </div>
            </div>
            
            <div class="fs-gcal-step">
                <div class="step-number">4</div>
                <div class="step-content">
                    <h4><?php esc_html_e('Publish the App', 'freelance-studio'); ?></h4>
                    <p><?php esc_html_e('Your app starts in "Testing" mode. You need to publish it to connect your Google account.', 'freelance-studio'); ?></p>
                    <ul>
                        <li><?php esc_html_e('On the OAuth consent screen page, find the "Publishing status" section', 'freelance-studio'); ?></li>
                        <li><?php echo wp_kses_post(__('Click <strong>"Publish App"</strong> button', 'freelance-studio')); ?></li>
                        <li><?php esc_html_e('Confirm by clicking "Confirm" in the popup', 'freelance-studio'); ?></li>
                    </ul>
                    <p class="description"><?php esc_html_e('Note: Since this is for personal use only, you don\'t need to go through Google\'s verification process. The "unverified app" warning during authorization is normal and safe to proceed through.', 'freelance-studio'); ?></p>
                </div>
            </div>
            
            <div class="fs-gcal-step">
                <div class="step-number">5</div>
                <div class="step-content">
                    <h4><?php esc_html_e('Create OAuth Credentials', 'freelance-studio'); ?></h4>
                    <p><?php esc_html_e('Go to "APIs & Services" → "Credentials" → "Create Credentials" → "OAuth client ID".', 'freelance-studio'); ?></p>
                    <ul>
                        <li><?php echo wp_kses_post(__('Application type: <strong>Web application</strong>', 'freelance-studio')); ?></li>
                        <li><?php echo wp_kses_post(__('Name: <strong>Freelance Studio</strong> (or any name you prefer)', 'freelance-studio')); ?></li>
                        <li><?php esc_html_e('Authorized redirect URI:', 'freelance-studio'); ?><br>
                            <code class="fs-copy-text"><?php echo  esc_url( admin_url('admin.php?page=fs-settings&tab=calendar&gcal_callback=1') ); ?></code>
                            <button type="button" class="button button-small fs-copy-btn" data-copy="<?php echo esc_attr(admin_url('admin.php?page=fs-settings&tab=calendar&gcal_callback=1')); ?>">
                                <span class="dashicons dashicons-clipboard"></span>
                            </button>
                        </li>
                    </ul>
                    <a href="https://console.cloud.google.com/apis/credentials/oauthclient" target="_blank" class="button button-secondary">
                        <?php esc_html_e('Create Credentials', 'freelance-studio'); ?> <span class="dashicons dashicons-external" style="margin-top: 4px;"></span>
                    </a>
                </div>
            </div>
            
            <div class="fs-gcal-step">
                <div class="step-number">6</div>
                <div class="step-content">
                    <h4><?php esc_html_e('Enter Your Credentials', 'freelance-studio'); ?></h4>
                    <p><?php esc_html_e('Copy the Client ID and Client Secret from Google Cloud and paste them below.', 'freelance-studio'); ?></p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Credentials Form -->
    <form method="post" action="" class="fs-gcal-credentials-form">
        <?php wp_nonce_field('fs_gcal_save_credentials', 'fs_gcal_nonce'); ?>
        
        <table class="form-table">
            <tr>
                <th scope="row"><label for="gcal_client_id"><?php esc_html_e('Client ID', 'freelance-studio'); ?></label></th>
                <td>
                    <input type="text" name="gcal_client_id" id="gcal_client_id" class="large-text" 
                           value="<?php echo esc_attr(get_option('fs_gcal_client_id', '')); ?>" 
                           placeholder="xxxxx.apps.googleusercontent.com">
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="gcal_client_secret"><?php esc_html_e('Client Secret', 'freelance-studio'); ?></label></th>
                <td>
                    <input type="password" name="gcal_client_secret" id="gcal_client_secret" class="regular-text" 
                           value="<?php echo esc_attr(get_option('fs_gcal_client_secret', '')); ?>" 
                           placeholder="GOCSPX-xxxxxxxxxx">
                    <button type="button" class="button button-secondary fs-toggle-password">
                        <span class="dashicons dashicons-visibility"></span>
                    </button>
                </td>
            </tr>
        </table>
        
        <p class="submit">
            <input type="submit" name="save_gcal_credentials" class="button button-primary" value="<?php esc_attr_e('Save Credentials', 'freelance-studio'); ?>">
        </p>
    </form>
    
    <?php if (get_option('fs_gcal_client_id') && get_option('fs_gcal_client_secret')): ?>
    <div class="fs-gcal-connect-box">
        <h4><?php esc_html_e('Ready to Connect', 'freelance-studio'); ?></h4>
        <p><?php esc_html_e('Your credentials have been saved. Click below to authorize Freelance Studio to access your Google Calendar.', 'freelance-studio'); ?></p>
        <a href="<?php echo esc_url(FS_Google_Calendar_Service::get_auth_url()); ?>" class="button button-primary button-hero">
            <span class="dashicons dashicons-google" style="margin-top: 8px;"></span>
            <?php esc_html_e('Connect with Google', 'freelance-studio'); ?>
        </a>
    </div>
    <?php endif; ?>
    
    <?php else: ?>
    
    <!-- Connected Settings -->
    <form method="post" action="">
        <?php wp_nonce_field('fs_gcal_save_settings', 'fs_gcal_settings_nonce'); ?>
        
        <table class="form-table">
            <tr>
                <th scope="row"><label for="gcal_enabled"><?php esc_html_e('Enable Sync', 'freelance-studio'); ?></label></th>
                <td>
                    <label class="fs-switch">
                        <input type="checkbox" name="gcal_enabled" id="gcal_enabled" value="1" <?php checked(get_option('fs_gcal_enabled', '0'), '1'); ?>>
                        <span class="fs-slider"></span>
                    </label>
                    <span class="description"><?php esc_html_e('Enable automatic syncing to Google Calendar', 'freelance-studio'); ?></span>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="gcal_calendar_id"><?php esc_html_e('Calendar', 'freelance-studio'); ?></label></th>
                <td>
                    <select name="gcal_calendar_id" id="gcal_calendar_id" class="regular-text">
                        <option value=""><?php esc_html_e('— Create New "Freelance Studio" Calendar —', 'freelance-studio'); ?></option>
                        <?php foreach ($calendars as $calendar): ?>
                            <option value="<?php echo esc_attr($calendar['id']); ?>" <?php selected($selected_calendar, $calendar['id']); ?>>
                                <?php echo esc_html($calendar['summary']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=fs-settings&tab=calendar')); ?>" class="button button-secondary" style="margin-left: 5px;">
                        <span class="dashicons dashicons-update" style="margin-top: 4px;"></span> <?php esc_html_e('Refresh', 'freelance-studio'); ?>
                    </a>
                    <?php if (!empty($calendar_error)): ?>
                        <p class="description" style="color: #c53030;"><?php echo esc_html($calendar_error); ?></p>
                    <?php elseif (empty($calendars)): ?>
                        <p class="description" style="color: #996800;"><?php esc_html_e('No calendars found. Click Refresh or the calendar will be created when you save settings.', 'freelance-studio'); ?></p>
                    <?php else: ?>
                        <?php /* translators: 1. count/number */ ?>
                        <p class="description"><?php echo wp_kses_post( sprintf( __('Found %d calendars. Choose which calendar to sync events to, or create a dedicated Freelance Studio calendar.', 'freelance-studio'), count($calendars))); ?></p>
                    <?php endif; ?>
                </td>
            </tr>
        </table>
        
        <h3 class="fs-gcal-section-title"><?php esc_html_e('What to Sync', 'freelance-studio'); ?></h3>
        <p class="description"><?php esc_html_e('Choose which items should be synced to your calendar. Different clients will appear in different colors.', 'freelance-studio'); ?></p>
        
        <table class="form-table">
            <tr>
                <th scope="row"><?php esc_html_e('Projects', 'freelance-studio'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="gcal_sync_projects" value="1" <?php checked(get_option('fs_gcal_sync_projects', '1'), '1'); ?>>
                        <?php esc_html_e('Project start dates and deadlines', 'freelance-studio'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Milestones', 'freelance-studio'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="gcal_sync_milestones" value="1" <?php checked(get_option('fs_gcal_sync_milestones', '1'), '1'); ?>>
                        <?php esc_html_e('Milestone due dates', 'freelance-studio'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Tasks', 'freelance-studio'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="gcal_sync_tasks" value="1" <?php checked(get_option('fs_gcal_sync_tasks', '1'), '1'); ?>>
                        <?php esc_html_e('Task deadlines (with priority indicators)', 'freelance-studio'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Invoices', 'freelance-studio'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="gcal_sync_invoices" value="1" <?php checked(get_option('fs_gcal_sync_invoices', '1'), '1'); ?>>
                        <?php esc_html_e('Invoice due dates with amounts', 'freelance-studio'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Contracts', 'freelance-studio'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="gcal_sync_contracts" value="1" <?php checked(get_option('fs_gcal_sync_contracts', '1'), '1'); ?>>
                        <?php esc_html_e('Contract expiration dates', 'freelance-studio'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Proposals', 'freelance-studio'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="gcal_sync_proposals" value="1" <?php checked(get_option('fs_gcal_sync_proposals', '1'), '1'); ?>>
                        <?php esc_html_e('Proposal expiration dates', 'freelance-studio'); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Tax Deadlines', 'freelance-studio'); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="gcal_sync_tax" value="1" <?php checked(get_option('fs_gcal_sync_tax', '1'), '1'); ?>>
                        <?php esc_html_e('Quarterly estimated tax payment deadlines', 'freelance-studio'); ?>
                    </label>
                </td>
            </tr>
        </table>
        
        <h3 class="fs-gcal-section-title"><?php esc_html_e('Two-Way Sync', 'freelance-studio'); ?></h3>
        <p class="description"><?php esc_html_e('When enabled, changes made in Google Calendar will automatically update your Freelance Studio data. For example, if you reschedule a booking or task in Google Calendar, the change will sync back here.', 'freelance-studio'); ?></p>
        
        <table class="form-table">
            <tr>
                <th scope="row"><label for="gcal_two_way_sync"><?php esc_html_e('Enable Two-Way Sync', 'freelance-studio'); ?></label></th>
                <td>
                    <label class="fs-switch">
                        <input type="checkbox" name="gcal_two_way_sync" id="gcal_two_way_sync" value="1" <?php checked(get_option('fs_gcal_two_way_sync', '0'), '1'); ?>>
                        <span class="fs-slider"></span>
                    </label>
                    <span class="description"><?php esc_html_e('Sync changes from Google Calendar back to Freelance Studio', 'freelance-studio'); ?></span>
                </td>
            </tr>
            <tr>
                <th scope="row"><label for="gcal_sync_frequency"><?php esc_html_e('Sync Frequency', 'freelance-studio'); ?></label></th>
                <td>
                    <select name="gcal_sync_frequency" id="gcal_sync_frequency">
                        <option value="fifteen_minutes" <?php selected(get_option('fs_gcal_sync_frequency', 'fifteen_minutes'), 'fifteen_minutes'); ?>><?php esc_html_e('Every 15 minutes', 'freelance-studio'); ?></option>
                        <option value="thirty_minutes" <?php selected(get_option('fs_gcal_sync_frequency', 'fifteen_minutes'), 'thirty_minutes'); ?>><?php esc_html_e('Every 30 minutes', 'freelance-studio'); ?></option>
                        <option value="hourly" <?php selected(get_option('fs_gcal_sync_frequency', 'fifteen_minutes'), 'hourly'); ?>><?php esc_html_e('Every hour', 'freelance-studio'); ?></option>
                    </select>
                    <p class="description"><?php esc_html_e('How often to check Google Calendar for changes.', 'freelance-studio'); ?></p>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('What Syncs Back', 'freelance-studio'); ?></th>
                <td>
                    <ul class="fs-feature-list">
                        <li><span class="dashicons dashicons-yes"></span> <?php esc_html_e('Booking date/time changes', 'freelance-studio'); ?></li>
                        <li><span class="dashicons dashicons-yes"></span> <?php esc_html_e('Task due date changes', 'freelance-studio'); ?></li>
                        <li><span class="dashicons dashicons-yes"></span> <?php esc_html_e('Milestone due date changes', 'freelance-studio'); ?></li>
                        <li><span class="dashicons dashicons-yes"></span> <?php esc_html_e('Invoice due date changes', 'freelance-studio'); ?></li>
                        <li><span class="dashicons dashicons-yes"></span> <?php esc_html_e('Project start/end date changes', 'freelance-studio'); ?></li>
                        <li><span class="dashicons dashicons-yes"></span> <?php esc_html_e('Deleted events mark items as completed/cancelled', 'freelance-studio'); ?></li>
                    </ul>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e('Last Sync', 'freelance-studio'); ?></th>
                <td>
                    <?php 
                    $last_sync = FS_Google_Calendar_Service::get_last_inbound_sync();
                    if ($last_sync): 
                    ?>
                        <span class="description">
                            <?php echo esc_html(human_time_diff(strtotime($last_sync), current_time('timestamp'))); ?> <?php esc_html_e('ago', 'freelance-studio'); ?>
                            <span style="color: #999;">(<?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($last_sync))); ?>)</span>
                        </span>
                    <?php else: ?>
                        <span class="description"><?php esc_html_e('Never synced', 'freelance-studio'); ?></span>
                    <?php endif; ?>
                    <br>
                    <button type="button" class="button button-secondary" id="fs-gcal-inbound-sync-btn" style="margin-top: 8px;">
                        <span class="dashicons dashicons-download" style="margin-top: 4px;"></span>
                        <?php esc_html_e('Sync from Google Now', 'freelance-studio'); ?>
                    </button>
                </td>
            </tr>
        </table>
        
        <h3 class="fs-gcal-section-title"><?php esc_html_e('Weekly Digest Email', 'freelance-studio'); ?></h3>
        <p class="description"><?php esc_html_e('Receive a weekly summary of your upcoming deadlines every Monday at 8 AM.', 'freelance-studio'); ?></p>
        
        <table class="form-table">
            <tr>
                <th scope="row"><label for="gcal_weekly_digest_enabled"><?php esc_html_e('Enable Weekly Digest', 'freelance-studio'); ?></label></th>
                <td>
                    <label class="fs-switch">
                        <input type="checkbox" name="gcal_weekly_digest_enabled" id="gcal_weekly_digest_enabled" value="1" <?php checked(get_option('fs_gcal_weekly_digest_enabled', '0'), '1'); ?>>
                        <span class="fs-slider"></span>
                    </label>
                    <span class="description"><?php esc_html_e('Send weekly digest email every Monday', 'freelance-studio'); ?></span>
                </td>
            </tr>
        </table>
        
        <div class="fs-gcal-digest-preview">
            <h4><?php esc_html_e('Preview Weekly Digest', 'freelance-studio'); ?></h4>
            <p class="description"><?php esc_html_e('Here\'s an example of what your weekly digest email will look like with sample data:', 'freelance-studio'); ?></p>
            <button type="button" class="button button-secondary" id="fs-preview-digest-btn">
                <span class="dashicons dashicons-visibility"></span>
                <?php esc_html_e('Show Preview', 'freelance-studio'); ?>
            </button>
            <button type="button" class="button button-secondary" id="fs-send-test-digest-btn">
                <span class="dashicons dashicons-email"></span>
                <?php esc_html_e('Send Test Email', 'freelance-studio'); ?>
            </button>
        </div>
        
        <p class="submit">
            <input type="submit" name="save_gcal_settings" class="button button-primary" value="<?php esc_attr_e('Save Settings', 'freelance-studio'); ?>">
            <button type="button" class="button button-secondary" id="fs-gcal-full-sync-btn">
                <span class="dashicons dashicons-update"></span>
                <?php esc_html_e('Sync All Now', 'freelance-studio'); ?>
            </button>
        </p>
    </form>
    
    <div class="fs-gcal-danger-zone">
        <h3><?php esc_html_e('Disconnect', 'freelance-studio'); ?></h3>
        <p><?php esc_html_e('Disconnect your Google account from Freelance Studio. This will stop all calendar syncing.', 'freelance-studio'); ?></p>
        <form method="post" action="" onsubmit="return confirm('<?php esc_html_e('Are you sure you want to disconnect from Google Calendar?', 'freelance-studio'); ?>');">
            <?php wp_nonce_field('fs_gcal_disconnect', 'fs_gcal_disconnect_nonce'); ?>
            <button type="submit" name="gcal_disconnect" class="button button-link-delete">
                <span class="dashicons dashicons-dismiss"></span>
                <?php esc_html_e('Disconnect Google Account', 'freelance-studio'); ?>
            </button>
        </form>
    </div>
    
    <?php endif; ?>
</div>

<!-- External Calendar URLs Section -->
<div class="fs-settings-section" style="margin-top: 30px;">
    <h2><?php esc_html_e('External Calendar URLs (iCal)', 'freelance-studio'); ?></h2>
    <p class="description mb-15"><?php esc_html_e('Add calendar URLs from other services (Office 365, Outlook, Apple Calendar, etc.) to sync busy times and block availability for meeting booking.', 'freelance-studio'); ?></p>
    
    <?php
    $external_calendars = FS_External_Calendar::get_all();
    ?>
    
    <!-- Add New Calendar Form -->
    <div class="fs-external-cal-add">
        <h3><?php esc_html_e('Add External Calendar', 'freelance-studio'); ?></h3>
        <form method="post" action="" class="fs-external-cal-form">
            <?php wp_nonce_field('fs_add_external_calendar', 'fs_external_cal_nonce'); ?>
            <input type="hidden" name="external_cal_action" value="add">
            
            <div class="fs-form-row">
                <div class="fs-form-group">
                    <label for="ext_cal_name"><?php esc_html_e('Calendar Name', 'freelance-studio'); ?></label>
                    <input type="text" name="ext_cal_name" id="ext_cal_name" placeholder="<?php esc_attr_e('e.g., Work Calendar, Office 365', 'freelance-studio'); ?>" required>
                </div>
                
                <div class="fs-form-group" style="flex: 2;">
                    <label for="ext_cal_url"><?php esc_html_e('Calendar URL (iCal/ICS)', 'freelance-studio'); ?></label>
                    <input type="url" name="ext_cal_url" id="ext_cal_url" placeholder="https://..." required>
                    <p class="description"><?php esc_html_e('The public URL to your calendar in iCal (.ics) format.', 'freelance-studio'); ?></p>
                </div>
                
                <div class="fs-form-group">
                    <label for="ext_cal_color"><?php esc_html_e('Color', 'freelance-studio'); ?></label>
                    <input type="color" name="ext_cal_color" id="ext_cal_color" value="#6b7280">
                </div>
            </div>
            
            <div class="fs-form-row">
                <div class="fs-form-group">
                    <label>
                        <input type="checkbox" name="ext_cal_affects_availability" value="1" checked>
                        <?php esc_html_e('Block availability for meeting booking', 'freelance-studio'); ?>
                    </label>
                    <p class="description"><?php esc_html_e('When checked, events from this calendar will block time slots in your meeting booking system.', 'freelance-studio'); ?></p>
                </div>
            </div>
            
            <p class="submit">
                <button type="submit" class="button button-primary">
                    <span class="dashicons dashicons-plus-alt" style="margin-top: 4px;"></span>
                    <?php esc_html_e('Add Calendar', 'freelance-studio'); ?>
                </button>
            </p>
        </form>
    </div>
    
    <!-- How to get calendar URL instructions -->
    <div class="fs-external-cal-help">
        <h4><?php esc_html_e('How to get your calendar URL:', 'freelance-studio'); ?></h4>
        <div class="fs-help-accordion">
            <details>
                <summary><strong>Microsoft Office 365 / Outlook</strong></summary>
                <ol>
                    <li><?php esc_html_e('Go to outlook.office.com and sign in', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Click the gear icon → View all Outlook settings', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Go to Calendar → Shared calendars', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Under "Publish a calendar", select your calendar', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Choose "Can view all details" and click Publish', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Copy the ICS link', 'freelance-studio'); ?></li>
                </ol>
            </details>
            <details>
                <summary><strong>Apple iCloud Calendar</strong></summary>
                <ol>
                    <li><?php esc_html_e('Go to icloud.com/calendar and sign in', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Click the share icon next to your calendar', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Check "Public Calendar"', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Copy the URL that appears', 'freelance-studio'); ?></li>
                </ol>
            </details>
            <details>
                <summary><strong>Google Calendar (Alternative to OAuth)</strong></summary>
                <ol>
                    <li><?php esc_html_e('Go to calendar.google.com', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Click the three dots next to your calendar → Settings', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Scroll to "Integrate calendar"', 'freelance-studio'); ?></li>
                    <li><?php esc_html_e('Copy the "Secret address in iCal format"', 'freelance-studio'); ?></li>
                </ol>
            </details>
        </div>
    </div>
    
    <!-- List of External Calendars -->
    <?php if (!empty($external_calendars)): ?>
    <div class="fs-external-cal-list">
        <h3><?php esc_html_e('Connected External Calendars', 'freelance-studio'); ?></h3>
        <table class="fs-table widefat">
            <thead>
                <tr>
                    <th style="width: 30px;"></th>
                    <th><?php esc_html_e('Name', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('URL', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Events', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Last Synced', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Actions', 'freelance-studio'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($external_calendars as $cal): 
                    $cached = $cal->cached_events ? json_decode($cal->cached_events, true) : array();
                    $event_count = is_array($cached) ? count($cached) : 0;
                ?>
                <tr>
                    <td>
                        <span class="fs-cal-color-dot" style="background-color: <?php echo esc_attr($cal->color); ?>;"></span>
                    </td>
                    <td>
                        <strong><?php echo esc_html($cal->name); ?></strong>
                        <?php if ($cal->affects_availability): ?>
                            <span class="fs-badge fs-badge-small"><?php esc_html_e('Affects Availability', 'freelance-studio'); ?></span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <code class="fs-url-display"><?php echo esc_html(substr($cal->url, 0, 50) . (strlen($cal->url) > 50 ? '...' : '')); ?></code>
                    </td>
                    <td>
                        <?php if ($cal->sync_error): ?>
                            <span class="fs-status-badge fs-status-error" title="<?php echo esc_attr($cal->sync_error); ?>">
                                <span class="dashicons dashicons-warning"></span> <?php esc_html_e('Error', 'freelance-studio'); ?>
                            </span>
                        <?php elseif ($cal->is_active): ?>
                            <span class="fs-status-badge fs-status-success">
                                <span class="dashicons dashicons-yes"></span> <?php esc_html_e('Active', 'freelance-studio'); ?>
                            </span>
                        <?php else: ?>
                            <span class="fs-status-badge fs-status-inactive"><?php esc_html_e('Inactive', 'freelance-studio'); ?></span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php echo  intval( $event_count ); ?> <?php esc_html_e('events cached', 'freelance-studio'); ?>
                    </td>
                    <td>
                        <?php 
                        if ($cal->last_synced) {
                            echo esc_html(human_time_diff(strtotime($cal->last_synced), current_time('timestamp')) . ' ago');
                        } else {
                            esc_html_e('Never', 'freelance-studio');
                        }
                        ?>
                    </td>
                    <td>
                        <form method="post" style="display: inline;">
                            <?php wp_nonce_field('fs_sync_external_calendar', 'fs_external_cal_nonce'); ?>
                            <input type="hidden" name="external_cal_action" value="sync">
                            <input type="hidden" name="calendar_id" value="<?php echo  intval( $cal->id ); ?>">
                            <button type="submit" class="button button-small" title="<?php esc_attr_e('Sync Now', 'freelance-studio'); ?>">
                                <span class="dashicons dashicons-update"></span>
                            </button>
                        </form>
                        <form method="post" style="display: inline;" onsubmit="return confirm('<?php esc_html_e('Delete this calendar?', 'freelance-studio'); ?>');">
                            <?php wp_nonce_field('fs_delete_external_calendar', 'fs_external_cal_nonce'); ?>
                            <input type="hidden" name="external_cal_action" value="delete">
                            <input type="hidden" name="calendar_id" value="<?php echo  intval( $cal->id ); ?>">
                            <button type="submit" class="button button-small" title="<?php esc_attr_e('Delete', 'freelance-studio'); ?>">
                                <span class="dashicons dashicons-trash"></span>
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- Digest Preview Modal -->
<div id="fs-digest-preview-modal" class="fs-modal">
    <div class="fs-modal-content fs-modal-large">
        <div class="fs-modal-header">
            <h3><?php esc_html_e('Weekly Digest Preview', 'freelance-studio'); ?></h3>
            <button type="button" class="fs-modal-close">&times;</button>
        </div>
        <div class="fs-modal-body" id="fs-digest-preview-content">
            <!-- Preview content loaded via AJAX -->
        </div>
    </div>
</div>
