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

if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'petugas'])) {
    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;
$alamat = $_POST['alamat'] ?? 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 !== '') {
        if ($alamat !== null) {
            $stmt = $pdo->prepare("UPDATE penduduk_miskin SET latitude = ?, longitude = ?, status_jangkauan = ?, fasilitas_publik_id = ?, alamat = ? WHERE id = ?");
            $stmt->execute([$latitude, $longitude, $status_jangkauan, $fasilitas_publik_id, $alamat, $id]);
        } else {
            $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 {
        if ($alamat !== null) {
            $stmt = $pdo->prepare("UPDATE penduduk_miskin SET latitude = ?, longitude = ?, alamat = ? WHERE id = ?");
            $stmt->execute([$latitude, $longitude, $alamat, $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()]);
}
