<?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;
}

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

$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 (!$nama || !$jenis || !$latitude || !$longitude) {
    echo json_encode(['status'=>'error','message'=>'Nama, Jenis, Latitude, dan Longitude wajib diisi.']);
    exit;
}

if (!is_numeric($latitude) || !is_numeric($longitude) || !is_numeric($radius)) {
    echo json_encode(['status'=>'error','message'=>'Koordinat dan radius harus berupa angka.']);
    exit;
}

try {
    $stmt = $pdo->prepare(
        "INSERT INTO fasilitas_publik (nama, jenis, alamat, radius, kontak, latitude, longitude)
         VALUES (?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->execute([$nama, $jenis, $alamat, $radius, $kontak, $latitude, $longitude]);
    $id = $pdo->lastInsertId();

    $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'=>'Gagal menyimpan: '.$e->getMessage()]);
}
?>
