<?php
session_start();
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'petugas'])) {
    header('Content-Type: application/json');
    http_response_code(403);
    echo json_encode(['status'=>'error','message'=>'Akses ditolak.']);
    exit;
}

include '../koneksi.php';
header('Content-Type: application/json');

$id         = (int)($_POST['id']         ?? 0);
$nama       = trim($_POST['nama']        ?? '');
$jenis      = trim($_POST['jenis']       ?? '');
$alamat     = trim($_POST['alamat']      ?? '');
$radius     = (int)($_POST['radius']     ?? 300);
$kontak     = trim($_POST['kontak']      ?? '');
$latitude   = trim($_POST['latitude']    ?? '');
$longitude  = trim($_POST['longitude']   ?? '');

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

try {
    $stmt = $pdo->prepare(
        "UPDATE fasilitas_publik SET nama=?, jenis=?, alamat=?, radius=?, kontak=?, latitude=?, longitude=? WHERE id=?"
    );
    $stmt->execute([$nama, $jenis, $alamat, $radius, $kontak, $latitude, $longitude, $id]);
    
    $stmtSelect = $pdo->prepare("SELECT * FROM fasilitas_publik WHERE id=?");
    $stmtSelect->execute([$id]);
    $data = $stmtSelect->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode(['status'=>'success','data'=>$data]);
} catch (PDOException $e) {
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>
