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

require_once 'config.php'; // Include the database configuration

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

// Retrieve the data from the POST request
$data = json_decode(file_get_contents("php://input"));

if (isset($data->house_number) && isset($data->alert_numbers)) {
    $house_number = $data->house_number;
    $alert_numbers = $data->alert_numbers;

    // Check if the house already exists
    $stmt = $conn->prepare("SELECT id FROM houses WHERE house_number = ?");
    $stmt->bind_param("s", $house_number);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        // House exists, update it
        $stmt = $conn->prepare("UPDATE houses SET alert_numbers = ?, updated_at = NOW() WHERE house_number = ?");
        $stmt->bind_param("ss", $alert_numbers, $house_number);

        if ($stmt->execute()) {
            echo json_encode(array("status" => "success", "message" => "House updated successfully"));
        } else {
            echo json_encode(array("status" => "error", "message" => "Failed to update house"));
        }
    } else {
        // House does not exist, insert it
        $stmt = $conn->prepare("INSERT INTO houses (house_number, alert_numbers, created_at, updated_at) VALUES (?, ?, NOW(), NOW())");
        $stmt->bind_param("ss", $house_number, $alert_numbers);

        if ($stmt->execute()) {
            echo json_encode(array("status" => "success", "message" => "House registered successfully"));
        } else {
            echo json_encode(array("status" => "error", "message" => "Failed to register house"));
        }
    }

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

$conn->close();
?>

