<?php
// admin/academic/session_rollover.php
$projectRoot = dirname(dirname(__DIR__));
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../../auth/login.php"); exit();
}

$stmtSet = $pdo->query("SELECT * FROM system_settings LIMIT 1");
$settings = $stmtSet->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_rollover'])) {
    $new_session = $_POST['new_session']; // e.g., 2026/2027
    $graduating_class_id = $_POST['graduating_class_id']; // The ID of SS3 or Grade 12

    try {
        $pdo->beginTransaction();

        // 1. Mark final year students as Graduated (Status 0 or move to alumni table)
        // We'll set their class_id to 0 to indicate they are no longer in a class
        $stmtGrad = $pdo->prepare("UPDATE students SET class_id = 0 WHERE class_id = ?");
        $stmtGrad->execute([$graduating_class_id]);

        // 2. Promote others: This assumes your class IDs are sequential (1, 2, 3...)
        // We move students in reverse order so we don't mix them up
        $classes = $pdo->query("SELECT id FROM classes ORDER BY id DESC")->fetchAll(PDO::FETCH_COLUMN);
        
        $promoteStmt = $pdo->prepare("UPDATE students SET class_id = ? WHERE class_id = ?");
        
        foreach ($classes as $current_id) {
            // If the next class ID exists, move students from current_id to current_id + 1
            // This logic depends on your specific class ID structure
            $next_id = $current_id + 1;
            
            // Only promote if the next class exists and isn't the one we just graduated
            $checkNext = $pdo->prepare("SELECT id FROM classes WHERE id = ?");
            $checkNext->execute([$next_id]);
            
            if ($checkNext->rowCount() > 0) {
                $promoteStmt->execute([$next_id, $current_id]);
            }
        }

        // 3. Update Global Settings to the New Session and FIRST TERM
        $updateSettings = $pdo->prepare("UPDATE system_settings SET active_session = ?, active_term = 'FIRST TERM' WHERE id = 1");
        $updateSettings->execute([$new_session]);

        $pdo->commit();
        $success = "Rollover Successful! Students promoted and system set to $new_session.";
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Critical Error: " . $e->getMessage();
    }
}

// Fetch classes for the dropdown
$all_classes = $pdo->query("SELECT * FROM classes ORDER BY id ASC")->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Session Rollover | <?php echo $school_name; ?></title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; background: #f4f4f4; padding: 40px; }
        .warning-box { background: #fff; border-top: 5px solid #e74c3c; padding: 30px; border-radius: 8px; max-width: 600px; margin: auto; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }
        .danger-zone { background: #fff5f5; border: 1px solid #feb2b2; padding: 20px; border-radius: 5px; margin: 20px 0; }
        .btn-roll { background: #e74c3c; color: white; padding: 12px 25px; border: none; border-radius: 5px; cursor: pointer; font-weight: bold; width: 100%; }
        input, select { width: 100%; padding: 10px; margin: 10px 0 20px 0; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
    </style>
</head>
<body>

<div class="warning-box">
    <a href="../dashboard.php" style="text-decoration:none; color:#3498db;">← Back to Dashboard</a>
    <h2>⚠️ Annual Session Rollover</h2>
    <p>This action is performed <strong>once per year</strong> at the end of the 3rd Term.</p>

    <?php if(isset($success)) echo "<p style='color:green; font-weight:bold;'>$success</p>"; ?>
    <?php if(isset($error)) echo "<p style='color:red; font-weight:bold;'>$error</p>"; ?>

    <div class="danger-zone">
        <p><strong>What this does:</strong></p>
        <ul style="font-size: 14px; color: #555;">
            <li>Moves students to the next class numerically.</li>
            <li>Graduates students in the highest class.</li>
            <li>Changes system session to the one entered below.</li>
            <li>Resets current term to <strong>FIRST TERM</strong>.</li>
        </ul>
    </div>

    <form method="POST" onsubmit="return confirm('CRITICAL ACTION: Have you backed up your database? This will move all students. Continue?');">
        <label>New Academic Session:</label>
        <input type="text" name="new_session" placeholder="e.g., 2026/2027" required>

        <label>Which is the Graduating Class? (e.g. SS3)</label>
        <select name="graduating_class_id" required>
            <option value="">-- Select --</option>
            <?php foreach($all_classes as $c): ?>
                <option value="<?php echo $c['id']; ?>"><?php echo $c['class_name']; ?></option>
            <?php endforeach; ?>
        </select>

        <button type="submit" name="confirm_rollover" class="btn-roll">EXECUTE ROLLOVER & PROMOTE ALL</button>
    </form>
</div>

</body>
</html>