<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Authorization, Content-Type");

// Enable error logging for debugging
ini_set('log_errors', 1);
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config.php';

$conn = getDbConnection();

if (!$conn) {
    error_log("Database connection failed: " . mysqli_connect_error());
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database connection failed"]);
    exit();
}

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Invalid request method. Only POST is allowed."]);
    exit();
}

// Parse incoming data
$data = json_decode(file_get_contents("php://input"));

if (!isset($data->otp_code) || empty($data->otp_code)) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "OTP code is missing."]);
    exit();
}

$otpCode = $data->otp_code;

// Check OTP in visitor_records
$stmt = $conn->prepare("SELECT id FROM visitor_records WHERE otp_code = ? AND is_exited = 0");
$stmt->bind_param("s", $otpCode);
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_assoc();

if ($record) {
    // Valid OTP and visitor has not exited
    http_response_code(200);
    echo json_encode(["isValid" => true, "message" => "OTP validated successfully."]);
} else {
    // Check OTP in exited_visitors
    $stmt = $conn->prepare("SELECT id FROM exited_visitors WHERE otp_code = ?");
    $stmt->bind_param("s", $otpCode);
    $stmt->execute();
    $result = $stmt->get_result();
    $exitedRecord = $result->fetch_assoc();

    if ($exitedRecord) {
        // Visitor has already exited
        http_response_code(200);
        echo json_encode(["isValid" => false, "message" => "Visitor has already exited."]);
    } else {
        // OTP not found
        http_response_code(200);
        echo json_encode(["isValid" => false, "message" => "Invalid OTP."]);
    }
}
$stmt->close();
$conn->close();
?>

