<?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(200); exit; }

require_once '../includes/config.php';
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'geojson';

// ── GET ───────────────────────────────────────────────────
if ($method === 'GET') {
    if ($action === 'geojson') {
        $where = "WHERE 1=1";
        if (!empty($_SESSION['role']) && $_SESSION['role'] === 'pengurus_ibadah') {
            $iid = (int)($_SESSION['id_rumah_ibadah'] ?? 0);
            $where .= " AND ri.id=$iid";
        }
        if (isset($_GET['id_ibadah']) && $_GET['id_ibadah']) {
            $where .= " AND ri.id=".(int)$_GET['id_ibadah'];
        }
        $res = $conn->query("SELECT ri.*,
            (SELECT COUNT(*) FROM penduduk p WHERE p.id_rumah_ibadah=ri.id) AS jumlah_kk,
            (SELECT COUNT(*) FROM bantuan b WHERE b.id_rumah_ibadah=ri.id) AS jumlah_bantuan,
            (SELECT COUNT(*) FROM laporan_status ls WHERE ls.id_rumah_ibadah=ri.id AND ls.status_verifikasi='pending') AS laporan_pending
            FROM rumah_ibadah ri $where ORDER BY ri.id");
        $features = [];
        while ($row = $res->fetch_assoc()) {
            $features[] = [
                'type'       => 'Feature',
                'geometry'   => ['type'=>'Point','coordinates'=>[(float)$row['longitude'],(float)$row['latitude']]],
                'properties' => $row
            ];
        }
        jsonResponse(['type'=>'FeatureCollection','features'=>$features]);

    } elseif ($action === 'list') {
        $res = $conn->query("SELECT id, nama, jenis, kelurahan, kecamatan FROM rumah_ibadah ORDER BY nama");
        $data = [];
        while ($r = $res->fetch_assoc()) $data[] = $r;
        jsonResponse($data);

    } elseif ($action === 'get' && isset($_GET['id'])) {
        $id = (int)$_GET['id'];
        $r  = $conn->query("SELECT * FROM rumah_ibadah WHERE id=$id")->fetch_assoc();
        jsonResponse($r ?: ['error'=>'Tidak ditemukan']);

    } elseif ($action === 'pengurus' && isset($_GET['id'])) {
        // Daftar pengurus rumah ibadah tertentu
        $id  = (int)$_GET['id'];
        $res = $conn->query("SELECT id,nama_lengkap,email,no_hp FROM users WHERE id_rumah_ibadah=$id AND role='pengurus_ibadah'");
        $data = [];
        while ($r = $res->fetch_assoc()) $data[] = $r;
        jsonResponse($data);
    }
}

// ── POST ──────────────────────────────────────────────────
if ($method === 'POST') {
    requireLogin(['admin','pengurus_ibadah']);
    $d      = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $nama   = esc($conn,$d['nama']??'');
    $jenis  = esc($conn,$d['jenis']??'Masjid');
    $kontak = esc($conn,$d['kontak']??'');
    $email  = esc($conn,$d['email']??'');
    $lat    = (float)($d['latitude']??0);
    $lon    = (float)($d['longitude']??0);
    $alamat = esc($conn,$d['alamat']??'');
    $kel    = esc($conn,$d['kelurahan']??'');
    $kec    = esc($conn,$d['kecamatan']??'');
    $radius = (int)($d['radius']??300);

    $sql = "INSERT INTO rumah_ibadah (nama,jenis,kontak,email,latitude,longitude,alamat,kelurahan,kecamatan,radius)
            VALUES ('$nama','$jenis','$kontak','$email',$lat,$lon,'$alamat','$kel','$kec',$radius)";
    if ($conn->query($sql)) {
        $id = $conn->insert_id;
        logAktivitas($conn,'tambah_rumah_ibadah','rumah_ibadah',$id,"Tambah: $nama");
        jsonResponse(['success'=>true,'id'=>$id,'message'=>'Rumah ibadah berhasil ditambahkan']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}

// ── PUT ───────────────────────────────────────────────────
if ($method === 'PUT') {
    requireLogin(['admin','pengurus_ibadah']);
    $d      = json_decode(file_get_contents('php://input'), true);
    $id     = (int)$d['id'];
    $nama   = esc($conn,$d['nama']??'');
    $jenis  = esc($conn,$d['jenis']??'');
    $kontak = esc($conn,$d['kontak']??'');
    $email  = esc($conn,$d['email']??'');
    $lat    = (float)($d['latitude']??0);
    $lon    = (float)($d['longitude']??0);
    $alamat = esc($conn,$d['alamat']??'');
    $kel    = esc($conn,$d['kelurahan']??'');
    $kec    = esc($conn,$d['kecamatan']??'');
    $radius = (int)($d['radius']??300);

    // Jika pengurus_ibadah, pastikan hanya boleh mengubah rumah ibadah miliknya
    if (!empty($_SESSION['role']) && $_SESSION['role'] === 'pengurus_ibadah') {
        $myIbadah = (int)($_SESSION['id_rumah_ibadah'] ?? 0);
        if ($myIbadah !== $id) {
            jsonResponse(['success'=>false,'error'=>'Tidak diizinkan mengubah rumah ibadah lain.'], 403);
        }
    }

    $sql = "UPDATE rumah_ibadah SET nama='$nama',jenis='$jenis',kontak='$kontak',email='$email',
            latitude=$lat,longitude=$lon,alamat='$alamat',kelurahan='$kel',kecamatan='$kec',radius=$radius
            WHERE id=$id";
    if ($conn->query($sql)) {
        logAktivitas($conn,'edit_rumah_ibadah','rumah_ibadah',$id,"Edit: $nama");
        jsonResponse(['success'=>true,'message'=>'Data diperbarui']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}

// ── DELETE ────────────────────────────────────────────────
if ($method === 'DELETE') {
    requireLogin(['admin']);
    $id = (int)($_GET['id']??0);
    if ($conn->query("DELETE FROM rumah_ibadah WHERE id=$id")) {
        logAktivitas($conn,'hapus_rumah_ibadah','rumah_ibadah',$id,'');
        jsonResponse(['success'=>true,'message'=>'Data dihapus']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}
?>
