<?php
session_start();
include '../koneksi.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$id = $_POST['id'] ?? '';
$latitude = $_POST['latitude'] ?? '';
$longitude = $_POST['longitude'] ?? '';
$status_jangkauan = $_POST['status_jangkauan'] ?? '';
$fasilitas_publik_id = $_POST['fasilitas_publik_id'] ?? null;

if (!$id || !$latitude || !$longitude) {
    echo json_encode(['status' => 'error', 'message' => 'Data tidak lengkap']);
    exit;
}

if ($fasilitas_publik_id === '') {
    $fasilitas_publik_id = null;
}

try {
    if ($status_jangkauan !== '') {
        $stmt = $pdo->prepare("UPDATE penduduk_miskin SET latitude = ?, longitude = ?, status_jangkauan = ?, fasilitas_publik_id = ? WHERE id = ?");
        $stmt->execute([$latitude, $longitude, $status_jangkauan, $fasilitas_publik_id, $id]);
    } else {
        $stmt = $pdo->prepare("UPDATE penduduk_miskin SET latitude = ?, longitude = ? WHERE id = ?");
        $stmt->execute([$latitude, $longitude, $id]);
    }
    
    echo json_encode(['status' => 'success']);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}
