<?php
require 'db_config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $data = json_decode(file_get_contents("php://input"), true);

    if (isset($data['site_id'], $data['checkpoints'])) {
        $site_id = $data['site_id'];
        $checkpoints = $data['checkpoints'];
        $position = 1;

        foreach ($checkpoints as $checkpoint) {
            $tag_id = $checkpoint['id'];
            $stmt = $conn->prepare("INSERT INTO patrol_routes (site_id, tag_id, order_position) VALUES (?, ?, ?)");
            $stmt->bind_param("iii", $site_id, $tag_id, $position);
            $stmt->execute();
            $position++;
        }

        echo json_encode(["success" => true, "message" => "Patrol route added"]);
    } else {
        echo json_encode(["success" => false, "message" => "Invalid input"]);
    }
}
$conn->close();
?>

