<?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
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');
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"), true);

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'];
error_log("Processing OTP for exit: $otpCode");

// Begin transaction
$conn->begin_transaction();

try {
    // Check if the OTP exists in `visitor_records` and hasn't been exited yet
    $stmt = $conn->prepare("SELECT * FROM visitor_records WHERE otp_code = ? AND is_exited = 0");
    $stmt->bind_param("s", $otpCode);
    $stmt->execute();
    $result = $stmt->get_result();
    $visitorRecord = $result->fetch_assoc();

    if (!$visitorRecord) {
        error_log("Invalid OTP or visitor already exited: $otpCode");
        http_response_code(404);
        echo json_encode(["status" => "error", "message" => "Invalid OTP or visitor already exited."]);
        $conn->rollback(); // Rollback transaction
        exit();
    }

    // Insert record into `exited_visitors`
    $stmt = $conn->prepare("
        INSERT INTO exited_visitors (house_id, description, name, phone_number, image_metadata, id_plates, admitted_by, otp_code)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param(
        "isssssss",
        $visitorRecord['house_id'],
        $visitorRecord['description'],
        $visitorRecord['name'],
        $visitorRecord['phone_number'],
        $visitorRecord['image_metadata'],
        $visitorRecord['id_plates'],
        $visitorRecord['admitted_by'],
        $visitorRecord['otp_code']
    );

    if (!$stmt->execute()) {
        error_log("Failed to insert into exited_visitors: " . $stmt->error);
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Failed to process exit record."]);
        $conn->rollback(); // Rollback transaction
        exit();
    }

    // Mark the visitor record as exited
    $stmt = $conn->prepare("UPDATE visitor_records SET is_exited = 1 WHERE otp_code = ?");
    $stmt->bind_param("s", $otpCode);

    if (!$stmt->execute()) {
        error_log("Failed to mark visitor as exited: " . $stmt->error);
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Failed to update visitor record."]);
        $conn->rollback(); // Rollback transaction
        exit();
    }

    // Commit the transaction
    $conn->commit();
    error_log("Visitor exited successfully: $otpCode");

    http_response_code(200);
    echo json_encode(["status" => "success", "message" => "Visitor exited successfully."]);
} catch (Exception $e) {
    error_log("Exception occurred: " . $e->getMessage());
    $conn->rollback(); // Rollback transaction
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "An error occurred while processing the request."]);
} finally {
    $stmt->close();
    $conn->close();
}
?>
