<?php
// Filename: admin_promotion.php
require 'config.php';
requireLogin();

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'timetable_coord', 'principal', 'assistant_hem', 'assistant']))) {
    header("Location: dashboard.php"); exit;
}

$msg = ''; $msg_type = '';

// FETCH CLASS STATS
try {
    $stats = $pdo->query("SELECT form_level, COUNT(*) as count FROM classes GROUP BY form_level ORDER BY form_level DESC")->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (Exception $e) {
    $msg = "Error: Database missing 'form_level' column.";
    $msg_type = "danger";
    $stats = [];
}

// HANDLE PROMOTION
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $target_form = intval($_POST['target_form']);
    $action_type = $_POST['action_type']; // 'promote' or 'graduate'
    
    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("SELECT id, class_name FROM classes WHERE form_level = ?");
        $stmt->execute([$target_form]);
        $classes = $stmt->fetchAll();
        $count = 0;

        if ($action_type === 'graduate') {
            $year = date('Y');
            $update = $pdo->prepare("UPDATE classes SET class_name = CONCAT(?, ' (', class_name, ')'), form_level = 99 WHERE id = ?");
            foreach ($classes as $c) {
                $update->execute(["Graduated $year", $c['id']]);
                $count++;
            }
            $msg = "$count classes marked as Graduated/Alumni.";
        } 
        elseif ($action_type === 'promote') {
            $new_form = $target_form + 1;
            $update = $pdo->prepare("UPDATE classes SET class_name = ?, form_level = ? WHERE id = ?");
            
            foreach ($classes as $c) {
                $new_name = preg_replace('/'.$target_form.'/', $new_form, $c['class_name'], 1);
                if ($new_name == $c['class_name']) {
                    $new_name = $new_form . " " . $c['class_name'];
                }
                $update->execute([$new_name, $new_form, $c['id']]);
                $count++;
            }
            $msg = "$count classes promoted from Form $target_form to $new_form.";
        }
        
        $pdo->commit();
        $msg_type = "success";
        $stats = $pdo->query("SELECT form_level, COUNT(*) as count FROM classes GROUP BY form_level ORDER BY form_level DESC")->fetchAll(PDO::FETCH_KEY_PAIR);

    } catch (Exception $e) {
        $pdo->rollBack();
        $msg = "Error: " . $e->getMessage();
        $msg_type = "danger";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Academic Promotion</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; --text-dark: #1e293b; --text-gray: #64748b; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        /* HEADER - Standardized with admin_quotes.php */
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }

        /* FLOATING CARD */
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }

        /* PROMOTION CARDS */
        .promo-item { 
            background: white; border-radius: 18px; padding: 18px; margin-bottom: 15px; 
            border: 1px solid #f1f5f9; transition: transform 0.2s;
        }
        .promo-item:active { transform: scale(0.98); background: #f8fafc; }

        .form-label-pill {
            background: #f3e8ff; color: #8B5CF6; font-weight: 800;
            padding: 4px 12px; border-radius: 50px; font-size: 0.8rem;
        }

        .usage-guide {
            background: #fffbeb; border-left: 4px solid #f59e0b;
            padding: 15px; border-radius: 12px; margin-top: 20px;
        }

        /* BOTTOM NAV */
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 10px 30px 18px 30px; display: flex; justify-content: space-between; border-radius: 30px 30px 0 0; box-shadow: 0 -5px 20px rgba(0,0,0,0.05); z-index: 100; }
        .nav-btn { display: flex; flex-direction: column; align-items: center; color: #94a3b8; text-decoration: none; font-size: 0.7rem; font-weight: 600; }
        .nav-btn.active { color: #8B5CF6; }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Year End Promotion</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Manage Academic Year Advancement</div>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-3"><?= $msg ?></div><?php endif; ?>

        <div class="alert alert-warning border-0 shadow-sm rounded-4 small mb-4 bg-warning bg-opacity-10 text-dark">
            <h6 class="fw-bold"><i class="bi bi-exclamation-triangle-fill me-2"></i>Critical Tool</h6>
            <p class="mb-0 opacity-75">Perform actions from <strong>Highest Form to Lowest</strong> to prevent data overlapping.</p>
        </div>

        <?php if(empty($stats)): ?>
            <div class="text-center py-5 text-muted small opacity-50">
                <i class="bi bi-folder-x display-1"></i><br>No classes with Form Levels found.
            </div>
        <?php else: ?>
            <div class="d-flex flex-column gap-2">
                <?php foreach($stats as $form => $count): 
                    if($form == 99) continue;
                ?>
                <div class="promo-item shadow-sm">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <span class="form-label-pill">FORM <?= $form ?></span>
                            <div class="small text-muted mt-1 fw-bold"><?= $count ?> Classes</div>
                        </div>
                        <i class="bi bi-arrow-up-circle text-primary opacity-25 fs-2"></i>
                    </div>

                    <div class="row g-2">
                        <div class="col-6">
                            <form method="POST" onsubmit="return confirm('Graduate Form <?= $form ?>?');">
                                <input type="hidden" name="target_form" value="<?= $form ?>">
                                <input type="hidden" name="action_type" value="graduate">
                                <button class="btn btn-outline-secondary btn-sm w-100 rounded-pill fw-bold py-2">
                                    <i class="bi bi-mortarboard me-1"></i> Graduate
                                </button>
                            </form>
                        </div>
                        <div class="col-6">
                            <form method="POST" onsubmit="return confirm('Promote Form <?= $form ?> to <?= $form+1 ?>?');">
                                <input type="hidden" name="target_form" value="<?= $form ?>">
                                <input type="hidden" name="action_type" value="promote">
                                <button class="btn btn-primary btn-sm w-100 rounded-pill fw-bold py-2 shadow-sm">
                                    <i class="bi bi-arrow-up me-1"></i> Promote to <?= $form + 1 ?>
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="usage-guide shadow-sm">
            <h6 class="fw-bold text-dark small mb-2"><i class="bi bi-info-circle-fill me-1"></i> Usage Sequence</h6>
            <ol class="small text-muted mb-0 ps-3">
                <li>Graduate the <strong>Highest Form</strong> (e.g., Form 5) first.</li>
                <li>Promote the next level (e.g., Form 4 to 5).</li>
                <li>Continue descending until <strong>Form 1</strong> is promoted.</li>
            </ol>
        </div>
    </div>

    <?php include 'menu.php'; ?>

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