<?php
require_once('source/dbconfig.php');
require_once('source/function.php');
session_start();
date_default_timezone_set('Africa/Lagos');

// Check if access code is already verified
$accessCodeVerified = isset($_SESSION['access_code_verified']) && $_SESSION['access_code_verified'] === true;

if (isset($_SESSION['student'])) {
    header("Location: welcome.php");
    exit();
}

// Handle access code verification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['access_code'])) {
    $accessCode = trim($_POST['access_code']);
    $currentTime = date('Y-m-d H:i:s');
    
    try {
        $DBH->beginTransaction();
        
        // Check if code exists and is valid
        $stmt = $DBH->prepare("
            SELECT * FROM exam_access_codes 
            WHERE access_code = ? 
            AND start_time <= ? 
            AND end_time >= ?
            FOR UPDATE
        ");
        $stmt->execute([$accessCode, $currentTime, $currentTime]);
        $codeRecord = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$codeRecord) {
            throw new Exception("Invalid access code or outside valid time window.");
        }
        
        if ($codeRecord['is_used']) {
            throw new Exception("This access code has already been used.");
        }
        
        // Mark code as used
        $stmt = $DBH->prepare("
            UPDATE exam_access_codes 
            SET is_used = TRUE, 
                used_date = ?,
                registration_no = ?
            WHERE access_code = ?
        ");
        $stmt->execute([$currentTime, $_POST['registration_no'] ?? null, $accessCode]);
        
        $_SESSION['access_code_verified'] = true; 
        $_SESSION['access_code'] = $accessCode;
        $_SESSION['access_code_expiry'] = $codeRecord['end_time'];
        
        $DBH->commit();
        header("Location: cbt_index.php");
        exit();
    } catch (Exception $e) {
        $DBH->rollBack();
        $accessCodeError = $e->getMessage();
    }
}

// Original login handling
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['registration_no'])) {
    // [Keep all your existing login code here]
    // ...
    
    // Additional check for access code validity
    if ($accessCodeVerified) {
        $currentTime = date('Y-m-d H:i:s');
        if ($currentTime > $_SESSION['access_code_expiry']) {
            $error = "The access code has expired. Please obtain a new code.";
            unset($_SESSION['access_code_verified']);
        }
    } else {
        $error = "Access code verification required.";
    }
    
    // [Rest of your existing login code]
}
?>

<!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>
        /* [Keep all your existing styles] */
        .access-code-info {
            background-color: #e8f5e9;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
            text-align: center;
            border-left: 4px solid #2e7d32;
        }
    </style> 
</head>
<body>

<!-- Access Code Modal -->
<div class="modal fade" id="accessCodeModal" tabindex="-1" aria-labelledby="accessCodeModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="accessCodeModalLabel">Exam Access Required</h5>
            </div>
            <div class="modal-body">
                <?php if (isset($accessCodeError)): ?>
                    <div class="alert alert-danger"><?php echo htmlspecialchars($accessCodeError); ?></div>
                <?php endif; ?>
                <div class="text-center mb-4">
                    <img src="assets/images/bkms.png" alt="BKMS Logo" style="max-width: 100px;">
                    <h4 class="mt-2 text-success">Enter Exam Access Code</h4>
                    <p class="text-muted">Code valid for 8 hours from activation time</p>
                </div>
                <form method="POST" id="accessCodeForm">
                    <div class="mb-3">
                        <label for="access_code" class="form-label">Exam Access Code</label>
                        <input type="password" class="form-control" id="access_code" name="access_code" required>
                    </div>
                    <div class="mb-3">
                        <label for="pre_registration_no" class="form-label">Admission Number</label>
                        <input type="text" class="form-control" id="pre_registration_no" name="registration_no" required>
                    </div>
                    <button type="submit" class="btn btn-success w-100">Continue to Exam</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Main Login Container (only shown if access code is verified) -->
<?php if ($accessCodeVerified): ?>
<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>
        
        <div class="access-code-info">
            <strong>Access Code:</strong> <?php echo htmlspecialchars($_SESSION['access_code']); ?> | 
            <strong>Valid Until:</strong> <?php echo date('h:i A, M j, Y', strtotime($_SESSION['access_code_expiry'])); ?>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <form method="POST">
            <!-- [Keep all your existing form fields] -->
        </form>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Show modal if access code not verified
    <?php if (!$accessCodeVerified): ?>
    document.addEventListener('DOMContentLoaded', function() {
        var accessCodeModal = new bootstrap.Modal(document.getElementById('accessCodeModal'));
        accessCodeModal.show();
        
        // Prevent closing modal by clicking backdrop or pressing escape
        document.getElementById('accessCodeModal').addEventListener('hide.bs.modal', function (e) {
            return false;
        });
    });
    <?php endif; ?>
    
    // Focus on access code input when modal shown
    document.getElementById('accessCodeModal').addEventListener('shown.bs.modal', function () {
        document.getElementById('access_code').focus();
    });
    
    // Auto-format admission number to uppercase
    document.getElementById('pre_registration_no').addEventListener('input', function(e) {
        this.value = this.value.toUpperCase();
    });
</script>
</body>
</html>