<?php
include_once 'config/koneksi.php';

$desa_id = $_GET['desa_id'] ?? '';

if (!$desa_id) {
    echo json_encode([]);
    exit;
}

$sql = "SELECT latitude, longitude FROM wilayahtugas WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $desa_id);
$stmt->execute();
$wil = $stmt->get_result()->fetch_assoc();
$stmt->close();

$lat = $wil['latitude'];
$lng = $wil['longitude'];

$sql = "
    SELECT 
        m.id,
        m.nama,
        (6371 * ACOS(
            COS(RADIANS(?)) * COS(RADIANS(m.latitude)) *
            COS(RADIANS(m.longitude) - RADIANS(?)) +
            SIN(RADIANS(?)) * SIN(RADIANS(m.latitude))
        )) AS jarak
    FROM mitra m
    ORDER BY jarak ASC
";

$stmt2 = $conn->prepare($sql);
$stmt2->bind_param("ddd", $lat, $lng, $lat);
$stmt2->execute();
$res = $stmt2->get_result();

$data = [];
while ($row = $res->fetch_assoc()) {
    $data[] = $row;
}

echo json_encode($data);
