<?php
/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : schedules.php
 * @location     : /modules/settings/schedules.php
 * @type         : Admin Page
 * @scope        : Module Only
 * @allowed      : Automation scheduling, cron configuration, timing settings
 * @reusability  : Single Use
 * @notes        : Automation schedules configuration page for settings module
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Start output buffering
ob_start();

// Load master dispatcher functions
if (!function_exists('igny8_get_defined_cron_jobs')) {
    include_once plugin_dir_path(__FILE__) . '../../core/cron/igny8-cron-master-dispatcher.php';
}


// Handle form submission
if (isset($_POST['igny8_save_cron_settings']) && wp_verify_nonce($_POST['igny8_cron_nonce'], 'igny8_cron_settings')) {
    $cron_jobs = $_POST['cron_jobs'] ?? [];
    $cron_settings = get_option('igny8_cron_settings', []);
    $cron_limits = get_option('igny8_cron_limits', []);
    
    // Update settings for each job
    foreach ($cron_jobs as $job_name => $job_data) {
        $cron_settings[$job_name] = [
            'enabled' => isset($job_data['enabled']),
            'last_run' => $cron_settings[$job_name]['last_run'] ?? 0
        ];
        
        // Update limits
        if (isset($job_data['limit'])) {
            $cron_limits[$job_name] = intval($job_data['limit']);
        }
    }
    
    update_option('igny8_cron_settings', $cron_settings);
    update_option('igny8_cron_limits', $cron_limits);
    
    echo '<div class="notice notice-success"><p>Settings saved successfully!</p></div>';
}

// Get current data
$defined_jobs = igny8_get_defined_cron_jobs();
$cron_settings = get_option('igny8_cron_settings', []);
$cron_limits = get_option('igny8_cron_limits', []);
$last_execution = get_option('igny8_cron_last_execution', []);

// Initialize defaults if needed
if (empty($cron_settings)) {
    $cron_settings = igny8_get_default_cron_settings();
    update_option('igny8_cron_settings', $cron_settings);
}

if (empty($cron_limits)) {
    $cron_limits = igny8_get_default_cron_limits();
    update_option('igny8_cron_limits', $cron_limits);
}

// Get health status for all jobs
$health_status = [];
foreach ($defined_jobs as $job_name => $job_config) {
    $health_status[$job_name] = igny8_get_job_health_status($job_name);
}
?>

<div class="wrap igny8-admin-page">
    
    <!-- Smart Automation Jobs Table -->
    <div class="igny8-card">
        <div class="igny8-standard-header">
            <div class="igny8-card-header-content">
                <div class="igny8-card-title-text">
                    <h3>Smart Automation Jobs</h3>
                    <p class="igny8-card-subtitle">Configure and manage all automation jobs</p>
                </div>
                <div class="igny8-card-icon">
                    <span class="dashicons dashicons-admin-tools igny8-dashboard-icon-lg igny8-dashboard-icon-purple"></span>
                </div>
            </div>
        </div>
        <div class="igny8-card-body">
            <form method="post" action="">
                <?php wp_nonce_field('igny8_cron_settings', 'igny8_cron_nonce'); ?>
                
                <table class="igny8-table" data-cron-key="<?php echo esc_attr(get_option('igny8_secure_cron_key')); ?>">
                    <thead>
                        <tr>
                            <th>Job Name</th>
                            <th>Module</th>
                            <th>Enable</th>
                            <th>Max Items</th>
                            <th>Last Run</th>
                            <th>Execution Time</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($defined_jobs as $job_name => $job_config): 
                            // Skip crons if their respective modules are disabled
                            $analytics_crons = ['igny8_process_ai_queue_cron', 'igny8_auto_recalc_cron', 'igny8_health_check_cron'];
                            $writer_crons = ['igny8_auto_generate_content_cron', 'igny8_auto_generate_images_cron', 'igny8_auto_publish_drafts_cron'];
                            $optimizer_crons = ['igny8_auto_optimizer_cron'];
                            
                            if (in_array($job_name, $analytics_crons) && !igny8_is_module_enabled('analytics')) {
                                continue;
                            }
                            if (in_array($job_name, $writer_crons) && !igny8_is_module_enabled('writer')) {
                                continue;
                            }
                            if (in_array($job_name, $optimizer_crons) && !igny8_is_module_enabled('optimizer')) {
                                continue;
                            }
                            
                            $job_settings = $cron_settings[$job_name] ?? [];
                            $job_status = igny8_get_cron_job_status($job_name);
                            $job_health = $health_status[$job_name];
                        ?>
                        <tr>
                            <td>
                                <strong><?php echo esc_html($job_config['description']); ?></strong>
                            </td>
                            <td>
                                <span class="igny8-module-badge igny8-module-<?php echo esc_attr($job_config['module']); ?>">
                                    <?php echo esc_html(ucfirst($job_config['module'])); ?>
                                </span>
                            </td>
                            <td>
                                <label class="igny8-toggle">
                                    <input type="checkbox" name="cron_jobs[<?php echo esc_attr($job_name); ?>][enabled]" 
                                           <?php checked($job_settings['enabled'] ?? false); ?>>
                                    <span class="igny8-toggle-slider"></span>
                                </label>
                            </td>
                            <td>
                                <input type="number" name="cron_jobs[<?php echo esc_attr($job_name); ?>][limit]" 
                                       value="<?php echo esc_attr($cron_limits[$job_name] ?? 10); ?>" 
                                       min="1" max="100" style="width: 60px;">
                                <?php
                                // Add descriptive text based on job type
                                $item_text = '';
                                switch($job_name) {
                                    case 'igny8_auto_cluster_cron':
                                        $item_text = 'keywords';
                                        break;
                                    case 'igny8_auto_generate_ideas_cron':
                                        $item_text = 'clusters';
                                        break;
                                    case 'igny8_auto_queue_cron':
                                        $item_text = 'ideas';
                                        break;
                                    case 'igny8_auto_generate_content_cron':
                                        $item_text = 'tasks';
                                        break;
                                    case 'igny8_auto_generate_images_cron':
                                        $item_text = 'posts';
                                        break;
                                    case 'igny8_auto_publish_drafts_cron':
                                        $item_text = 'drafts';
                                        break;
                                    case 'igny8_process_ai_queue_cron':
                                        $item_text = 'tasks';
                                        break;
                                    case 'igny8_auto_recalc_cron':
                                        $item_text = 'items';
                                        break;
                                    default:
                                        $item_text = 'items';
                                }
                                echo ' <small style="color: #666; font-size: 12px;">' . $item_text . '</small>';
                                ?>
                            </td>
                            <td>
                                <?php echo esc_html($job_health['last_run']); ?>
                                <?php if (!empty($job_health['result_details'])): ?>
                                    <br><small style="color: <?php echo ($job_health['last_success'] === true) ? '#28a745' : '#dc3545'; ?>;">
                                        <?php echo esc_html($job_health['result_details']); ?>
                                        <?php if ($job_health['last_success'] === true): ?>
                                            ✓
                                        <?php else: ?>
                                            ✗
                                        <?php endif; ?>
                                    </small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php 
                                $execution_time = $job_health['execution_time'] ?? 0;
                                echo $execution_time > 0 ? number_format($execution_time, 2) . 's' : 'N/A';
                                ?>
                                <?php if (!empty($job_health['execution_method'])): ?>
                                    <br><small style="color: #666;">
                                        via <?php echo esc_html($job_health['execution_method']); ?>
                                    </small>
                                <?php endif; ?>
                            </td>
                            <td class="igny8-align-center igny8-actions">
                                <button class="igny8-icon-only igny8-icon-external" data-action="openInNewWindow" data-hook="<?php echo esc_attr($job_name); ?>" title="Open in New Window">
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
                                        <polyline points="15,3 21,3 21,9"></polyline>
                                        <line x1="10" y1="14" x2="21" y2="3"></line>
                                    </svg>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <p class="submit">
                    <input type="submit" name="igny8_save_cron_settings" class="button-primary" value="Save All Settings">
                </p>
            </form>
        </div>
    </div>
    
    <!-- Master Scheduler Status -->
    <div class="igny8-card">
        <div class="igny8-standard-header">
            <div class="igny8-card-header-content">
                <div class="igny8-card-title-text">
                    <h3>Master Scheduler Configuration</h3>
                    <p class="igny8-card-subtitle">Single cron job manages all automation</p>
                </div>
                <div class="igny8-card-icon">
                    <span class="dashicons dashicons-clock igny8-dashboard-icon-lg igny8-dashboard-icon-blue"></span>
                </div>
            </div>
        </div>
        <div class="igny8-card-body">
            <p><strong>Single cPanel Configuration Required:</strong></p>
            <code>*/5 * * * * curl -s "https://<?php echo $_SERVER['HTTP_HOST']; ?>/wp-load.php?import_key=<?php echo get_option('igny8_secure_cron_key'); ?>&import_id=igny8_cron&action=master_scheduler" > /dev/null 2>&1</code>
            <p><em>This single cron job will intelligently manage all automation based on your settings below.</em></p>
        </div>
    </div>
    
    <!-- System Overview -->
    <div class="igny8-card">
        <div class="igny8-standard-header">
            <div class="igny8-card-header-content">
                <div class="igny8-card-title-text">
                    <h3>System Overview</h3>
                    <p class="igny8-card-subtitle">Current automation system status</p>
                </div>
                <div class="igny8-card-icon">
                    <span class="dashicons dashicons-dashboard igny8-dashboard-icon-lg igny8-dashboard-icon-green"></span>
                </div>
            </div>
        </div>
        <div class="igny8-card-body">
            <?php
            $total_jobs = count($defined_jobs);
            $enabled_jobs = count(array_filter($cron_settings, function($settings) { return $settings['enabled'] ?? false; }));
            $scheduled_jobs = count(array_filter($health_status, function($status) { return $status['enabled']; }));
            $failed_jobs = count(array_filter($health_status, function($status) { return $status['last_success'] === false; }));
            ?>
            <div class="igny8-stats-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px; margin: 20px 0;">
                <div class="igny8-metric-item" style="background: var(--panel); border: 1px solid var(--stroke); border-radius: var(--radius); padding: 15px; text-align: center;">
                    <h4 style="margin: 0 0 10px 0; color: var(--blue-dark);">Total Jobs</h4>
                    <p style="margin: 0; font-size: 24px; font-weight: 700; color: var(--text);"><?php echo esc_html($total_jobs); ?></p>
                </div>
                <div class="igny8-metric-item" style="background: var(--panel); border: 1px solid var(--stroke); border-radius: var(--radius); padding: 15px; text-align: center;">
                    <h4 style="margin: 0 0 10px 0; color: var(--green-dark);">Enabled Jobs</h4>
                    <p style="margin: 0; font-size: 24px; font-weight: 700; color: var(--text);"><?php echo esc_html($enabled_jobs); ?></p>
                </div>
                <div class="igny8-metric-item" style="background: var(--panel); border: 1px solid var(--stroke); border-radius: var(--radius); padding: 15px; text-align: center;">
                    <h4 style="margin: 0 0 10px 0; color: var(--amber-dark);">Scheduled Jobs</h4>
                    <p style="margin: 0; font-size: 24px; font-weight: 700; color: var(--text);"><?php echo esc_html($scheduled_jobs); ?></p>
                </div>
                <div class="igny8-metric-item" style="background: var(--panel); border: 1px solid var(--stroke); border-radius: var(--radius); padding: 15px; text-align: center;">
                    <h4 style="margin: 0 0 10px 0; color: var(--red-dark);">Failed Jobs</h4>
                    <p style="margin: 0; font-size: 24px; font-weight: 700; color: var(--text);"><?php echo esc_html($failed_jobs); ?></p>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Capture page content
$igny8_page_content = ob_get_clean();

// Include global layout
include plugin_dir_path(__FILE__) . '../../core/global-layout.php';
?>