<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type");

require_once 'config.php'; // Include DB connection config

$conn = getDbConnection();

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

// Ensure DB connection closes at the end
register_shutdown_function(function() use ($conn) {
    if ($conn) {
        $conn->close();
    }
});

// Query only unexited visitors
$query = "
    SELECT vr.id, vr.house_id, h.house_number, vr.description, vr.name, 
           vr.phone_number, vr.image_metadata, vr.id_plates, vr.admitted_by, 
           vr.created_at, vr.otp_code, vr.is_exited 
    FROM visitor_records vr
    LEFT JOIN houses h ON vr.house_id = h.id
    WHERE vr.is_exited = 0
    ORDER BY vr.created_at DESC
";

$result = $conn->query($query);

if (!$result) {
    echo json_encode(["status" => "error", "message" => "Query failed"]);
    exit();
}

$visitors = [];

while ($row = $result->fetch_assoc()) {
    $visitors[] = $row;
}

$result->free();

echo json_encode([
    "status" => "success",
    "visitor_records" => $visitors
]);
exit();
?>
