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

require_once '../includes/config.php';
startSession();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'list';

// ── GET ───────────────────────────────────────────────────
if ($method === 'GET') {
    if ($action === 'list') {
        $where = "WHERE 1=1";

        // Filter wilayah untuk pengurus ibadah
        if (!empty($_SESSION['role']) && $_SESSION['role'] === 'pengurus_ibadah') {
            $iid = (int)$_SESSION['id_rumah_ibadah'];
            $where .= " AND ls.id_rumah_ibadah=$iid";
        }
        if (isset($_GET['status']) && $_GET['status'])
            $where .= " AND ls.status_verifikasi='".esc($conn,$_GET['status'])."'";
        if (isset($_GET['jenis']) && $_GET['jenis'])
            $where .= " AND ls.jenis_laporan='".esc($conn,$_GET['jenis'])."'";

        $res = $conn->query("SELECT ls.*,
            p.nama_kepala_keluarga, p.alamat AS alamat_kk, p.kelurahan, p.kecamatan,
            u.nama_lengkap AS nama_pelapor, u.no_hp AS hp_pelapor,
            ri.nama AS nama_ibadah,
            up.nama_lengkap AS nama_pengurus
            FROM laporan_status ls
            LEFT JOIN penduduk p      ON ls.id_penduduk=p.id
            LEFT JOIN users u         ON ls.id_pelapor_user=u.id
            LEFT JOIN rumah_ibadah ri ON ls.id_rumah_ibadah=ri.id
            LEFT JOIN users up        ON ls.id_pengurus_verif=up.id
            $where ORDER BY ls.created_at DESC LIMIT 200");
        $data = [];
        while ($r = $res->fetch_assoc()) $data[] = $r;
        jsonResponse($data);

    } elseif ($action === 'get' && isset($_GET['id'])) {
        $id  = (int)$_GET['id'];
        $row = $conn->query("SELECT ls.*,
            p.nama_kepala_keluarga,p.alamat AS alamat_kk,
            u.nama_lengkap AS nama_pelapor,
            ri.nama AS nama_ibadah
            FROM laporan_status ls
            LEFT JOIN penduduk p      ON ls.id_penduduk=p.id
            LEFT JOIN users u         ON ls.id_pelapor_user=u.id
            LEFT JOIN rumah_ibadah ri ON ls.id_rumah_ibadah=ri.id
            WHERE ls.id=$id")->fetch_assoc();
        jsonResponse($row ?: ['error'=>'Tidak ditemukan']);
    }
}

// ── POST: buat laporan baru (dari masyarakat) ─────────────
if ($method === 'POST' && $action === 'kirim') {
    startSession();
    $d           = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $id_penduduk = (int)($d['id_penduduk']??0) ?: 'NULL';
    $id_anggota  = (int)($d['id_anggota']??0) ?: 'NULL';
    $jenis       = esc($conn,$d['jenis_laporan']??'lainnya');
    $deskripsi   = esc($conn,$d['deskripsi']??'');
    $nama        = esc($conn,$d['nama_terkait']??'');
    $tgl         = esc($conn,$d['tanggal_kejadian']??date('Y-m-d'));
    $uid         = isset($_SESSION['user_id'])?(int)$_SESSION['user_id']:'NULL';

    if (!$deskripsi) jsonResponse(['success'=>false,'error'=>'Deskripsi wajib diisi'],400);

    // Auto-assign rumah ibadah berdasarkan lokasi KK
    $id_ibadah = 'NULL';
    if ($id_penduduk !== 'NULL') {
        $kk = $conn->query("SELECT latitude,longitude FROM penduduk WHERE id=$id_penduduk")->fetch_assoc();
        if ($kk) {
            $matches = findIbadahInRadius($conn,(float)$kk['latitude'],(float)$kk['longitude']);
            if ($matches && $matches[0]) $id_ibadah = (int)$matches[0]['id'];
        }
    }

    $foto = uploadFile('lampiran','laporan');
    $foto_e = $foto ? esc($conn,$foto) : '';

    $sql = "INSERT INTO laporan_status
            (id_penduduk,id_anggota,id_pelapor_user,jenis_laporan,deskripsi,nama_terkait,
             tanggal_kejadian,lampiran_foto,id_rumah_ibadah)
            VALUES ($id_penduduk,$id_anggota,$uid,'$jenis','$deskripsi','$nama','$tgl','$foto_e',$id_ibadah)";
    if ($conn->query($sql)) {
        $lid = $conn->insert_id;

        // Notifikasi ke pengurus rumah ibadah
        if ($id_ibadah !== 'NULL') {
            $pengurus = $conn->query("SELECT id FROM users WHERE id_rumah_ibadah=$id_ibadah AND role='pengurus_ibadah'");
            while ($p = $pengurus->fetch_assoc()) {
                kirimNotifikasi($conn,(int)$p['id'],
                    "Laporan Baru: ".ucfirst(str_replace('_',' ',$d['jenis_laporan'])),
                    "Ada laporan baru masuk mengenai: $deskripsi",
                    'laporan_masuk',$lid);
            }
        }

        logAktivitas($conn,'kirim_laporan','laporan_status',$lid,"Jenis: $jenis");
        jsonResponse(['success'=>true,'id'=>$lid,'message'=>'Laporan berhasil dikirim. Terima kasih!']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}

// ── PUT: verifikasi laporan (oleh pengurus) ───────────────
if ($method === 'PUT' && $action === 'verifikasi') {
    requireLogin(['admin','pengurus_ibadah']);
    $d      = json_decode(file_get_contents('php://input'), true);
    $id     = (int)$d['id'];
    $status = esc($conn,$d['status_verifikasi']??'diproses');
    $catatan= esc($conn,$d['catatan_pengurus']??'');
    $uid    = (int)$_SESSION['user_id'];

    $sql = "UPDATE laporan_status SET status_verifikasi='$status',
            catatan_pengurus='$catatan',id_pengurus_verif=$uid,diverifikasi_at=NOW()
            WHERE id=$id";

    if ($conn->query($sql)) {
        // Jika disetujui → update status anggota keluarga
        if ($status === 'disetujui') {
            $lap = $conn->query("SELECT * FROM laporan_status WHERE id=$id")->fetch_assoc();
            if ($lap['id_anggota'] && in_array($lap['jenis_laporan'],['kematian','pindah_keluar'])) {
                $new_status = $lap['jenis_laporan']==='kematian'?'meninggal':'pindah';
                $aid = (int)$lap['id_anggota'];
                $conn->query("UPDATE anggota_keluarga SET status_hidup='$new_status' WHERE id=$aid");
            }
            // Notif ke pelapor
            if ($lap['id_pelapor_user']) {
                kirimNotifikasi($conn,(int)$lap['id_pelapor_user'],
                    'Laporan Disetujui','Laporan Anda telah diverifikasi dan disetujui oleh pengurus.','verifikasi',$id);
            }
        }

        logAktivitas($conn,'verifikasi_laporan','laporan_status',$id,"Status: $status");
        jsonResponse(['success'=>true,'message'=>'Status laporan diperbarui']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}
?>
