<?php
require_once('source/dbconfig.php');
require_once('source/function.php');
session_start();
date_default_timezone_set('Africa/Lagos');

if (isset($_SESSION['student'])) {
    header("Location: welcome.php");
    exit();
}

$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $registration_no = trim($_POST['registration_no']);
    $class = trim($_POST['class']);
    $term = trim($_POST['term']);
    $session_input = trim($_POST['session']);
    $pin = trim($_POST['pin']);

    try {
        $DBH->beginTransaction();

        // Verify student exists
        $stmt = $DBH->prepare("SELECT * FROM tbl_user WHERE registration_no = ? AND teacher = 'false' AND status = 'Active'");
        $stmt->execute([$registration_no]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$student) throw new Exception("Invalid admission number or inactive account.");

        // Lock and fetch PIN
        $stmt = $DBH->prepare("SELECT * FROM tbl_pin WHERE pin = ? FOR UPDATE");
        $stmt->execute([$pin]);
        $pinRecord = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$pinRecord) throw new Exception("PIN not found.");

        $now = date('Y-m-d H:i:s');

        if (!empty($pinRecord['reg_no'])) {
            if ($pinRecord['reg_no'] !== $registration_no) {
                throw new Exception("This PIN has already been used by another student.");
            }

            if ($pinRecord['year'] !== $session_input) {
                throw new Exception("This PIN was used in a different session: " . $pinRecord['year']);
            }

            // Allow login, increment used_count and log
            $DBH->prepare("UPDATE tbl_pin SET used_count = used_count + 1, updated_at = ? WHERE pin = ?")
                ->execute([$now, $pin]);

        } else {
            // First time use — assign
            $DBH->prepare("
                UPDATE tbl_pin SET
                    reg_no = ?,
                    class = ?,
                    term = ?,
                    year = ?,
                    date_time = ?,
                    dt_stamp_start = ?,
                    created_date_time = ?,
                    updated_at = ?,
                    used_count = 1
                WHERE pin = ?
            ")->execute([
                $registration_no,
                $class,
                $term,
                $session_input,
                $now,
                $now,
                $now,
                $now,
                $pin
            ]);
        }

        // Log to pin_logins table
        $DBH->prepare("
            INSERT INTO pin_logins (pin, reg_no, class, term, year, login_time)
            VALUES (?, ?, ?, ?, ?, ?)
        ")->execute([$pin, $registration_no, $class, $term, $session_input, $now]);

        // Store session
        $_SESSION['student'] = $student;
        $_SESSION['exam_info'] = [
            'class' => $class,
            'term' => $term,
            'session' => $session_input,
            'pin' => $pin
        ];

        $DBH->commit();
        header("Location: welcome.php");
        exit();

    } catch (Exception $e) {
        $DBH->rollBack();
        $error = $e->getMessage();
    }
}
?>

<!-- HTML Section -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>BKMS-BLC CBT Portal - Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #e8f5e9; font-family: 'Segoe UI', sans-serif; }
        .login-container {
            max-width: 600px; margin: 5% auto; padding: 30px;
            background: white; border-radius: 10px; box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .school-logo { max-width: 150px; display: block; margin: 0 auto 20px; }
        .school-header { color: #2e7d32; text-align: center; margin-bottom: 30px; }
        .form-label { font-weight: 600; color: #2e7d32; }
        .btn-login { background-color: #2e7d32; border: none; font-weight: 600; }
        .form-control, .form-select {
            border: 1px solid #2e7d32;
        }
        .form-control:focus, .form-select:focus {
            border-color: #2e7d32;
            box-shadow: 0 0 0 0.25rem rgba(46, 125, 50, 0.25);
        }
    </style>
</head>
<body>
<div class="container">
    <div class="login-container">
        <img src="assets/images/bkms.png" alt="BKMS Logo" class="school-logo">
        <h2 class="school-header">BKMS-BLC CBT Portal</h2>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="mb-3">
                <label for="registration_no" class="form-label">Admission Number</label>
                <input type="text" name="registration_no" id="registration_no" class="form-control" required>
            </div>

            <div class="mb-3">
                <label for="class" class="form-label">Class</label>
                <select name="class" id="class" class="form-select" required>
                    <option value="">Select Class</option>
                    <?php
                    $classes = $DBH->query("SELECT DISTINCT class FROM tbl_class ORDER BY class");
                    while ($class = $classes->fetch(PDO::FETCH_ASSOC)) {
                        echo "<option value='" . htmlspecialchars($class['class']) . "'>" . htmlspecialchars($class['class']) . "</option>";
                    }
                    ?>
                </select>
            </div>

            <div class="mb-3">
                <label for="term" class="form-label">Term</label>
                <select name="term" id="term" class="form-select" required>
                    <option value="">Select Term</option>
                    <option value="1st Term">1st Term</option>
                    <option value="2nd Term">2nd Term</option>
                    <option value="3rd Term">3rd Term</option>
                </select>
            </div>

            <div class="mb-3">
                <label for="session" class="form-label">Session (Academic Year)</label>
                <select name="session" id="session" class="form-select" required>
                    <option value="">Select Session</option>
                    <?php
                    $sessions = $DBH->query("SELECT DISTINCT session FROM tbl_session ORDER BY session DESC");
                    while ($session = $sessions->fetch(PDO::FETCH_ASSOC)) {
                        echo "<option value='" . htmlspecialchars($session['session']) . "'>" . htmlspecialchars($session['session']) . "</option>";
                    }
                    ?>
                </select>
            </div>

            <div class="mb-3">
                <label for="pin" class="form-label">PIN</label>
                <input type="password" name="pin" id="pin" class="form-control" required>
            </div>

            <button type="submit" class="btn btn-success btn-login w-100">LOGIN</button>
        </form>
    </div>
</div>
</body>
</html>
