<?php
session_start();

// 🔌 Connect to SQLite database
try {
    $db = new PDO('sqlite:database.db');
    // ⚙️ Set error mode to exceptions for better error handling
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die(" Database connection failed: " . $e->getMessage());
}

// ============================================================
// GET ACTIVATION SLOT COUNT
// ============================================================
try {
    $slot_stmt = $db->query("SELECT COALESCE(SUM(number), 0) as total FROM activation_slot");
    $slot_count = $slot_stmt->fetchColumn();
} catch (PDOException $e) {
    $slot_count = 0;
}

// ============================================================
// GET ALL LEVEL TABLES (EXCLUDING STUDENTS/EXAM PAGE)
// ============================================================
$levels = [];
try {
    $stmt = $db->query("SELECT * FROM levels_tracking WHERE table_name != 'students' ORDER BY display_name ASC");
    $levels = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Table might not exist yet
}

// ============================================================
// GET LAST SELECTED TABLE FROM SESSION
// ============================================================
$last_selected_table = $_SESSION['last_student_table'] ?? '';

// ============================================================
// HANDLE ADD SLOT
// ============================================================
if (isset($_POST['add_slot_code'])) {
    $code = trim($_POST['add_slot_code']);
    if (!empty($code)) {
        // VERIFY externally using cURL
        $verifyUrl = 'https://cbt.net.ng/verify_pin.php';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $verifyUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['pin' => $code]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $verify = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($verify, true);

        if ($result && $result['status'] === 'success') {
            // Extract number at the beginning of the code
            if (preg_match('/^(\d+)/', $code, $matches)) {
                $number = (int)$matches[1];

                if ($number > 0) {
                    // Get the current slots if exists
                    $current_slots = $db->query('SELECT number FROM activation_slot LIMIT 1')->fetchColumn();

                    if ($current_slots === false) {
                        // No slots exist, insert new record
                        $stmt = $db->prepare('INSERT INTO activation_slot (number) VALUES (:number)');
                        $stmt->bindParam(':number', $number, PDO::PARAM_INT);
                        $stmt->execute();
                        $_SESSION['message'] = ["text" => "✅ $number activation slots added successfully!", "type" => "success"];
                    } else {
                        // Slots exist, update by adding
                        $new_number = $current_slots + $number;
                        $stmt = $db->prepare('UPDATE activation_slot SET number = :number');
                        $stmt->bindParam(':number', $new_number, PDO::PARAM_INT);
                        $stmt->execute();
                        $_SESSION['message'] = ["text" => "✅ $number activation slots added successfully!", "type" => "success"];
                    }

                    // Update slot count for display
                    $slot_stmt = $db->query("SELECT COALESCE(SUM(number), 0) as total FROM activation_slot");
                    $slot_count = $slot_stmt->fetchColumn();

                    header("Location: " . $_SERVER['PHP_SELF']);
                    exit;
                } else {
                    $_SESSION['message'] = ["text" => "❌ No valid number found at the beginning of the code.", "type" => "error"];
                }
            } else {
                $_SESSION['message'] = ["text" => "❌ Code does not begin with a number.", "type" => "error"];
            }
        } else {
            $_SESSION['message'] = ["text" => "❌ Invalid pin or verification failed.", "type" => "error"];
        }
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $_SESSION['message'] = ["text" => "⚠️ Please enter a valid code.", "type" => "error"];
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

// ============================================================
// FUNCTION TO INSERT STUDENT INTO SPECIFIC TABLE
// ============================================================
function insertStudent($db, $table_name, $user_id, $name, $sex, $picture)
{
    try {
        // 🔍 Check if the table exists
        $check = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='$table_name'")->fetch();
        if (!$check) {
            $_SESSION['message'] = ["text" => "❌ Error: Selected level table does not exist.", "type" => "error"];
            return;
        }

        // 🔍 Check if the user_id AND name combination already exists
        $stmt = $db->prepare("SELECT COUNT(*) FROM '$table_name' WHERE user_id = :user_id AND name = :name");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
        $stmt->bindParam(':name', $name, PDO::PARAM_STR);
        $stmt->execute();
        $count = $stmt->fetchColumn();

        if ($count > 0) {
            $_SESSION['message'] = ["text" => "Error: A student with this ID and Name already exists in this level.", "type" => "error"];
            return;
        }

        // 📝 Prepare the SQL insert statement for the specific table
        $stmt = $db->prepare("INSERT INTO '$table_name' (user_id, name, sex, picture) VALUES (:user_id, :name, :sex, :picture)");

        // 🔗 Bind parameters to the SQL query
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
        $stmt->bindParam(':name', $name, PDO::PARAM_STR);
        $stmt->bindParam(':sex', $sex, PDO::PARAM_STR);
        $stmt->bindParam(':picture', $picture, PDO::PARAM_LOB);

        // 🚀 Execute the query
        if ($stmt->execute()) {
            // Save the table name to session for next time
            $_SESSION['last_student_table'] = $table_name;
            $_SESSION['message'] = ["text" => "Student data uploaded successfully to level!", "type" => "success"];
        } else {
            $_SESSION['message'] = ["text" => "❌ Failed to upload student data.", "type" => "error"];
        }
    } catch (PDOException $e) {
        $_SESSION['message'] = ["text" => "⚠️ Error: " . $e->getMessage(), "type" => "error"];
    }
}

// 🖼️ Function to resize and compress image to ~250KB
function resizeAndCompressImage($imagePath, $targetSizeKB = 250)
{
    // Get the image type
    $imageInfo = getimagesize($imagePath);
    $mimeType = $imageInfo['mime'];

    // Create image from file based on mime type
    switch ($mimeType) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($imagePath);
            break;
        case 'image/png':
            $image = imagecreatefrompng($imagePath);
            break;
        case 'image/gif':
            $image = imagecreatefromgif($imagePath);
            break;
        case 'image/webp':
            $image = imagecreatefromwebp($imagePath);
            break;
        default:
            throw new Exception("⚠️ Unsupported image type: $mimeType");
    }

    // Get original dimensions
    $originalWidth = imagesx($image);
    $originalHeight = imagesy($image);

    // Start with a reasonable size (800x800 max)
    $maxWidth = 800;
    $maxHeight = 800;

    // Calculate new dimensions maintaining aspect ratio
    $ratio = min($maxWidth / $originalWidth, $maxHeight / $originalHeight, 1);
    $newWidth = (int)($originalWidth * $ratio);
    $newHeight = (int)($originalHeight * $ratio);

    // If original is smaller than max, keep original size
    if ($ratio >= 1) {
        $newWidth = $originalWidth;
        $newHeight = $originalHeight;
    }

    // Create new image
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

    // Preserve transparency for PNG and GIF
    if ($mimeType == 'image/png' || $mimeType == 'image/gif') {
        imagecolortransparent($resizedImage, imagecolorallocatealpha($resizedImage, 0, 0, 0, 127));
        imagealphablending($resizedImage, false);
        imagesavealpha($resizedImage, true);
    }

    // Resize the image
    imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

    // Start with quality 80 and adjust to reach target size
    $quality = 85;
    $targetBytes = $targetSizeKB * 1024;
    $imageData = null;
    $attempts = 0;

    do {
        ob_start();
        switch ($mimeType) {
            case 'image/jpeg':
                imagejpeg($resizedImage, null, $quality);
                break;
            case 'image/png':
                // PNG compression level (0-9)
                $pngCompression = (int)(9 - ($quality / 10));
                $pngCompression = max(0, min(9, $pngCompression));
                imagepng($resizedImage, null, $pngCompression);
                break;
            case 'image/gif':
                imagegif($resizedImage);
                break;
            case 'image/webp':
                imagewebp($resizedImage, null, $quality);
                break;
            default:
                imagejpeg($resizedImage, null, $quality);
        }
        $imageData = ob_get_clean();
        $currentSize = strlen($imageData);
        $attempts++;

        // If image is too large, reduce quality
        if ($currentSize > $targetBytes && $quality > 10) {
            $quality -= 5;
        }
        // If image is too small and quality is low, increase quality
        elseif ($currentSize < $targetBytes * 0.3 && $quality < 95) {
            $quality += 5;
        } else {
            break;
        }

        // Prevent infinite loop
        if ($attempts > 20) break;
    } while ($currentSize > $targetBytes && $quality > 5);

    // If still too large, reduce dimensions further
    if (strlen($imageData) > $targetBytes && $newWidth > 200) {
        // Try resizing again with smaller dimensions
        $scaleFactor = 0.7;
        $newWidth = (int)($newWidth * $scaleFactor);
        $newHeight = (int)($newHeight * $scaleFactor);

        $resizedImage2 = imagecreatetruecolor($newWidth, $newHeight);

        if ($mimeType == 'image/png' || $mimeType == 'image/gif') {
            imagecolortransparent($resizedImage2, imagecolorallocatealpha($resizedImage2, 0, 0, 0, 127));
            imagealphablending($resizedImage2, false);
            imagesavealpha($resizedImage2, true);
        }

        imagecopyresampled($resizedImage2, $resizedImage, 0, 0, 0, 0, $newWidth, $newHeight, imagesx($resizedImage), imagesy($resizedImage));

        ob_start();
        if ($mimeType == 'image/png') {
            imagepng($resizedImage2, null, 9);
        } elseif ($mimeType == 'image/webp') {
            imagewebp($resizedImage2, null, 80);
        } else {
            imagejpeg($resizedImage2, null, 80);
        }
        $imageData = ob_get_clean();

        imagedestroy($resizedImage2);
    }

    // Free memory
    imagedestroy($image);
    imagedestroy($resizedImage);

    return $imageData;
}

// ============================================================
// DEDUCT ONE SLOT
// ============================================================
function deductSlot($db)
{
    try {
        // Get one slot
        $row = $db->query("SELECT rowid, number FROM activation_slot WHERE number > 0 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $new_number = $row['number'] - 1;
            if ($new_number > 0) {
                $db->exec("UPDATE activation_slot SET number = " . (int)$new_number . " WHERE rowid = " . (int)$row['rowid']);
            } else {
                $db->exec("DELETE FROM activation_slot WHERE rowid = " . (int)$row['rowid']);
            }
            return true;
        }
        return false;
    } catch (PDOException $e) {
        return false;
    }
}

// 📝 Handling form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check if the necessary form data is available
    if (
        isset($_POST['user_id']) && isset($_POST['name']) &&
        isset($_POST['sex']) && isset($_POST['level_table']) &&
        isset($_FILES['picture']['tmp_name']) && !empty($_FILES['picture']['tmp_name'])
    ) {

        // Check if there are available slots
        if ($slot_count <= 0) {
            $_SESSION['message'] = ["text" => "❌ No activation slots available. Please purchase more slots.", "type" => "error"];
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }

        // 📥 Retrieve form data
        $user_id = trim($_POST['user_id']);
        $name = trim($_POST['name']);
        $sex = trim($_POST['sex']);
        $table_name = trim($_POST['level_table']);
        $picturePath = $_FILES['picture']['tmp_name'];

        try {
            // 🖼️ Resize and compress the image to ~250KB
            $picture = resizeAndCompressImage($picturePath, 250);

            // 📤 Call the function to insert student data
            insertStudent($db, $table_name, $user_id, $name, $sex, $picture);

            // Deduct one slot after successful insertion
            if ($_SESSION['message']['type'] === 'success') {
                deductSlot($db);
                // Update slot count for display
                $slot_stmt = $db->query("SELECT COALESCE(SUM(number), 0) as total FROM activation_slot");
                $slot_count = $slot_stmt->fetchColumn();
            }

            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        } catch (Exception $e) {
            $_SESSION['message'] = ["text" => "Error processing image: " . $e->getMessage(), "type" => "error"];
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
    } else {
        $_SESSION['message'] = ["text" => "Please fill in all fields, select a level, and upload a picture.", "type" => "error"];
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

// 💬 Retrieve and clear the session message
$message = isset($_SESSION['message']) ? $_SESSION['message'] : '';
unset($_SESSION['message']);

// Get current page name for active navigation
$current_page = basename($_SERVER['PHP_SELF']);

// Get school info for Buy Activation Pin button
$school_stmt = $db->query("SELECT school_name, institution_id FROM schools ORDER BY id DESC LIMIT 1");
$school_data = $school_stmt->fetch(PDO::FETCH_ASSOC);
$school_name = $school_data['school_name'] ?? '';
$institution_id = $school_data['institution_id'] ?? '';
$subdomain_host = $_SERVER['HTTP_HOST'];
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CAOSCE · Add Students</title>
    <link rel="icon" type="image/x-icon" href="CAOSCE Network.ico">

    <!-- Font Awesome 6 (Free) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /*
|--------------------------------------------------------------------------
| ROOT VARIABLES
|--------------------------------------------------------------------------
*/
        :root {
            --primary: #4361ee;
            --primary-dark: #0d47a1;
            --primary-light: #1565c0;
            --success: #4cc9f0;
            --danger: #f72585;
            --dark: #071a31;
            --ink: #1a2332;
            --gray: #6b7a8f;
            --light-gray: #f0f4f8;
            --white: #ffffff;
            --shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            --transition: 0.3s ease;
        }

        /*
|--------------------------------------------------------------------------
| RESET & BASE
|--------------------------------------------------------------------------
*/
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f0f4fb;
            color: var(--ink);
            line-height: 1.6;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /*
|--------------------------------------------------------------------------
| NAVIGATION (SOLID, NON-TRANSPARENT)
|--------------------------------------------------------------------------
*/
        .navbar {
            position: sticky;
            top: 0;
            z-index: 60;
            background: #ffffff;
            border-bottom: 2px solid #e2eaf2;
            padding: 0 5vw;
            height: 74px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 12px rgba(16, 35, 63, 0.06);
        }

        .brand {
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 800;
            font-size: 20px;
            color: var(--ink);
            text-decoration: none;
        }

        .brand-icon {
            width: 38px;
            height: 38px;
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            border-radius: 12px;
            display: grid;
            place-items: center;
            color: white;
            font-size: 18px;
            font-weight: 900;
            box-shadow: 0 8px 18px rgba(26, 108, 240, 0.25);
        }

        .brand-light {
            font-weight: 500;
            color: #4f6580;
        }

        .nav-links {
            display: flex;
            align-items: center;
            gap: 28px;
        }

        .nav-links a {
            font-size: 14px;
            font-weight: 600;
            color: #4f6580;
            text-decoration: none;
            transition: 0.2s;
            position: relative;
            padding: 6px 0;
        }

        .nav-links a i {
            margin-right: 6px;
            font-size: 13px;
        }

        .nav-links a:hover {
            color: #1a6cf0;
        }

        /* ACTIVE link with solid underline */
        .nav-links a.active {
            color: #1a6cf0;
        }

        .nav-links a.active::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            width: 100%;
            height: 3px;
            background: #1a6cf0;
            border-radius: 4px;
        }

        .nav-logout {
            background: #f0f4fb;
            border: 1px solid #d9e2eb;
            border-radius: 30px;
            padding: 6px 18px;
            font-weight: 600;
            font-size: 13px;
            color: var(--ink);
            transition: 0.2s;
        }

        .nav-logout:hover {
            background: #e2eaf2;
            border-color: #b0c4d8;
            color: #1a6cf0;
        }

        /*
|--------------------------------------------------------------------------
| MAIN CONTAINER (form card)
|--------------------------------------------------------------------------
*/
        main {
            flex: 1;
            padding: 30px 0;
        }

        .container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 24px;
            width: 90%;
            max-width: 600px;
            margin: 0 auto;
            padding: 35px 40px 40px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08);
            border: 1px solid #eef4fa;
        }

        .container:hover {
            transform: translateY(-2px);
            transition: transform 0.3s ease;
        }

        h2 {
            color: var(--ink);
            margin-bottom: 28px;
            font-size: 28px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        h2 i {
            color: #1a6cf0;
        }

        .slot-info {
            background: linear-gradient(135deg, #e8f5e9, #c8e6c9);
            padding: 12px 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid #a5d6a7;
        }

        .slot-info .slot-label {
            font-weight: 600;
            color: #2e7d32;
            font-size: 15px;
        }

        .slot-info .slot-count {
            font-weight: 700;
            color: #1b5e20;
            font-size: 20px;
            background: white;
            padding: 4px 16px;
            border-radius: 8px;
            border: 1px solid #a5d6a7;
        }

        .slot-info .slot-count.zero {
            color: #dc3545;
            border-color: #dc3545;
            background: #f8d7da;
        }

        /* ----- ADD SLOT SECTION ----- */
        .add-slot-section {
            background: #fff3cd;
            padding: 18px 20px;
            border-radius: 12px;
            border: 1px solid #ffc107;
            margin-bottom: 25px;
        }

        .add-slot-section .slot-form {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
        }

        .add-slot-section .slot-form label {
            font-weight: 600;
            color: #856404;
            font-size: 14px;
            margin-bottom: 0;
        }

        .add-slot-section .slot-form input[type="text"] {
            flex: 1;
            min-width: 150px;
            padding: 10px 14px;
            border: 2px solid #ffc107;
            border-radius: 8px;
            font-size: 14px;
            background: white;
        }

        .add-slot-section .slot-form input[type="text"]:focus {
            outline: none;
            border-color: #1a6cf0;
            box-shadow: 0 0 0 4px rgba(26, 108, 240, 0.12);
        }

        .add-slot-section .slot-form .btn {
            padding: 10px 20px;
            font-size: 14px;
            border-radius: 8px;
        }

        .btn-buy-pin {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 10px 24px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-buy-pin:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(40, 167, 69, 0.3);
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--ink);
            font-size: 14px;
        }

        label i {
            margin-right: 6px;
            color: #1a6cf0;
        }

        .form-hint {
            font-size: 12px;
            color: #6b7a8f;
            margin-top: 4px;
        }

        .form-hint a {
            color: #1a6cf0;
            text-decoration: none;
            font-weight: 600;
        }

        .form-hint a:hover {
            text-decoration: underline;
        }

        input[type="text"],
        input[type="file"],
        select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s;
            background: #fafcff;
            box-sizing: border-box;
        }

        input[type="text"]:focus,
        input[type="file"]:focus,
        select:focus {
            border-color: #1a6cf0;
            outline: none;
            box-shadow: 0 0 0 4px rgba(26, 108, 240, 0.12);
            background: white;
        }

        input[type="file"] {
            padding: 10px 12px;
        }

        select option {
            padding: 8px;
        }

        .btn {
            display: inline-block;
            padding: 13px 30px;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
            text-align: center;
        }

        .btn-primary {
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            color: white;
            width: 100%;
            margin-top: 6px;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(26, 108, 240, 0.3);
        }

        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .btn-primary:disabled:hover {
            transform: none;
            box-shadow: none;
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(40, 167, 69, 0.3);
        }

        .btn-danger {
            background: #dc3545;
            color: white;
            padding: 10px 28px;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(220, 53, 69, 0.25);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
            padding: 10px 28px;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .bottom-center {
            display: flex;
            justify-content: center;
            gap: 12px;
            margin-top: 30px;
            flex-wrap: wrap;
        }

        .empty-levels {
            text-align: center;
            padding: 30px 20px;
            background: #f8fafc;
            border-radius: 12px;
            border: 2px dashed #d9e2eb;
        }

        .empty-levels i {
            font-size: 48px;
            color: #d9e2eb;
            display: block;
            margin-bottom: 12px;
        }

        .empty-levels p {
            color: #6b7a8f;
            font-size: 16px;
        }

        /*
|--------------------------------------------------------------------------
| NOTIFICATIONS
|--------------------------------------------------------------------------
*/
        .notification {
            position: fixed;
            top: 90px;
            left: 50%;
            transform: translateX(-50%);
            padding: 14px 28px;
            border-radius: 12px;
            z-index: 1000;
            display: flex;
            align-items: center;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
            animation: slide-down 0.5s forwards;
            font-weight: 500;
        }

        .notification.success {
            background: #d4edda;
            color: #155724;
            border-left: 5px solid #28a745;
        }

        .notification.error {
            background: #f8d7da;
            color: #721c24;
            border-left: 5px solid #dc3545;
        }

        .notification i {
            margin-right: 12px;
            font-size: 20px;
        }

        @keyframes slide-down {
            from {
                top: -100px;
                opacity: 0;
            }

            to {
                top: 90px;
                opacity: 1;
            }
        }

        .fade-out {
            animation: fade-out 0.5s forwards;
        }

        @keyframes fade-out {
            from {
                opacity: 1;
            }

            to {
                opacity: 0;
                visibility: hidden;
            }
        }

        /*
|--------------------------------------------------------------------------
| FOOTER (solid)
|--------------------------------------------------------------------------
*/
        .footer {
            margin-top: auto;
            padding: 24px 5vw 20px;
            background: #071a31;
            color: #b6c9dd;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
            border-top: 1px solid #1f3550;
        }

        .footer strong {
            color: #dce7f5;
        }

        .footer .meta {
            display: flex;
            gap: 24px;
            align-items: center;
        }

        .footer .meta span {
            color: #7c92ab;
        }

        /*
|--------------------------------------------------------------------------
| RESPONSIVE
|--------------------------------------------------------------------------
*/
        @media (max-width: 900px) {
            .navbar {
                padding: 0 4vw;
                height: 68px;
            }

            .nav-links a:not(.nav-logout) {
                display: none;
            }

            .nav-links a.nav-logout {
                display: inline-block;
            }

            .container {
                padding: 25px 20px;
            }

            .add-slot-section .slot-form {
                flex-direction: column;
                align-items: stretch;
            }

            .add-slot-section .slot-form input[type="text"] {
                min-width: auto;
            }
        }

        @media (max-width: 600px) {
            .container {
                padding: 20px 16px;
                width: 95%;
            }

            h2 {
                font-size: 22px;
            }

            .footer {
                flex-direction: column;
                gap: 10px;
                align-items: flex-start;
            }

            .notification {
                width: 90%;
                top: 80px;
                font-size: 14px;
                padding: 12px 18px;
            }

            .bottom-center {
                flex-direction: column;
                align-items: center;
            }

            .bottom-center .btn {
                width: 100%;
                justify-content: center;
            }

            .slot-info {
                flex-direction: column;
                gap: 8px;
                text-align: center;
            }

            .add-slot-section .slot-form {
                flex-direction: column;
                align-items: stretch;
            }

            .add-slot-section .slot-form input[type="text"] {
                min-width: auto;
            }

            @keyframes slide-down {
                from {
                    top: -100px;
                    opacity: 0;
                }

                to {
                    top: 80px;
                    opacity: 1;
                }
            }
        }

        @media (max-width: 400px) {
            .brand {
                font-size: 16px;
            }

            .brand-icon {
                width: 30px;
                height: 30px;
                font-size: 14px;
            }
        }
    </style>
</head>

<body>

    <!-- ============================================================
         NAVIGATION (SOLID, NON-TRANSPARENT)
         ============================================================ -->
    <header class="navbar">
        <a href="admin.php" class="brand">
            <span class="brand-icon">CN</span>
            <span>CAOSCE <span class="brand-light">Network</span></span>
        </a>
        <div class="nav-links">
            <a href="admin.php" class="<?php echo $current_page == 'admin.php' ? 'active' : ''; ?>">
                <i class="fas fa-th-large"></i> Dashboard
            </a>
            <a href="classes.php" class="<?php echo $current_page == 'classes.php' ? 'active' : ''; ?>">
                <i class="fas fa-user-plus"></i> Class lists
            </a>
            <a href="result.php" class="<?php echo $current_page == 'result.php' ? 'active' : ''; ?>">
                <i class="fas fa-chart-pie"></i>OSCE Result
            </a>
            <a href="exam_manager.php" class="<?php echo $current_page == 'exam_manager.php' ? 'active' : ''; ?>">
                <i class="fas fa-sliders-h"></i> Exams settings
            </a>
            <a href="logout.php" class="nav-logout">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </div>
    </header>

    <!-- ============================================================
         MAIN CONTENT
         ============================================================ -->
    <main>
        <div class="container">
            <h2><i class="fas fa-user-graduate"></i> CAOSCE Network Student Onboarding</h2>

            <!-- Slot Info Display -->
            <?php if ($slot_count > 0): ?>
                <div class="slot-info">
                    <span class="slot-label"><i class="fas fa-ticket-alt"></i> Available Onboarding Slots</span>
                    <span class="slot-count"><?= $slot_count ?></span>
                </div>
            <?php else: ?>
                <div class="slot-info">
                    <span class="slot-label"><i class="fas fa-ticket-alt"></i> Available Onboarding Slots</span>
                    <span class="slot-count zero"><?= $slot_count ?> (No slots available)</span>
                </div>
            <?php endif; ?>

            <!-- Add Slot Section -->
           
            <a href="https://caosce.net/buy_pin.php?school_name=<?= urlencode($school_name) ?>&institution_id=<?= urlencode($institution_id) ?>&subdomain=<?= urlencode($subdomain_host) ?>" target="_blank" class="btn-buy-pin">
                <i class="fas fa-shopping-cart"></i> Buy Onboarding slots
            </a>

            <?php if (empty($levels)): ?>
                <!-- No levels exist - show message -->
                <div class="empty-levels">
                    <i class="fas fa-layer-group"></i>
                    <p><strong>No levels available</strong></p>
                    <p style="margin-top:8px; font-size:14px;">
                        Please go to the <a href="classes.php" style="color:#1a6cf0; font-weight:600;">Levels Management</a> page to create a level first before onboarding students.
                    </p>
                </div>
                <div class="bottom-center">
                    <button class="btn btn-secondary" onclick="window.location.href='classes.php'">
                        <i class="fas fa-layer-group"></i> Go to Levels Management
                    </button>
                    <button class="btn btn-danger" onclick="window.location.href='admin.php'">
                        <i class="fas fa-arrow-left"></i> Go Back
                    </button>
                </div>
            <?php else: ?>
                <!-- Levels exist - show form -->
                <form action="" method="POST" enctype="multipart/form-data">
                    <!-- Level Selection -->
                    <div class="form-group">
                        <label for="level_table"><i class="fas fa-layer-group"></i> Select Level</label>
                        <select name="level_table" id="level_table" required>
                            <option value="">-- Select Level --</option>
                            <?php foreach ($levels as $level): ?>
                                <option value="<?= htmlspecialchars($level['table_name']) ?>"
                                    <?= ($last_selected_table === $level['table_name']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($level['display_name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="user_id"><i class="fas fa-id-card"></i> Matric or Exam no (must be the last numbers after the last / only)</label>
                        <input type="text" name="user_id" id="user_id" required placeholder="e.g., 2024/1234">
                        <div class="form-hint">
                            <i class="fas fa-info-circle"></i> You can have duplicate user IDs as long as the names are different.
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="name"><i class="fas fa-user"></i> Full Name</label>
                        <input type="text" name="name" id="name" required placeholder="Enter student's full name">
                    </div>

                    <div class="form-group">
                        <label for="sex"><i class="fas fa-venus-mars"></i> Gender</label>
                        <select name="sex" id="sex" required>
                            <option value="">-- Select Gender --</option>
                            <option value="male">♂️ Male</option>
                            <option value="female">♀️ Female</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="picture"><i class="fas fa-camera"></i> Photo</label>
                        <input type="file" name="picture" id="picture" accept="image/*" required>
                        <div class="form-hint">
                            <i class="fas fa-info-circle"></i> Image will be automatically compressed to ~250KB for optimal storage.
                        </div>
                    </div>

                    <?php if ($slot_count > 0): ?>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus-circle"></i> Onboard Student
                        </button>
                    <?php else: ?>
                        <button type="submit" class="btn btn-primary" disabled>
                            <i class="fas fa-times-circle"></i> No Onboarding Slots Available
                        </button>
                    <?php endif; ?>
                </form>

                <div class="bottom-center">
                    <button class="btn btn-danger" onclick="window.location.href='admin.php'">
                        <i class="fas fa-arrow-left"></i> Go Back
                    </button>
                </div>
            <?php endif; ?>

        </div>
    </main>

    <!-- ============================================================
         FOOTER
         ============================================================ -->
    <footer class="footer">
        <div>
            <strong><i class="fas fa-network-wired" style="margin-right:8px;"></i> CAOSCE Network</strong>
            <span style="margin-left:18px;">© <?php echo date('Y'); ?> All rights reserved</span>
        </div>
        <div class="meta">
            <span><i class="fas fa-code"></i> v2.0</span>
            <span>|</span>
            <span><i class="fas fa-user-cog"></i> Admin Panel</span>
            <span>|</span>
        </div>
    </footer>

    <!-- ============================================================
         NOTIFICATION
         ============================================================ -->
    <?php if ($message): ?>
        <div class="notification <?php echo htmlspecialchars($message['type']); ?>">
            <i class="fas <?php echo $message['type'] == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?>"></i>
            <?php echo htmlspecialchars($message['text']); ?>
        </div>
    <?php endif; ?>

    <script>
        // Auto-hide notification after 5 seconds
        document.addEventListener('DOMContentLoaded', () => {
            const notification = document.querySelector('.notification');
            if (notification) {
                notification.style.display = 'flex';
                setTimeout(() => {
                    notification.classList.add('fade-out');
                    setTimeout(() => {
                        notification.remove();
                    }, 500);
                }, 5000);
            }
        });

        // Store the selected level in session when changed
        document.addEventListener('DOMContentLoaded', function() {
            const levelSelect = document.getElementById('level_table');

            // Save selection to session via AJAX when changed
            if (levelSelect) {
                levelSelect.addEventListener('change', function() {
                    const selectedTable = this.value;
                    if (selectedTable) {
                        fetch('save_level_session.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: 'table_name=' + encodeURIComponent(selectedTable)
                        }).catch(err => console.log('Error saving level preference:', err));
                    }
                });
            }
        });

        // Show file size info when a file is selected
        document.addEventListener('DOMContentLoaded', function() {
            const fileInput = document.getElementById('picture');
            if (fileInput) {
                const hint = fileInput.closest('.form-group').querySelector('.form-hint');

                fileInput.addEventListener('change', function() {
                    if (this.files && this.files[0]) {
                        const fileSizeMB = (this.files[0].size / (1024 * 1024)).toFixed(2);
                        hint.innerHTML = '<i class="fas fa-file-image"></i> Selected: ' +
                            this.files[0].name +
                            ' (' + fileSizeMB + ' MB) - Will be compressed to ~250KB';
                    }
                });
            }
        });
    </script>

</body>

</html>