<?php
// Define admin access constant
define('ADMIN_ACCESS', true);

session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$pdo = getDBConnection();
$message = '';
$message_type = '';

// Handle manual cron job execution
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['run_cron'])) {
    try {
        // Run the cron job manually
        ob_start();
        include '../cron/complete_pending_appointments.php';
        $output = ob_get_clean();
        
        $message = "Cron job executed successfully! Check logs for details.";
        $message_type = 'success';
        
    } catch (Exception $e) {
        $message = "Error running cron job: " . $e->getMessage();
        $message_type = 'danger';
    }
}

// Get recent cron logs
$logFile = '../logs/cron_complete_appointments.log';
$recentLogs = [];
if (file_exists($logFile)) {
    $logs = file($logFile, FILE_IGNORE_NEW_LINES);
    $recentLogs = array_slice(array_reverse($logs), 0, 30); // Last 30 entries
}

// Get pending appointments count
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM appointments WHERE status = 'pending'");
$stmt->execute();
$pendingCount = $stmt->fetch()['count'];

// Get today's completed appointments
$today = date('Y-m-d');
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM appointments WHERE status = 'completed' AND DATE(updated_at) = ?");
$stmt->execute([$today]);
$todayCompleted = $stmt->fetch()['count'];

// Get pending appointments up to current date
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM appointments WHERE status = 'pending' AND appointment_date <= ?");
$stmt->execute([$today]);
$pendingUpToToday = $stmt->fetch()['count'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cron Job Management - Astro Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
        }
        .log-entry {
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 d-md-block bg-dark sidebar">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="index.php">
                                <i class="fas fa-tachometer-alt"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="appointment_management.php">
                                <i class="fas fa-calendar-check"></i> Appointments
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white active" href="cron_management.php">
                                <i class="fas fa-clock"></i> Cron Jobs
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Cron Job Management</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="location.reload()">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                        </div>
                    </div>
                </div>

                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-warning text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $pendingCount; ?></h4>
                                        <p class="mb-0">Total Pending</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-danger text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $pendingUpToToday; ?></h4>
                                        <p class="mb-0">Pending Up to Today</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-calendar-times fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4><?php echo $todayCompleted; ?></h4>
                                        <p class="mb-0">Completed Today</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-check-circle fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4>12:00 AM</h4>
                                        <p class="mb-0">Daily Schedule</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-calendar-day fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Manual Execution -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">Manual Cron Job Execution</h5>
                    </div>
                    <div class="card-body">
                        <p><strong>What this does:</strong> Completes all pending appointments up to today's date (<?php echo date('Y-m-d'); ?>).</p>
                        <p class="text-muted">Currently there are <strong><?php echo $pendingUpToToday; ?></strong> pending appointments that will be completed.</p>
                        <form method="POST">
                            <button type="submit" name="run_cron" class="btn btn-primary" onclick="return confirm('Are you sure you want to complete all pending appointments up to today? This action cannot be undone.')">
                                <i class="fas fa-play"></i> Run Cron Job Now
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Recent Logs -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Recent Cron Job Logs</h5>
                        <small class="text-muted">Last 30 entries</small>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recentLogs)): ?>
                            <p class="text-muted">No logs available yet.</p>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th width="150">Timestamp</th>
                                            <th>Message</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recentLogs as $log): ?>
                                            <tr>
                                                <td class="text-muted small log-entry">
                                                    <?php echo htmlspecialchars(substr($log, 0, 19)); ?>
                                                </td>
                                                <td class="log-entry">
                                                    <?php 
                                                    $message = substr($log, 20);
                                                    if (strpos($message, '✓') !== false) {
                                                        echo '<span class="text-success">' . htmlspecialchars($message) . '</span>';
                                                    } elseif (strpos($message, '✗') !== false) {
                                                        echo '<span class="text-danger">' . htmlspecialchars($message) . '</span>';
                                                    } elseif (strpos($message, '📱') !== false) {
                                                        echo '<span class="text-info">' . htmlspecialchars($message) . '</span>';
                                                    } else {
                                                        echo htmlspecialchars($message);
                                                    }
                                                    ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Setup Instructions -->
                <div class="card mt-4">
                    <div class="card-header">
                        <h5 class="mb-0">Setup Instructions</h5>
                    </div>
                    <div class="card-body">
                        <h6>To set up the cron job on your server:</h6>
                        <ol>
                            <li>SSH into your server</li>
                            <li>Navigate to the cron directory: <code>cd /path/to/astro_admin/cron/</code></li>
                            <li>Make the setup script executable: <code>chmod +x setup_cron.sh</code></li>
                            <li>Run the setup script: <code>./setup_cron.sh</code></li>
                            <li>Verify the cron job was added: <code>crontab -l</code></li>
                        </ol>
                        <div class="alert alert-info">
                            <strong>Note:</strong> The cron job will run daily at 12:00 AM (midnight) and automatically complete all pending appointments that are on or before the current date.
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>