<?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'] ?? '';
$registrationNo = $data['registration_no'] ?? '';

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

try {
    // Mark the key as used
    $stmt = $DBH->prepare("
        UPDATE exam_access_codes 
        SET used_date = NOW(),
            is_used = 1
        WHERE access_code = :access_code 
        AND registration_no = :reg_no
        AND is_used = 0
    ");
    $stmt->execute([
        'access_code' => $accessCode,
        'reg_no' => $registrationNo
    ]);

    if ($stmt->rowCount() > 0) {
        echo json_encode(['success' => true, 'message' => 'Key marked as used']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Key not found or already used']);
    }

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