<?php
// includes/pin_validator.php

function validatePin($pdo, $pin_code, $student_id) {
    // Check if PIN exists and is unused
    $stmt = $pdo->prepare("SELECT * FROM pins WHERE pin_code = ?");
    $stmt->execute([$pin_code]);
    $pin = $stmt->fetch();

    if (!$pin) {
        return "Invalid PIN. Please check the code and try again.";
    }

    if ($pin['status'] == 'used' && $pin['student_id'] != $student_id) {
        return "This PIN has already been used by another student.";
    }

    // If unused, mark as used by this student
    if ($pin['status'] == 'unused') {
        $update = $pdo->prepare("UPDATE pins SET status = 'used', student_id = ?, used_date = NOW() WHERE pin_code = ?");
        $update->execute([$student_id, $pin_code]);
    }

    return true; // Success
}
?>