<?php
// admin/cron-management.php
// ============================================================
// CRON MANAGEMENT DASHBOARD
// View, run, enable/disable, and monitor cron jobs.
// ============================================================

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../config/config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit();
}

// Handle actions: run, toggle, reset
$action = $_GET['action'] ?? '';
$job_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$message = '';
$message_type = 'info';

// ============================================================
// 1. PROCESS ACTIONS
// ============================================================
if ($action === 'run' && $job_id > 0) {
    // Fetch job details
    $stmt = $pdo->prepare("SELECT * FROM cron_jobs WHERE id = ?");
    $stmt->execute([$job_id]);
    $job = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($job) {
        // Mark as running
        $pdo->prepare("UPDATE cron_jobs SET last_status = 'pending', last_run = NOW() WHERE id = ?")->execute([$job_id]);
        
        // Execute the script
        $file_path = __DIR__ . '/../' . $job['file_path'];
        if (file_exists($file_path)) {
            // Capture output
            ob_start();
            include $file_path;
            $output = ob_get_clean();
            $status = 'success';
            $message = "Cron job executed successfully.";
        } else {
            $status = 'failed';
            $output = "Error: File not found: " . $file_path;
            $message = "File not found.";
        }
        
        // Update with result
        $pdo->prepare("UPDATE cron_jobs SET last_status = ?, last_message = ? WHERE id = ?")
            ->execute([$status, $output, $job_id]);
        
        $message_type = ($status === 'success') ? 'success' : 'danger';
        $message = "Cron job '{$job['name']}' executed. Status: " . strtoupper($status);
    }
}

if ($action === 'toggle' && $job_id > 0) {
    $stmt = $pdo->prepare("SELECT is_enabled FROM cron_jobs WHERE id = ?");
    $stmt->execute([$job_id]);
    $current = $stmt->fetchColumn();
    $new = $current ? 0 : 1;
    $pdo->prepare("UPDATE cron_jobs SET is_enabled = ? WHERE id = ?")->execute([$new, $job_id]);
    $message = "Cron job " . ($new ? 'enabled' : 'disabled') . " successfully.";
    $message_type = 'success';
}

if ($action === 'reset_logs' && $job_id > 0) {
    $pdo->prepare("UPDATE cron_jobs SET last_status = 'pending', last_message = NULL WHERE id = ?")->execute([$job_id]);
    $message = "Logs cleared.";
    $message_type = 'success';
}

// ============================================================
// 2. FETCH ALL CRON JOBS
// ============================================================
$jobs = $pdo->query("SELECT * FROM cron_jobs ORDER BY is_enabled DESC, id ASC")->fetchAll(PDO::FETCH_ASSOC);

// If no jobs exist, show a notice
if (empty($jobs)) {
    // Insert default jobs if table is empty
    $pdo->query("
        INSERT IGNORE INTO cron_jobs (job_key, name, description, file_path, schedule, is_enabled) VALUES
        ('bet_of_the_day', 'Bet of the Day Alert', 'Send daily Bet of the Day email to all active users.', 'admin/cron-bet-of-the-day.php', 'daily', 1),
        ('expiry_reminder', 'VIP Expiry Reminder', 'Send reminder emails to users whose VIP expires in 7 days.', 'admin/cron-expiry-reminder.php', 'daily', 1),
        ('prediction_sync', 'API Predictions Sync', 'Sync match data and predictions from the external API.', 'admin/cron-sync.php', 'hourly', 1)
    ");
    // Re-fetch
    $jobs = $pdo->query("SELECT * FROM cron_jobs ORDER BY is_enabled DESC, id ASC")->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Cron Management</title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        .status-badge {
            display: inline-block;
            padding: 0.2rem 0.75rem;
            border-radius: 9999px;
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        .status-success { background: #dcfce7; color: #166534; border: 1px solid #86efac; }
        .status-failed { background: #fee2e2; color: #991b1b; border: 1px solid #fca5a5; }
        .status-pending { background: #fef3c7; color: #92400e; border: 1px solid #fcd34d; }
        .dark .status-success { background: #064e3b; color: #34d399; border-color: #065f46; }
        .dark .status-failed { background: #7f1d1d; color: #fca5a5; border-color: #991b1b; }
        .dark .status-pending { background: #78350f; color: #fbbf24; border-color: #92400e; }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') document.documentElement.classList.add('dark');
        else document.documentElement.classList.remove('dark');
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        
        <!-- Header -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
                <div class="inline-flex items-center space-x-2 bg-purple-500/10 border border-purple-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-purple-400 mb-2">
                    <span class="w-1.5 h-1.5 rounded-full bg-purple-400 animate-pulse"></span>
                    <span>Scheduled Tasks</span>
                </div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Cron Job Manager</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Monitor and manage automated system tasks.</p>
            </div>
            <div class="flex items-center gap-2">
                <span class="text-[10px] text-slate-500 dark:text-gray-500">Last sync: <?php echo date('H:i:s'); ?></span>
                <a href="?refresh=1" class="bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 text-slate-700 dark:text-gray-300 px-3 py-1.5 rounded-lg text-xs font-bold transition border border-slate-200 dark:border-slate-700">⟳ Refresh</a>
            </div>
        </div>

        <!-- Messages -->
        <?php if (!empty($message)): ?>
            <div class="bg-<?php echo $message_type === 'success' ? 'emerald' : ($message_type === 'danger' ? 'rose' : 'blue'); ?>-50 border border-<?php echo $message_type === 'success' ? 'emerald' : ($message_type === 'danger' ? 'rose' : 'blue'); ?>-200 text-<?php echo $message_type === 'success' ? 'emerald' : ($message_type === 'danger' ? 'rose' : 'blue'); ?>-700 dark:bg-<?php echo $message_type === 'success' ? 'emerald' : ($message_type === 'danger' ? 'rose' : 'blue'); ?>-500/10 dark:border-<?php echo $message_type === 'success' ? 'emerald' : ($message_type === 'danger' ? 'rose' : 'blue'); ?>-500/30 dark:text-<?php echo $message_type === 'success' ? 'emerald' : ($message_type === 'danger' ? 'rose' : 'blue'); ?>-400 p-3 rounded-xl text-sm font-medium flex items-center gap-2">
                <span>✅</span> <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Total Jobs</span>
                <span class="text-2xl font-extrabold text-slate-900 dark:text-white mt-1 block"><?php echo count($jobs); ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Enabled</span>
                <span class="text-2xl font-extrabold text-emerald-600 dark:text-emerald-500 mt-1 block">
                    <?php echo array_reduce($jobs, function($c, $j) { return $c + ($j['is_enabled'] ? 1 : 0); }, 0); ?>
                </span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Last Run</span>
                <span class="text-sm font-bold text-slate-900 dark:text-white mt-1 block truncate">
                    <?php 
                        $latest = array_reduce($jobs, function($a, $j) { 
                            return ($j['last_run'] && (!$a || $j['last_run'] > $a)) ? $j['last_run'] : $a; 
                        }, null);
                        echo $latest ? date('M d, H:i', strtotime($latest)) : 'Never';
                    ?>
                </span>
            </div>
        </div>

        <!-- Jobs Table -->
        <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl overflow-hidden shadow-sm transition-colors duration-300">
            <div class="overflow-x-auto -mx-4 sm:-mx-6 px-4 sm:px-6">
                <table class="w-full text-left text-sm border-collapse min-w-[700px]">
                    <thead>
                        <tr class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800 text-[10px] font-black tracking-wider uppercase">
                            <th class="py-3 px-2">Job</th>
                            <th class="py-3 px-2">Schedule</th>
                            <th class="py-3 px-2 text-center">Status</th>
                            <th class="py-3 px-2 text-center">Last Run</th>
                            <th class="py-3 px-2 text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300 text-xs">
                        <?php foreach ($jobs as $job): 
                            $status_class = $job['last_status'] === 'success' ? 'status-success' : ($job['last_status'] === 'failed' ? 'status-failed' : 'status-pending');
                            $status_label = $job['last_status'] ? strtoupper($job['last_status']) : 'PENDING';
                            $is_enabled = $job['is_enabled'];
                        ?>
                        <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition">
                            <td class="py-3 px-2">
                                <div class="font-bold text-slate-900 dark:text-white"><?= htmlspecialchars($job['name']); ?></div>
                                <div class="text-[10px] text-slate-500 dark:text-gray-400 truncate max-w-[180px]"><?= htmlspecialchars($job['description'] ?? ''); ?></div>
                                <div class="text-[9px] font-mono text-slate-400 dark:text-gray-500 mt-0.5"><?= htmlspecialchars($job['job_key']); ?></div>
                            </td>
                            <td class="py-3 px-2">
                                <span class="bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider"><?= $job['schedule'] ?? 'manual'; ?></span>
                            </td>
                            <td class="py-3 px-2 text-center">
                                <span class="status-badge <?= $status_class; ?>"><?= $status_label; ?></span>
                                <?php if ($job['last_message']): ?>
                                    <div class="text-[8px] text-slate-400 dark:text-gray-500 mt-1 truncate max-w-[120px] mx-auto" title="<?= htmlspecialchars($job['last_message']); ?>">
                                        <?= substr(htmlspecialchars($job['last_message']), 0, 40); ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-2 text-center text-slate-400 dark:text-gray-500">
                                <?= $job['last_run'] ? date('M d, H:i', strtotime($job['last_run'])) : '—'; ?>
                            </td>
                            <td class="py-3 px-2 text-center">
                                <div class="flex items-center justify-center gap-1.5 flex-wrap">
                                    <a href="?action=run&id=<?= $job['id']; ?>" onclick="return confirm('Run this cron job now?')" class="bg-emerald-50 hover:bg-emerald-100 dark:bg-emerald-500/10 dark:hover:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 px-2.5 py-1.5 rounded-lg text-[9px] font-bold uppercase tracking-wider transition border border-emerald-200 dark:border-emerald-500/30" title="Run Now">▶ Run</a>
                                    <a href="?action=toggle&id=<?= $job['id']; ?>" onclick="return confirm('<?= $is_enabled ? 'Disable' : 'Enable'; ?> this job?')" class="bg-<?= $is_enabled ? 'amber' : 'blue'; ?>-50 hover:bg-<?= $is_enabled ? 'amber' : 'blue'; ?>-100 dark:bg-<?= $is_enabled ? 'amber' : 'blue'; ?>-500/10 dark:hover:bg-<?= $is_enabled ? 'amber' : 'blue'; ?>-500/20 text-<?= $is_enabled ? 'amber' : 'blue'; ?>-600 dark:text-<?= $is_enabled ? 'amber' : 'blue'; ?>-400 px-2.5 py-1.5 rounded-lg text-[9px] font-bold uppercase tracking-wider transition border border-<?= $is_enabled ? 'amber' : 'blue'; ?>-200 dark:border-<?= $is_enabled ? 'amber' : 'blue'; ?>-500/30">
                                        <?= $is_enabled ? 'Disable' : 'Enable'; ?>
                                    </a>
                                    <a href="?action=reset_logs&id=<?= $job['id']; ?>" onclick="return confirm('Clear logs for this job?')" class="bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 text-slate-600 dark:text-gray-400 px-2.5 py-1.5 rounded-lg text-[9px] font-bold uppercase tracking-wider transition border border-slate-200 dark:border-slate-700" title="Clear Logs">🗑️</a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Instructions -->
        <div class="bg-slate-900/40 backdrop-blur border border-slate-800/60 rounded-2xl p-5 text-xs text-slate-400 leading-relaxed">
            <h4 class="font-bold text-white mb-2">📌 How Cron Works</h4>
            <p>These cron jobs are scheduled tasks that run automatically at specified times. You can also trigger them manually using the <strong>▶ Run</strong> button.</p>
            <p class="mt-2">To set up real cron jobs on your server, add the following entries to your crontab:</p>
            <pre class="mt-2 bg-slate-950 p-3 rounded-lg border border-slate-800 text-[10px] font-mono text-emerald-400 overflow-x-auto">
# Daily at 8:00 AM – Bet of the Day
0 8 * * * php <?= __DIR__; ?>/../cron-bet-of-the-day.php

# Daily at 9:00 AM – Expiry Reminder
0 9 * * * php <?= __DIR__; ?>/../cron-expiry-reminder.php

# Hourly – API Sync (optional)
0 * * * * php <?= __DIR__; ?>/../cron-sync.php
            </pre>
        </div>

    </main>
</body>
</html>