<?php
session_start();

/* =====================
   DATABASE
===================== */
$db = new PDO('sqlite:database.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

/* =====================
   SLOT TABLE
===================== */
$db->exec("CREATE TABLE IF NOT EXISTS activation_slot (number INTEGER)");

$slot_count = $db->query("SELECT COALESCE(SUM(number),0) FROM activation_slot")->fetchColumn();

/* =====================
   ADD SLOT
===================== */
if (isset($_POST['add_slot_code'])) {
    $code = trim($_POST['add_slot_code']);

    if ($code !== '') {
        $ch = curl_init("https://cbt.net.ng/verify_pin.php");
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query(['pin' => $code]),
            CURLOPT_RETURNTRANSFER => true
        ]);
        $response = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($response, true);

        if ($result && $result['status'] === 'success') {
            if (preg_match('/^(\d+)/', $code, $m)) {
                $new = (int)$m[1];

                $current = $db->query("SELECT number FROM activation_slot LIMIT 1")->fetchColumn();

                if ($current === false) {
                    $db->prepare("INSERT INTO activation_slot (number) VALUES (?)")->execute([$new]);
                } else {
                    $db->prepare("UPDATE activation_slot SET number=?")->execute([$current + $new]);
                }

                header("Location: activation_page.php");
                exit;
            }
        }

        echo "<script>alert('Invalid slot code');</script>";
    }
}

/* =====================
   SLOT ACTIVATION
===================== */
if (isset($_POST['manual_activate_user_id'])) {
    if ($slot_count <= 0) {
        echo "<script>alert('No activation slots left');</script>";
    } else {
        $uid = $_POST['manual_activate_user_id'];

        $check = $db->prepare("SELECT COUNT(*) FROM activated_students WHERE user_id=?");
        $check->execute([$uid]);

        if ($check->fetchColumn() == 0) {
            $db->prepare("INSERT INTO activated_students (user_id) VALUES (?)")->execute([$uid]);

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

            echo "<script>alert('Student activated successfully');</script>";
        } else {
            echo "<script>alert('Student already activated');</script>";
        }
    }
}

/* =====================
   PIN ACTIVATION
===================== */
if (isset($_POST['activate_user_id'], $_POST['activation_pin'])) {
    $uid = $_POST['activate_user_id'];
    $pin = $_POST['activation_pin'];

    $ch = curl_init("https://cbt.net.ng/verify_pin.php");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query(['pin' => $pin]),
        CURLOPT_RETURNTRANSFER => true
    ]);
    $res = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($res, true);

    if ($result && $result['status'] === 'success') {
        $check = $db->prepare("SELECT COUNT(*) FROM activated_students WHERE user_id=?");
        $check->execute([$uid]);

        if ($check->fetchColumn() == 0) {
            $db->prepare("INSERT INTO activated_students (user_id) VALUES (?)")->execute([$uid]);
            echo "<script>alert('Student activated successfully');</script>";
        } else {
            echo "<script>alert('Student already activated');</script>";
        }
    } else {
        echo "<script>alert('Invalid activation PIN');</script>";
    }
}

/* =====================
   SEARCH STUDENT
===================== */
$student = null;

if (!empty($_GET['search'])) {
    $s = '%' . $_GET['search'] . '%';
    $stmt = $db->prepare("SELECT * FROM students WHERE user_id LIKE ? OR name LIKE ? LIMIT 1");
    $stmt->execute([$s, $s]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
}

// 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 · Student Activation</title>
    <link rel="icon" href="caosce.ico" type="image/x-icon">
    <!-- 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: 750px;
            margin: 0 auto;
            background: #ffffff;
            padding: 35px 40px 40px;
            border-radius: 24px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.08);
            border: 1px solid #eef4fa;
        }

        /* ----- PAGE HEADER WITH GO BACK ----- */
        .page-header {
            text-align: center;
            margin-bottom: 28px;
            position: relative;
        }

        .page-header .go-back-btn {
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            background: #e9ecef;
            color: #4f6580;
            padding: 8px 18px;
            border-radius: 30px;
            text-decoration: none;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .page-header .go-back-btn:hover {
            background: #dde1e6;
            transform: translateY(-50%) scale(1.03);
        }

        .page-header .icon-large {
            font-size: 42px;
            display: block;
            margin-bottom: 6px;
        }

        .page-header h2 {
            font-size: 28px;
            font-weight: 700;
            color: #10233f;
            margin: 0;
        }

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

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

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

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

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

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

        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            box-shadow: 0 4px 14px rgba(40, 167, 69, 0.25);
        }

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

        .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-secondary {
            background: #e9ecef;
            color: #4f6580;
        }

        .btn-secondary:hover {
            background: #dde1e6;
        }

        /* ----- SEARCH BOX ----- */
        .search-box {
            margin-bottom: 25px;
        }

        .search-input-wrapper {
            display: flex;
            align-items: center;
            background: #ffffff;
            border-radius: 50px;
            padding: 4px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
            border: 2px solid #e9ecef;
            transition: 0.3s ease;
        }

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

        .search-icon {
            font-size: 18px;
            margin-left: 18px;
            color: #6b7a8f;
        }

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

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

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

        .search-input-wrapper button:hover {
            transform: scale(1.03);
            box-shadow: 0 4px 16px rgba(26, 108, 240, 0.3);
        }

        /* ----- STUDENT RESULT CARD ----- */
        .student-card {
            background: #f8fafc;
            border-radius: 18px;
            padding: 25px 30px;
            margin-top: 10px;
            border: 1px solid #eef4fa;
            text-align: center;
        }

        .student-card .user-id {
            font-size: 18px;
            font-weight: 600;
            color: #10233f;
        }

        .student-card .user-id span {
            color: #1a6cf0;
        }

        .student-card .user-name {
            font-size: 20px;
            font-weight: 700;
            color: #10233f;
            margin: 4px 0 12px 0;
        }

        .student-card img {
            width: 140px;
            height: 140px;
            border-radius: 16px;
            object-fit: cover;
            border: 3px solid #eef4fa;
            margin: 10px 0 16px 0;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
        }

        .status-activated {
            display: inline-block;
            padding: 6px 20px;
            border-radius: 30px;
            background: #d4edda;
            color: #155724;
            font-weight: 600;
            font-size: 15px;
        }

        .status-inactive {
            display: inline-block;
            padding: 6px 20px;
            border-radius: 30px;
            background: #fff3cd;
            color: #856404;
            font-weight: 600;
            font-size: 15px;
        }

        .action-buttons-group {
            display: flex;
            gap: 12px;
            justify-content: center;
            flex-wrap: wrap;
            margin-top: 16px;
        }

        .not-found {
            text-align: center;
            padding: 30px 20px;
            color: #6b7a8f;
        }

        .not-found 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: 400px;
            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);
                opacity: 0;
            }

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

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

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

        .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 .btn {
            width: 100%;
            justify-content: center;
            margin-top: 8px;
        }

        .modal-content .close-btn {
            background: transparent;
            border: none;
            font-size: 28px;
            color: #999;
            cursor: pointer;
            float: right;
            transition: 0.2s;
        }

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

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

            .container {
                padding: 25px 20px;
            }

            .page-header .go-back-btn {
                position: static;
                transform: none;
                margin-bottom: 12px;
                display: inline-flex;
            }
        }

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

            .page-header h2 {
                font-size: 22px;
            }

            .page-header .go-back-btn {
                font-size: 12px;
                padding: 6px 14px;
            }

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

            .search-input-wrapper {
                flex-direction: column;
                border-radius: 20px;
                padding: 12px;
                background: #f8fafc;
            }

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

            .search-input-wrapper button {
                width: 100%;
                border-radius: 30px;
                padding: 12px;
            }

            .search-icon {
                display: none;
            }

            .student-card {
                padding: 18px 16px;
            }

            .student-card img {
                width: 100px;
                height: 100px;
            }

            .action-buttons-group {
                flex-direction: column;
                align-items: stretch;
            }

            .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>
</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="insert_student_data.php" class="<?php echo $current_page == 'insert_student_data.php' ? 'active' : ''; ?>">
                <i class="fas fa-user-plus"></i> Students
            </a>
            <a href="result.php" class="<?php echo $current_page == 'result.php' ? 'active' : ''; ?>">
                <i class="fas fa-chart-pie"></i> Results
            </a>
            <a href="exam_manager.php" class="<?php echo $current_page == 'exam_manager.php' ? 'active' : ''; ?>">
                <i class="fas fa-sliders-h"></i> Exams
            </a>
            <a href="folderName.php" class="<?php echo $current_page == 'folderName.php' ? 'active' : ''; ?>">
                <i class="fas fa-folder"></i> Folder
            </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">

            <!-- Header with Go Back Button -->
            <div class="page-header">
                <a href="activatedstudents.php" class="go-back-btn">
                    <i class="fas fa-arrow-left"></i> Go Back
                </a>
                <span class="icon-large">🔓</span>
                <h2>Student Activation</h2>
                <div class="subtitle">Activate students one by one using a slot or PIN</div>
            </div>

            <!-- Slot Bar -->
            <div class="slot-bar">
                <div class="slot-info">
                    <i class="fas fa-ticket-alt"></i>
                    <span>Slots Left:</span>
                    <span class="slot-count"><?= $slot_count ?></span>
                </div>
                <button class="btn btn-success" onclick="openSlot()">
                    <i class="fas fa-plus-circle"></i> Add Slot
                </button>
            </div>

            <!-- Search -->
            <form method="GET" class="search-box">
                <div class="search-input-wrapper">
                    <span class="search-icon"><i class="fas fa-search"></i></span>
                    <input
                        type="text"
                        name="search"
                        placeholder="Search by User ID or Name..."
                        value="<?= htmlspecialchars($_GET['search'] ?? '') ?>"
                        required>
                    <button type="submit">
                        <i class="fas fa-search"></i> Search
                    </button>
                </div>
            </form>

            <!-- Results -->
            <?php if ($student): ?>
                <?php
                $chk = $db->prepare("SELECT COUNT(*) FROM activated_students WHERE user_id=?");
                $chk->execute([$student['user_id']]);
                $is_activated = $chk->fetchColumn() > 0;
                ?>
                <div class="student-card">
                    <div class="user-id">
                        <i class="fas fa-id-card" style="color:#1a6cf0;"></i>
                        <span><?= htmlspecialchars($student['user_id']) ?></span>
                    </div>
                    <div class="user-name"><?= htmlspecialchars($student['name']) ?></div>
                    <?php if ($student['picture']): ?>
                        <img src="data:image/jpeg;base64,<?= base64_encode($student['picture']) ?>" alt="Student Photo">
                    <?php endif; ?>

                    <?php if ($is_activated): ?>
                        <div class="status-activated">
                            <i class="fas fa-check-circle"></i> Activated
                        </div>
                    <?php else: ?>
                        <div class="status-inactive">
                            <i class="fas fa-clock"></i> Not Activated
                        </div>
                        <div class="action-buttons-group">
                            <button class="btn btn-primary" onclick="document.getElementById('method').style.display='flex'">
                                <i class="fas fa-user-check"></i> Activate Student
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            <?php elseif (isset($_GET['search']) && !empty($_GET['search'])): ?>
                <div class="not-found">
                    <i class="fas fa-user-slash"></i>
                    <p>No student found matching "<strong><?= htmlspecialchars($_GET['search']) ?></strong>"</p>
                    <p style="font-size:14px; color:#a0b0c4;">Please try a different Exam Number or Name.</p>
                </div>
            <?php endif; ?>

        </div>
    </main>

    <!-- ============================================================
         ADD SLOT MODAL
         ============================================================ -->
    <div id="slot" class="modal">
        <div class="modal-content">
            <button class="close-btn" onclick="closeSlot()">&times;</button>
            <h3><i class="fas fa-ticket-alt" style="color:#28a745;"></i> Add Slot</h3>
            <form method="POST">
                <input type="text" name="add_slot_code" placeholder="Enter slot code" required>
                <br><br>
                <button class="btn btn-success" type="submit">
                    <i class="fas fa-plus-circle"></i> Add Slot
                </button>
            </form>
        </div>
    </div>

    <!-- ============================================================
         ACTIVATION METHOD MODAL
         ============================================================ -->
    <div id="method" class="modal">
        <div class="modal-content">
            <button class="close-btn" onclick="closeMethod()">&times;</button>
            <h3><i class="fas fa-options" style="color:#1a6cf0;"></i> Activation Method</h3>

            <form method="POST">
                <input type="hidden" name="manual_activate_user_id" value="<?= $student['user_id'] ?? '' ?>">
                <button class="btn btn-primary" type="submit">
                    <i class="fas fa-ticket-alt"></i> Use Slot
                </button>
            </form>

            <hr class="divider">

            <form method="POST">
                <input type="hidden" name="activate_user_id" value="<?= $student['user_id'] ?? '' ?>">
                <input type="text" name="activation_pin" placeholder="Enter activation PIN" required>
                <br><br>
                <button class="btn btn-primary" type="submit">
                    <i class="fas fa-key"></i> Use PIN
                </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>

    <!-- ============================================================
         SCRIPTS
         ============================================================ -->
    <script>
        function openSlot() {
            document.getElementById('slot').style.display = 'flex';
        }

        function closeSlot() {
            document.getElementById('slot').style.display = 'none';
        }

        function closeMethod() {
            document.getElementById('method').style.display = 'none';
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
    </script>

</body>

</html>