<?php
require __DIR__ . '/config.php';

header('Content-Type: application/json');

$conn = getDbConnection();
$data = json_decode(file_get_contents("php://input"), true);

if (isset($data['org_id'], $data['site_name'], $data['latitude'], $data['longitude'], $data['site_address'])) {
    $org_id = intval($data['org_id']);
    $site_name = trim($data['site_name']);
    $latitude = doubleval($data['latitude']);
    $longitude = doubleval($data['longitude']);
    $site_address = trim($data['site_address']);

    // Check if site already exists
    $check_stmt = $conn->prepare("SELECT site_id FROM sites WHERE site_name = ?");
    $check_stmt->bind_param("s", $site_name);
    $check_stmt->execute();
    $check_stmt->store_result();

    if ($check_stmt->num_rows > 0) {
        echo json_encode(["success" => false, "message" => "Site name already exists."]);
        exit;
    }
    $check_stmt->close();

    // Insert new site
    $stmt = $conn->prepare("INSERT INTO sites (org_id, site_name, latitude, longitude, site_address, subscription_status) 
                            VALUES (?, ?, ?, ?, ?, 'Active')");
    $stmt->bind_param("isdds", $org_id, $site_name, $latitude, $longitude, $site_address);

    if ($stmt->execute()) {
        echo json_encode(["success" => true, "message" => "Site added successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => $stmt->error]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Invalid input"]);
}

$conn->close();
?>
