<?php
session_start();

// Connect to SQLite database
$db = new PDO('sqlite:database.db');



// ✅ SET created_at for existing rows (current time)
$db->exec("UPDATE students SET created_at = CURRENT_TIMESTAMP WHERE created_at IS NULL");

// ✅ AUTO-DELETE students older than 6 years
$db->exec("
    DELETE FROM students
    WHERE created_at <= datetime('now', '-6 years')
");




// Before using the table anywhere
$db->exec('CREATE TABLE IF NOT EXISTS activation_slot (number INTEGER)');

// Fetch current slots
$slot_count_stmt = $db->query('SELECT COALESCE(SUM(number),0) as total FROM activation_slot');
$slot_count = $slot_count_stmt->fetchColumn();

// ✅ Check if a delete request has been made
if (isset($_POST['delete_user_id'])) {
    $delete_user_id = $_POST['delete_user_id'];

    // ✅ Prevent deletion of user_id 0
    if ($delete_user_id !== "0") {
        $delete_stmt = $db->prepare('DELETE FROM students WHERE user_id = :user_id');
        $delete_stmt->bindParam(':user_id', $delete_user_id, PDO::PARAM_STR);
        $delete_stmt->execute();
    }
}

// Check if manual burn is requested and slot_count is > 0
if (isset($_POST['manual_activate_user_id'])) {
    if ($slot_count <= 0) {
        echo "<script>alert('No activation slot is left. Please buy more slots.');</script>";
    } else {
        $user_id = $_POST['manual_activate_user_id'];

        // Check if user is already activated
        $check_stmt = $db->prepare('SELECT COUNT(*) FROM activated_students WHERE user_id = :user_id');
        $check_stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
        $check_stmt->execute();

        if ($check_stmt->fetchColumn() > 0) {
            echo "<script>alert('This user is already activated. No slot was used.');</script>";
        } else {
            // Activate the user
            $stmt = $db->prepare('INSERT INTO activated_students (user_id) VALUES (:user_id)');
            $stmt->bindParam(':user_id', $user_id);
            $stmt->execute();

            // Fetch 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']);
                }
            }

            // ✅ Redirect to success page
            header('Location: student_activated_success.php');
            exit;
        }
    }
}

// Check if an activation request has been made
if (isset($_POST['activate_user_id']) && isset($_POST['activation_pin'])) {
    $activate_user_id = $_POST['activate_user_id'];
    $activation_pin = $_POST['activation_pin'];

    // ✅ Reject if pin length is greater than 100
    if (strlen($activation_pin) > 100) {
        echo "<script>alert('Activation pin cannot exceed 10 characters.');</script>";
    } else {
        // Proceed with verification since length is OK
        $verification_url = 'https://cbt.net.ng/verify_pin.php';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $verification_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['pin' => $activation_pin]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            echo "<script>alert('Error connecting to verification server.');</script>";
            curl_close($ch);
            exit;
        }

        curl_close($ch);
        $response_data = json_decode($response, true);

        if ($response_data && $response_data['status'] === 'success') {
            // Check if user is already activated
            $check_stmt = $db->prepare('SELECT COUNT(*) FROM activated_students WHERE user_id = :user_id');
            $check_stmt->bindParam(':user_id', $activate_user_id, PDO::PARAM_STR);
            $check_stmt->execute();

            if ($check_stmt->fetchColumn() == 0) {
                $insert_stmt = $db->prepare('INSERT INTO activated_students (user_id) VALUES (:user_id)');
                $insert_stmt->bindParam(':user_id', $activate_user_id, PDO::PARAM_STR);
                $insert_stmt->execute();

                echo "<script>alert('Student activated successfully!');</script>";
            } else {
                echo "<script>alert('User already activated.');</script>";
            }
        } else {
            echo "<script>alert('Invalid activation pin!');</script>";
        }
    }
}

// Initialize query to fetch all students
$query = 'SELECT * FROM students';

// Check if a search request has been made
$search = isset($_GET['search']) ? $_GET['search'] : '';
if ($search) {
    $query .= ' WHERE user_id LIKE :search OR name LIKE :search';
}

$query .= ' ORDER BY CAST(SUBSTR(user_id, INSTR(user_id, "/") + 1) AS INTEGER) ASC';

// Prepare the statement
$stmt = $db->prepare($query);

// Bind the search parameter if a search was made
if ($search) {
    $searchParam = '%' . $search . '%';
    $stmt->bindParam(':search', $searchParam, PDO::PARAM_STR);
}

// Execute the statement
$stmt->execute();

// 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();
                        header('Location: success.php');
                        exit;
                    } 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();
                        header('Location: success.php');
                        exit;
                    }
                } else {
                    echo "<script>alert('No valid number found at the beginning of the code.');</script>";
                }
            } else {
                echo "<script>alert('Code does not begin with a number.');</script>";
            }
        } else {
            echo "<script>alert('Invalid pin or verification failed.');</script>";
        }
    } else {
        echo "<script>alert('Please enter a valid code.');</script>";
    }
}

// Upload students button handler
if (isset($_POST['upload_students'])) {
    try {
        set_time_limit(300); // give enough time
        ini_set('memory_limit', '512M');

        // ✅ Fetch and encode pictures
        $students_raw = $db->query("SELECT user_id, name, picture, sex FROM students")->fetchAll(PDO::FETCH_ASSOC);

        $students = [];
        foreach ($students_raw as $row) {
            $students[] = [
                'user_id' => $row['user_id'],
                'name'    => $row['name'],
                'picture' => $row['picture'] !== null ? base64_encode($row['picture']) : '',
                'sex'     => $row['sex']
            ];
        }

        if ($students) {
            $json = json_encode($students);

            $ch = curl_init("https://cbt.net.ng/nducaosce/upload_students.php");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($json)
            ]);

            $response = curl_exec($ch);
            if (curl_errno($ch)) {
                echo "<script>alert('Error uploading: " . curl_error($ch) . "');</script>";
            } else {
                echo "<script>alert('Upload response: " . htmlspecialchars($response) . "');</script>";
            }
            curl_close($ch);
        } else {
            echo "<script>alert('No students found in local DB.');</script>";
        }
    } catch (Exception $e) {
        echo "<script>alert('Upload failed: " . $e->getMessage() . "');</script>";
    }
}

// Handle activate all users
if (isset($_POST['activate_all_users'])) {
    // Count total users
    $total_users = $db->query("SELECT COUNT(*) FROM students")->fetchColumn();
    $already_activated = $db->query("SELECT COUNT(*) FROM activated_students")->fetchColumn();
    $remaining_to_activate = $total_users - $already_activated;

    if ($remaining_to_activate <= 0) {
        echo "<script>alert('All users are already activated.');</script>";
    } elseif ($slot_count < $remaining_to_activate) {
        echo "<script>alert('Not enough activation slots. Please buy more activation pins.');</script>";
    } else {
        // Fetch all non-activated users
        $users_to_activate = $db->query("
            SELECT user_id FROM students 
            WHERE user_id NOT IN (SELECT user_id FROM activated_students)
        ")->fetchAll(PDO::FETCH_COLUMN);

        // Begin transaction
        $db->beginTransaction();
        try {
            $stmt = $db->prepare("INSERT INTO activated_students (user_id) VALUES (:user_id)");
            foreach ($users_to_activate as $uid) {
                $stmt->execute([':user_id' => $uid]);
            }

            // Deduct used slots
            $used = $remaining_to_activate;
            $row = $db->query("SELECT rowid, number FROM activation_slot WHERE number > 0 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
            if ($row) {
                $new_number = $row['number'] - $used;
                if ($new_number > 0) {
                    $db->exec("UPDATE activation_slot SET number = $new_number WHERE rowid = {$row['rowid']}");
                } else {
                    $db->exec("DELETE FROM activation_slot WHERE rowid = {$row['rowid']}");
                }
            }

            $db->commit();
            echo "<script>alert('All users activated successfully!');</script>";
        } catch (Exception $e) {
            $db->rollBack();
            echo "<script>alert('Activation failed: " . $e->getMessage() . "');</script>";
        }
    }
}

// Get school info for the 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'];

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

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CAOSCE · Network</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>
        /* ----- RESET & BASE ----- */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Poppins', sans-serif;
            background: #f0f4fb;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            color: #10233f;
        }

        /* ----- 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: #10233f;
            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;
        }

        .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: #10233f;
            transition: 0.2s;
        }

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

        /* ----- MAIN CONTAINER ----- */
        main {
            flex: 1;
            padding: 30px 5vw;
        }

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

        /* ----- PAGE HEADER ----- */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .page-header h1 {
            font-size: 26px;
            font-weight: 700;
            color: #10233f;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header h1 i {
            color: #1a6cf0;
        }

        .page-header .subtitle {
            font-size: 14px;
            color: #6b7a8f;
        }

        .header-actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        /* ----- BUTTONS ----- */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 9px 20px;
            border: none;
            border-radius: 30px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            font-size: 14px;
        }

        .btn-back {
            background: #e9ecef;
            color: #4f6580;
        }

        .btn-back:hover {
            background: #dde1e6;
            transform: translateY(-2px);
        }

        .btn-primary {
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            color: white;
            box-shadow: 0 4px 14px rgba(26, 108, 240, 0.25);
        }

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

        .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;
        }

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

        .btn-warning {
            background: linear-gradient(135deg, #ff9800, #f57c00);
            color: white;
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(255, 152, 0, 0.35);
        }

        .btn-sm {
            padding: 5px 14px;
            font-size: 12px;
            border-radius: 20px;
        }

        /* ----- SEARCH BAR ----- */
        .search-bar {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .search-bar .search-input-wrapper {
            flex: 1;
            display: flex;
            align-items: center;
            background: #f8fafc;
            border-radius: 30px;
            padding: 4px 4px 4px 18px;
            border: 2px solid #e9ecef;
            transition: 0.3s;
            min-width: 200px;
        }

        .search-bar .search-input-wrapper:focus-within {
            border-color: #1a6cf0;
            box-shadow: 0 0 0 4px rgba(26, 108, 240, 0.12);
        }

        .search-bar .search-input-wrapper i {
            color: #6b7a8f;
            font-size: 16px;
        }

        .search-bar .search-input-wrapper input {
            flex: 1;
            border: none;
            outline: none;
            padding: 10px 14px;
            font-size: 15px;
            background: transparent;
            color: #10233f;
        }

        .search-bar .search-input-wrapper input::placeholder {
            color: #a0b0c4;
        }

        .search-bar .search-input-wrapper button {
            background: linear-gradient(135deg, #1a6cf0, #6d5dfc);
            color: white;
            border: none;
            border-radius: 30px;
            padding: 8px 20px;
            font-weight: 600;
            cursor: pointer;
            transition: 0.3s;
            font-size: 14px;
        }

        .search-bar .search-input-wrapper button:hover {
            transform: scale(1.03);
        }

        /* ----- SLOT INFO BAR ----- */
        .slot-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #f8fafc;
            padding: 12px 20px;
            border-radius: 14px;
            border: 1px solid #eef4fa;
            margin-bottom: 24px;
            flex-wrap: wrap;
            gap: 12px;
        }

        .slot-bar .slot-info {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
            font-weight: 500;
        }

        .slot-bar .slot-info i {
            color: #1a6cf0;
            font-size: 18px;
        }

        .slot-bar .slot-count {
            font-weight: 700;
            color: #1a6cf0;
            font-size: 18px;
        }

        .slot-bar .slot-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        /* ----- TABLE ----- */
        .table-wrapper {
            overflow-x: auto;
            border-radius: 12px;
            border: 1px solid #eef4fa;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        th {
            background: #f8fafc;
            color: #10233f;
            font-weight: 700;
            padding: 13px 16px;
            text-align: left;
            border-bottom: 2px solid #e2eaf2;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        td {
            padding: 12px 16px;
            border-bottom: 1px solid #eef4fa;
            vertical-align: middle;
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover td {
            background: #f8fafc;
        }

        td img {
            border-radius: 8px;
            width: 60px;
            height: 60px;
            object-fit: cover;
            border: 2px solid #eef4fa;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background: #fff3cd;
            color: #856404;
        }

        .action-cell {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
            align-items: center;
        }

        .action-cell .btn-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 32px;
            height: 32px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: 0.3s;
            color: white;
            font-size: 13px;
        }

        .action-cell .btn-icon:hover {
            transform: translateY(-2px);
        }

        .btn-delete-icon {
            background: #dc3545;
        }

        .btn-delete-icon:hover {
            background: #b91c1c;
            box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
        }

        .btn-activate-icon {
            background: #28a745;
        }

        .btn-activate-icon:hover {
            background: #1e7e34;
            box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
        }

        .btn-activate-icon:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

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

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #6b7a8f;
        }

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

        /* ----- MODALS ----- */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            backdrop-filter: blur(4px);
        }

        .modal-content {
            background: white;
            padding: 30px 35px;
            width: 90%;
            max-width: 420px;
            border-radius: 20px;
            box-shadow: 0 30px 60px rgba(0, 0, 0, 0.2);
            animation: modalIn 0.3s ease;
        }

        @keyframes modalIn {
            from {
                transform: scale(0.9) translateY(20px);
                opacity: 0;
            }

            to {
                transform: scale(1) translateY(0);
                opacity: 1;
            }
        }

        .modal-content .close {
            float: right;
            font-size: 28px;
            font-weight: 700;
            color: #999;
            cursor: pointer;
            transition: 0.2s;
            background: none;
            border: none;
            padding: 0 8px;
        }

        .modal-content .close:hover {
            color: #333;
        }

        .modal-content h2 {
            font-size: 22px;
            margin-bottom: 16px;
            color: #10233f;
            text-align: center;
        }

        .modal-content h2 i {
            color: #1a6cf0;
        }

        .modal-content .modal-subtitle {
            text-align: center;
            color: #6b7a8f;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .modal-content input[type="text"] {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 15px;
            transition: 0.3s;
            margin-bottom: 16px;
        }

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

        .modal-content .modal-buttons {
            display: flex;
            gap: 12px;
            justify-content: center;
            flex-wrap: wrap;
        }

        .modal-content .modal-buttons .btn {
            min-width: 120px;
            justify-content: center;
        }

        .modal-content .modal-divider {
            border: none;
            border-top: 1px solid #eef4fa;
            margin: 16px 0;
        }

        /* ----- FOOTER ----- */
        .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;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .header-actions {
                width: 100%;
            }

            .header-actions .btn {
                flex: 1;
                justify-content: center;
            }
        }

        @media (max-width: 600px) {
            main {
                padding: 16px 4vw;
            }

            .container {
                padding: 18px 14px;
            }

            .page-header h1 {
                font-size: 20px;
            }

            .search-bar .search-input-wrapper {
                flex-wrap: wrap;
                border-radius: 16px;
                padding: 8px;
                background: #f8fafc;
            }

            .search-bar .search-input-wrapper input {
                width: 100%;
                text-align: center;
                padding: 10px;
            }

            .search-bar .search-input-wrapper button {
                width: 100%;
                border-radius: 30px;
                justify-content: center;
            }

            .search-bar .search-input-wrapper i {
                display: none;
            }

            .slot-bar {
                flex-direction: column;
                align-items: stretch;
                text-align: center;
            }

            .slot-bar .slot-actions {
                justify-content: center;
            }

            th,
            td {
                padding: 8px 10px;
                font-size: 12px;
            }

            td img {
                width: 40px;
                height: 40px;
            }

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

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

            .modal-content {
                padding: 25px 20px;
            }
        }

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

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

    <script>
        let currentUserId = null;

        function confirmDelete() {
            return confirm("Are you sure you want to delete this user?");
        }

        function openModal(userId) {
            currentUserId = userId;
            document.getElementById('chooseMethodModal').style.display = 'flex';
        }

        function closeChooseModal() {
            document.getElementById('chooseMethodModal').style.display = 'none';
        }

        function choosePIN() {
            closeChooseModal();
            document.getElementById('pinModal').style.display = 'flex';
            document.getElementById('pin_activate_user_id').value = currentUserId;
        }

        function chooseSLOT() {
            closeChooseModal();
            var form = document.createElement('form');
            form.method = 'POST';
            var inputUser = document.createElement('input');
            inputUser.type = 'hidden';
            inputUser.name = 'manual_activate_user_id';
            inputUser.value = currentUserId;
            form.appendChild(inputUser);
            document.body.appendChild(form);
            form.submit();
        }

        function closePinModal() {
            document.getElementById('pinModal').style.display = 'none';
        }

        function closeSlotModal() {
            document.getElementById('addSlotModal').style.display = 'none';
        }

        // Close modals on outside click
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }

        // Close modals on Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                document.querySelectorAll('.modal').forEach(modal => {
                    modal.style.display = 'none';
                });
            }
        });
    </script>
</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">

            <!-- Page Header -->
            <div class="page-header">
                <div>
                    <h1>
                        <i class="fas fa-users"></i>
                        Exam Page/OSCE Exam Candidates
                    </h1>
                    <div class="subtitle">
                        <i class="fas fa-list-ul"></i>
                        Manage student records and activations for a scheduled CAOSCE/OSCE
                    </div>
                </div>
                <div class="header-actions">
                    <a href="admin.php" class="btn btn-back">
                        <i class="fas fa-arrow-left"></i> Go Back
                    </a>
                    <?php if ($search): ?>
                        <a href="show_all_students_details.php" class="btn btn-primary">
                            <i class="fas fa-list"></i> Show All
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Search Bar -->
            <form class="search-bar" method="GET" action="">
                <div class="search-input-wrapper">
                    <i class="fas fa-search"></i>
                    <input type="text" name="search" placeholder="Search by User ID or Name..."
                        value="<?php echo htmlspecialchars($search); ?>">
                    <button type="submit">Search</button>
                </div>
            </form>

            

            <!-- Table -->
            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th style="width:50px;">#</th>
                            <th>User ID</th>
                            <th>Name</th>
                            <th style="width:80px;">Photo</th>
                            <th style="width:220px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $counter = 1;
                        $has_rows = false;
                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                            $has_rows = true;
                            // Check if activated
                            $activated_stmt = $db->prepare('SELECT COUNT(*) FROM activated_students WHERE user_id = :user_id');
                            $activated_stmt->bindParam(':user_id', $row['user_id'], PDO::PARAM_STR);
                            $activated_stmt->execute();
                            $is_activated = $activated_stmt->fetchColumn() > 0;
                        ?>
                            <tr>
                                <td><?= $counter++ ?></td>
                                <td><strong><?= htmlspecialchars($row['user_id']) ?></strong></td>
                                <td><?= htmlspecialchars($row['name']) ?></td>
                                <td>
                                    <?php if ($row['picture']): ?>
                                        <img src="data:image/jpeg;base64,<?= base64_encode($row['picture']) ?>" alt="Photo">
                                    <?php else: ?>
                                        <span style="color:#999; font-size:12px;">No photo</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="action-cell">
                                        <?php if ($row['user_id'] !== "0"): ?>
                                            <form method="POST" style="display:inline;" onsubmit="return confirmDelete();">
                                                <input type="hidden" name="delete_user_id" value="<?= htmlspecialchars($row['user_id']) ?>">
                                                <button type="submit" class="btn-icon btn-delete-icon" title="Delete User">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        <?php endif; ?>

                                        <?php if ($is_activated): ?>
                                            <span class="status-badge status-active">
                                                <i class="fas fa-check-circle"></i> Activated
                                            </span>
                                        <?php else: ?>
                                            <button class="btn-icon btn-activate-icon" onclick="openModal('<?= htmlspecialchars($row['user_id']) ?>')" title="Activate Student">
                                                <i class="fas fa-unlock"></i>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php } ?>

                        <?php if (!$has_rows): ?>
                            <tr>
                                <td colspan="5">
                                    <div class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <p>No students found<?= $search ? ' matching "' . htmlspecialchars($search) . '"' : '' ?>.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

        </div>
    </main>

    <!-- ============================================================
         ADD SLOT MODAL
         ============================================================ -->
    <div id="addSlotModal" class="modal">
        <div class="modal-content">
            <button class="close" onclick="closeSlotModal()">&times;</button>
          
            <form method="POST" action="">
                
                
            </form>

            <hr class="modal-divider">

            <!-- Buy Activation Pin Button -->
            <form method="POST" action="https://caosce.net/buy_pin.php" target="_blank" style="display:inline; width:100%;">
                <input type="hidden" name="school_name" value="<?= htmlspecialchars($school_name) ?>">
                <input type="hidden" name="institution_id" value="<?= htmlspecialchars($institution_id) ?>">
                <input type="hidden" name="subdomain" value="<?= htmlspecialchars($subdomain_host) ?>">
                <button type="submit" class="btn btn-primary" style="width:100%; justify-content:center; padding:12px; text-decoration:none; display:inline-flex; align-items:center; gap:10px; margin-top:12px;">
                    <i class="fas fa-shopping-cart"></i> Buy Activation Pin
                </button>
            </form>
        </div>
    </div>

    <!-- ============================================================
         CHOOSE METHOD MODAL
         ============================================================ -->
    <div id="chooseMethodModal" class="modal">
        <div class="modal-content">
            <button class="close" onclick="closeChooseModal()">&times;</button>
            <h2><i class="fas fa-user-check"></i> Activate Student</h2>
            <p class="modal-subtitle">How would you like to activate this student?</p>
            <div class="modal-buttons">
                <button class="btn btn-primary" onclick="choosePIN()">
                    <i class="fas fa-key"></i> Use PIN
                </button>
                <button class="btn btn-success" onclick="chooseSLOT()">
                    <i class="fas fa-ticket-alt"></i> Use Slot
                </button>
            </div>
        </div>
    </div>

    <!-- ============================================================
         PIN MODAL
         ============================================================ -->
    <div id="pinModal" class="modal">
        <div class="modal-content">
            <button class="close" onclick="closePinModal()">&times;</button>
            <h2><i class="fas fa-key"></i> Enter PIN</h2>
            <form method="POST" action="">
                <input type="hidden" name="activate_user_id" id="pin_activate_user_id">
                <input type="text" name="activation_pin" placeholder="Enter activation PIN" required>
                <button type="submit" class="btn btn-primary" style="width:100%; justify-content:center; padding:12px;">
                    <i class="fas fa-check"></i> Activate
                </button>
            </form>
        </div>
    </div>

    <!-- ============================================================
         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>

</body>

</html>