<?php
// Admin-only monitoring page
session_start();

// Verify admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    die('Unauthorized');
}

$config_path = dirname(__DIR__) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
    // Verify is_admin
    if (!isset($_SESSION['user_id'])) {
        die('Session error');
    }
    $stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :uid");
    $stmt->execute([':uid' => $_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user || $user['is_admin'] != 1) {
        die('Admin access required');
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Cron Job Status - Goverifyr</title>
    <style>
        body { font-family: Arial; margin: 20px; background: #f5f5f5; }
        .container { max-width: 900px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { color: #333; border-bottom: 3px solid #4e73df; padding-bottom: 10px; }
        .status-box { background: #f8f9fa; padding: 15px; border-left: 4px solid #28a745; margin: 15px 0; border-radius: 4px; }
        .status-box.error { border-left-color: #e74a3b; background: #fff5f5; }
        .status-box.warning { border-left-color: #f6c23e; background: #fffef5; }
        .logs { background: #1e1e1e; color: #00ff00; padding: 15px; border-radius: 4px; font-family: monospace; font-size: 12px; max-height: 500px; overflow-y: auto; white-space: pre-wrap; word-wrap: break-word; }
        .log-entry { margin-bottom: 5px; }
        .log-success { color: #00ff00; }
        .log-error { color: #ff6b6b; }
        .log-warning { color: #ffd700; }
        button { background: #4e73df; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-size: 14px; }
        button:hover { background: #224abe; }
        .meta { color: #666; font-size: 12px; margin-top: 10px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 Cron Job Status & Logs</h1>

        <?php
        $log_file = __DIR__ . '/cron.log';
        $status = 'No logs found yet';
        $color = 'warning';

        if (file_exists($log_file)) {
            $logs = file_get_contents($log_file);
            $lines = explode("\n", trim($logs));
            $last_line = end($lines);

            if (strpos($last_line, 'CRON SUCCESS') !== false) {
                $status = '✅ Last cron ran successfully';
                $color = '';
            } elseif (strpos($last_line, 'CRON FAILED') !== false) {
                $status = '❌ Last cron failed';
                $color = 'error';
            } elseif (strpos($last_line, 'CRON START') !== false) {
                $status = '⏳ Cron currently running...';
                $color = 'warning';
            }

            // Get last run time
            foreach (array_reverse($lines) as $line) {
                if (preg_match('/\[(.*?)\]/', $line, $matches)) {
                    $last_run = $matches[1];
                    break;
                }
            }
        }
        ?>

        <div class="status-box <?php echo $color; ?>">
            <strong><?php echo $status; ?></strong>
            <?php if (isset($last_run)): ?>
                <div class="meta">Last activity: <?php echo htmlspecialchars($last_run); ?></div>
            <?php endif; ?>
        </div>

        <h3>📋 Recent Logs:</h3>
        <div class="logs">
            <?php
            if (file_exists($log_file)) {
                $logs = file_get_contents($log_file);
                $lines = array_slice(explode("\n", $logs), -30); // Last 30 lines
                
                foreach ($lines as $line) {
                    if (empty(trim($line))) continue;
                    
                    $class = 'log-entry';
                    if (strpos($line, 'ERROR') !== false) {
                        $class .= ' log-error';
                    } elseif (strpos($line, 'WARNING') !== false) {
                        $class .= ' log-warning';
                    } elseif (strpos($line, 'SUCCESS') !== false) {
                        $class .= ' log-success';
                    }
                    
                    echo "<div class='{$class}'>" . htmlspecialchars($line) . "</div>";
                }
            } else {
                echo "<div class='log-entry log-warning'>No logs yet. Cron jobs will start logging after first run.</div>";
            }
            ?>
        </div>

        <h3>ℹ️ Cron Job Schedule:</h3>
        <table style="width:100%; border-collapse: collapse; margin-top: 10px;">
            <tr style="background:#f5f5f5;">
                <th style="border:1px solid #ddd; padding:10px; text-align:left;">Job</th>
                <th style="border:1px solid #ddd; padding:10px; text-align:left;">Command</th>
                <th style="border:1px solid #ddd; padding:10px; text-align:left;">Schedule</th>
            </tr>
            <tr>
                <td style="border:1px solid #ddd; padding:10px;"><strong>Resync SMS Prices</strong></td>
                <td style="border:1px solid #ddd; padding:10px; font-family:monospace; font-size:11px;">resync_prices_cron.php</td>
                <td style="border:1px solid #ddd; padding:10px;">Every hour (minute 0)</td>
            </tr>
            <tr style="background:#f9f9f9;">
                <td style="border:1px solid #ddd; padding:10px;"><strong>Sync SMM Services</strong></td>
                <td style="border:1px solid #ddd; padding:10px; font-family:monospace; font-size:11px;">sync_smm_cron.php</td>
                <td style="border:1px solid #ddd; padding:10px;">Every hour (minute 5)</td>
            </tr>
        </table>

        <div style="margin-top:20px; padding:15px; background:#e7f3ff; border-radius:4px; border-left:4px solid #2196F3;">
            <strong>📌 Note:</strong> This page auto-refreshes every 30 seconds. Check back after the next hour to see if cron jobs executed.
        </div>
    </div>

    <script>
        // Auto-refresh every 30 seconds
        setTimeout(() => { location.reload(); }, 30000);
    </script>
</body>
</html>