<?php
header("Access-Control-Allow-Origin: *");
// Izinkan metode POST, GET, OPTIONS
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
// Izinkan header tertentu
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

// Jika ini adalah request OPTIONS (preflight), kirim OK dan keluar
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}
// 1. Koneksi Database (SESUAIKAN DENGAN USERNAME/PASSWORD ANDA)
$host = "localhost";
$user = "mitra432_root";      // Default XAMPP: root
$pass = "20061996Lk#";          // Default XAMPP: kosong
$db   = "mitra432_bulfood";

try {
    $conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Koneksi gagal"]);
    exit();
}

// 2. Terima Input Koordinat User
$user_lat = isset($_GET['lat']) ? $_GET['lat'] : null;
$user_lng = isset($_GET['lng']) ? $_GET['lng'] : null;

if (!$user_lat || !$user_lng) {
    // Jika tidak ada koordinat, kirim data kosong atau error
    echo json_encode([]);
    exit();
}

// 3. QUERY SAKTI: IMPLEMENTASI HAVERSINE (dalam KM)
// Rumus ini menghitung jarak dan langsung mengurutkan dari yang terdekat.
// Angka 6371 adalah jari-jari bumi dalam Kilometer.

$sql = "SELECT id, name, cuisine, rating, image_url, latitude, longitude,
        ( 6371 * acos( 
            cos( radians(:user_lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(:user_lng) ) + 
            sin( radians(:user_lat) ) * sin( radians( latitude ) ) 
          ) 
        ) AS distance_km
        FROM restaurants
        WHERE is_active = 1
        HAVING distance_km < 10  -- Filter hanya radius 10 KM (Opsional)
        ORDER BY distance_km ASC -- Urutkan dari yang terdekat
        LIMIT 20"; // Batasi tampilkan 20 resto saja

try {
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':user_lat', $user_lat);
    $stmt->bindParam(':user_lng', $user_lng);
    $stmt->execute();
    $restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Format jarak agar cantik (misal: "1.2 km")
    foreach ($restaurants as &$resto) {
        $resto['distance'] = number_format($resto['distance_km'], 1) . ' km';
        // Hapus data mentah agar respon lebih ringan
        unset($resto['distance_km']);
        unset($resto['latitude']);
        unset($resto['longitude']);
    }

    echo json_encode($restaurants);

} catch(PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => $e->getMessage()]);
}
?>