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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$data = json_decode(file_get_contents('php://input'), true);

$accessCode = $data['access_code'] ?? '';
$examSubjectId = $data['exam_subject_id'] ?? '';
$registrationNo = $data['registration_no'] ?? '';
$subject = $data['subject'] ?? '';
$assessmentType = $data['assessment_type'] ?? '';

if (empty($accessCode) || empty($examSubjectId) || empty($registrationNo)) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

try {
    // Check if access key exists and is valid
    $stmt = $DBH->prepare("
        SELECT * FROM exam_access_codes 
        WHERE access_code = :access_code 
        AND is_used = 0
    ");
    $stmt->execute(['access_code' => $accessCode]);
    $accessKey = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$accessKey) {
        echo json_encode(['success' => false, 'message' => 'Invalid or already used access key']);
        exit();
    }

    // Check if key has expired
    $currentTime = time();
    $startTime = strtotime($accessKey['start_time']);
    $endTime = strtotime($accessKey['end_time']);

    if ($currentTime < $startTime) {
        echo json_encode(['success' => false, 'message' => 'This access key is not yet active']);
        exit();
    }

    if ($currentTime > $endTime) {
        echo json_encode(['success' => false, 'message' => 'This access key has expired']);
        exit();
    }

    // Check if key is already assigned to a different student
    if (!empty($accessKey['registration_no']) && $accessKey['registration_no'] !== $registrationNo) {
        echo json_encode(['success' => false, 'message' => 'This access key has already been used by another student']);
        exit();
    }

    // If key is not assigned to anyone yet, assign it to this student
    if (empty($accessKey['registration_no'])) {
        $stmt = $DBH->prepare("
            UPDATE exam_access_codes 
            SET registration_no = :reg_no
            WHERE id = :id
        ");
        $stmt->execute([
            'reg_no' => $registrationNo,
            'id' => $accessKey['id']
        ]);
    }

    // Store verified key in session
    $_SESSION['verified_access_key'] = [
        'code' => $accessCode,
        'exam_subject_id' => $examSubjectId,
        'subject' => $subject,
        'assessment_type' => $assessmentType,
        'verified_at' => time()
    ];

    echo json_encode(['success' => true, 'message' => 'Access key verified successfully']);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>