<?php
require 'config.php'; // Database connection setup

header("Content-Type: application/json");
$data = json_decode(file_get_contents("php://input"), true);

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["success" => false, "message" => "Invalid request method"]);
    exit;
}

// Validate incoming data
if (!isset($data['siteId'], $data['checkpoints']) || !is_array($data['checkpoints'])) {
    http_response_code(400);
    echo json_encode(["success" => false, "message" => "Invalid payload"]);
    exit;
}

$siteId = intval($data['siteId']);
$checkpoints = $data['checkpoints'];

// Establish database connection
$conn = getDbConnection();
if (!$conn) {
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Database connection failed"]);
    exit;
}

// Start a transaction to ensure data consistency
$conn->begin_transaction();

try {
    // Create a new route_id for this patrol route
    $routeQuery = "INSERT INTO patrol_routes (site_id) VALUES (?)";
    $routeStmt = $conn->prepare($routeQuery);
    $routeStmt->bind_param("i", $siteId);

    if (!$routeStmt->execute()) {
        throw new Exception("Failed to create patrol route");
    }

    $routeId = $routeStmt->insert_id; // Get the ID of the new route
    $routeStmt->close();

    // Insert checkpoints into the database
    $insertQuery = "INSERT INTO patrol_route_checkpoints (route_id, checkpoint_name, latitude, longitude, created_at) 
                    VALUES (?, ?, ?, ?, NOW())";
    $insertStmt = $conn->prepare($insertQuery);

    foreach ($checkpoints as $checkpoint) {
        if (!isset($checkpoint['checkpoint_name'], $checkpoint['latitude'], $checkpoint['longitude'])) {
            throw new Exception("Invalid checkpoint data");
        }

        $name = $checkpoint['checkpoint_name'];
        $lat = floatval($checkpoint['latitude']);
        $lng = floatval($checkpoint['longitude']);

        $insertStmt->bind_param("issd", $routeId, $name, $lat, $lng);

        if (!$insertStmt->execute()) {
            throw new Exception("Failed to save checkpoint: $name");
        }
    }

    $insertStmt->close();

    // Commit the transaction
    $conn->commit();

    // Success response
    http_response_code(200);
    echo json_encode(["success" => true, "message" => "Patrol route saved successfully"]);
} catch (Exception $e) {
    // Rollback the transaction on failure
    $conn->rollback();
    http_response_code(500);
    echo json_encode(["success" => false, "message" => $e->getMessage()]);
} finally {
    $conn->close();
}
?>

