<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
error_log("Request Payload: " . file_get_contents('php://input'));

require_once 'config.php';

$conn = getDbConnection(); // Connect to the database

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



if (isset($data->house_id) && isset($data->description) && isset($data->name) && isset($data->phone_number) && isset($data->admitted_by) && isset($data->otp_code)) {
    $house_id = $data->house_id;
    $description = $data->description;
    $name = $data->name;
    $phone_number = $data->phone_number;
    $admitted_by = $data->admitted_by;
    $otp_code = $data->otp_code;
    $image_metadata = isset($data->image_metadata) ? $data->image_metadata : null;
    $id_plates = isset($data->id_plates) ? $data->id_plates : null;

    // Insert visitor record into the database
    $stmt = $conn->prepare("
        INSERT INTO visitor_records 
        (house_id, description, name, phone_number, image_metadata, id_plates, admitted_by, otp_code) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("isssssss", $house_id, $description, $name, $phone_number, $image_metadata, $id_plates, $admitted_by, $otp_code);

    if ($stmt->execute()) {
        // Fetch the alert numbers for the house
        $alert_stmt = $conn->prepare("SELECT alert_numbers FROM houses WHERE id = ?");
        $alert_stmt->bind_param("i", $house_id);
        $alert_stmt->execute();
        $alert_stmt->bind_result($alert_numbers);
        $alert_stmt->fetch();

        // Simulate sending an SMS with the OTP
        error_log("Sending SMS to $alert_numbers: Visitor $name, $description, Phone: $phone_number, Plates: $id_plates, OTP: $otp_code");

        echo json_encode(array(
            "status" => "success",
            "message" => "Visitor record saved and SMS sent",
            "image_metadata" => $image_metadata,
            "otp_code" => $otp_code
        ));
    } else {
        echo json_encode(array("status" => "error", "message" => "Failed to save visitor record"));
    }

    $stmt->close();
} else {
    echo json_encode(array("status" => "error", "message" => "Invalid input"));
}

$conn->close();
?>

