<?php
// api/rumah_ibadah.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require_once '../config/db.php';

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    // ── GET ──────────────────────────────────────────────────────────────────
    case 'GET':
        if (isset($_GET['id'])) {
            $id     = (int)$_GET['id'];
            $result = $conn->query("SELECT * FROM rumah_ibadah WHERE id = $id");
            if ($row = $result->fetch_assoc()) {
                echo json_encode(['success' => true, 'data' => $row]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Data tidak ditemukan']);
            }
        } else {
            // Filter opsional
            $where = [];
            if (!empty($_GET['jenis']))     $where[] = "jenis = '" . $conn->real_escape_string($_GET['jenis']) . "'";
            if (!empty($_GET['kecamatan'])) $where[] = "kecamatan LIKE '%" . $conn->real_escape_string($_GET['kecamatan']) . "%'";
            if (!empty($_GET['search']))    $where[] = "(nama LIKE '%" . $conn->real_escape_string($_GET['search']) . "%' OR alamat LIKE '%" . $conn->real_escape_string($_GET['search']) . "%')";

            $sql    = "SELECT * FROM rumah_ibadah" . ($where ? " WHERE " . implode(' AND ', $where) : "") . " ORDER BY nama ASC";
            $result = $conn->query($sql);
            if ($result === false) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Gagal mengambil data dari tabel "rumah_ibadah": ' . $conn->error . '. Pastikan Anda telah mengimpor berkas database "database/bansos_gis.sql" di phpMyAdmin Anda!'
                ]);
                break;
            }
            $data   = [];
            while ($row = $result->fetch_assoc()) $data[] = $row;
            echo json_encode(['success' => true, 'data' => $data, 'total' => count($data)]);
        }
        break;

    // ── POST ─────────────────────────────────────────────────────────────────
    case 'POST':
        $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;

        $nama      = $conn->real_escape_string(trim($input['nama'] ?? ''));
        $jenis     = $conn->real_escape_string($input['jenis'] ?? 'masjid');
        $alamat    = $conn->real_escape_string($input['alamat'] ?? '');
        $kelurahan = $conn->real_escape_string($input['kelurahan'] ?? '');
        $kecamatan = $conn->real_escape_string($input['kecamatan'] ?? '');
        $kota      = $conn->real_escape_string($input['kota'] ?? '');
        $lat       = (float)($input['latitude'] ?? 0);
        $lng       = (float)($input['longitude'] ?? 0);
        $pj        = $conn->real_escape_string($input['penanggung_jawab'] ?? '');
        $kontak    = $conn->real_escape_string($input['kontak'] ?? '');
        $ket       = $conn->real_escape_string($input['keterangan'] ?? '');

        $kap       = (int)($input['kapasitas_kk'] ?? 20);
        $rad       = (int)($input['radius_primer'] ?? 500);
        $anggaran  = (float)($input['anggaran_bulanan'] ?? 0);

        if (!$nama || !$lat || !$lng) {
            echo json_encode(['success' => false, 'message' => 'Nama, latitude, dan longitude wajib diisi']);
            break;
        }

        $sql = "INSERT INTO rumah_ibadah (nama,jenis,alamat,kelurahan,kecamatan,kota,latitude,longitude,penanggung_jawab,kontak,keterangan,kapasitas_kk,radius_primer,anggaran_bulanan)
                VALUES ('$nama','$jenis','$alamat','$kelurahan','$kecamatan','$kota',$lat,$lng,'$pj','$kontak','$ket',$kap,$rad,$anggaran)";

        if ($conn->query($sql)) {
            echo json_encode(['success' => true, 'message' => 'Data berhasil disimpan', 'id' => $conn->insert_id]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal menyimpan: ' . $conn->error]);
        }
        break;

    // ── PUT ──────────────────────────────────────────────────────────────────
    case 'PUT':
        $input = json_decode(file_get_contents('php://input'), true);
        $id        = (int)($input['id'] ?? 0);
        $nama      = $conn->real_escape_string(trim($input['nama'] ?? ''));
        $jenis     = $conn->real_escape_string($input['jenis'] ?? 'masjid');
        $alamat    = $conn->real_escape_string($input['alamat'] ?? '');
        $kelurahan = $conn->real_escape_string($input['kelurahan'] ?? '');
        $kecamatan = $conn->real_escape_string($input['kecamatan'] ?? '');
        $kota      = $conn->real_escape_string($input['kota'] ?? '');
        $lat       = (float)($input['latitude'] ?? 0);
        $lng       = (float)($input['longitude'] ?? 0);
        $pj        = $conn->real_escape_string($input['penanggung_jawab'] ?? '');
        $kontak    = $conn->real_escape_string($input['kontak'] ?? '');
        $ket       = $conn->real_escape_string($input['keterangan'] ?? '');

        $kap       = (int)($input['kapasitas_kk'] ?? 20);
        $rad       = (int)($input['radius_primer'] ?? 500);
        $anggaran  = (float)($input['anggaran_bulanan'] ?? 0);

        if (!$id) { echo json_encode(['success' => false, 'message' => 'ID tidak valid']); break; }

        $sql = "UPDATE rumah_ibadah SET
                  nama='$nama', jenis='$jenis', alamat='$alamat',
                  kelurahan='$kelurahan', kecamatan='$kecamatan', kota='$kota',
                  latitude=$lat, longitude=$lng,
                  penanggung_jawab='$pj', kontak='$kontak', keterangan='$ket',
                  kapasitas_kk=$kap, radius_primer=$rad, anggaran_bulanan=$anggaran
                WHERE id=$id";

        if ($conn->query($sql)) {
            echo json_encode(['success' => true, 'message' => 'Data berhasil diperbarui']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal memperbarui: ' . $conn->error]);
        }
        break;

    // ── DELETE ───────────────────────────────────────────────────────────────
    case 'DELETE':
        $id = (int)($_GET['id'] ?? 0);
        if (!$id) {
            $input = json_decode(file_get_contents('php://input'), true);
            $id    = (int)($input['id'] ?? 0);
        }
        if ($conn->query("DELETE FROM rumah_ibadah WHERE id=$id")) {
            echo json_encode(['success' => true, 'message' => 'Data berhasil dihapus']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal menghapus: ' . $conn->error]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}
$conn->close();