<?php
ob_start();
session_start();
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    ob_end_clean();
    echo json_encode(["status" => "error", "pesan" => "Akses ditolak. Silakan login."]);
    exit;
}

include 'koneksi.php';

$aksi      = $_GET['aksi'] ?? '';
$user_id   = (int)($_SESSION['user_id'] ?? 0);
$user_role = $_SESSION['role'] ?? 'warga';

// ─── 1. SIMPAN LAPORAN (warga) ───────────────────────────────────────────────
if ($aksi === 'simpan') {
    $tipe      = in_array($_POST['tipe_laporan'] ?? '', ['diri_sendiri','orang_lain']) ? $_POST['tipe_laporan'] : 'orang_lain';
    $nama      = trim($_POST['nama_kk']        ?? '');
    $jml       = max(1, (int)($_POST['jumlah_anggota'] ?? 1));
    $alamat    = trim($_POST['alamat']          ?? '');
    $lat       = (float)($_POST['lat']          ?? 0);
    $lng       = (float)($_POST['lng']          ?? 0);
    $pekerjaan = trim($_POST['pekerjaan']       ?? '');
    $ket       = trim($_POST['keterangan']      ?? '');

    $fakir   = (int)(($_POST['is_fakir_miskin']   ?? 0) == '1');
    $dhuafa  = (int)(($_POST['is_dhuafa']          ?? 0) == '1');
    $lansia  = (int)(($_POST['is_lansia_tunggal']  ?? 0) == '1');
    $yatim   = (int)(($_POST['is_anak_yatim']      ?? 0) == '1');
    $bencana = (int)(($_POST['is_korban_bencana']  ?? 0) == '1');
    $disab   = (int)(($_POST['is_disabilitas']     ?? 0) == '1');

    if (empty($nama) || empty($alamat) || $lat == 0 || $lng == 0) {
        ob_end_clean();
        echo json_encode(["status" => "error", "pesan" => "Nama, alamat, dan titik lokasi di peta wajib diisi."]);
        exit;
    }

    $stmt = $pdo->prepare("
        INSERT INTO laporan_warga
            (pelapor_id, tipe_laporan, nama_kk, jumlah_anggota, alamat, lat, lng,
             pekerjaan, keterangan,
             is_fakir_miskin, is_dhuafa, is_lansia_tunggal, is_anak_yatim, is_korban_bencana, is_disabilitas)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    ");
    $stmt->execute([
        $user_id, $tipe, $nama, $jml, $alamat, $lat, $lng,
        $pekerjaan, $ket,
        $fakir, $dhuafa, $lansia, $yatim, $bencana, $disab
    ]);
    $id = $pdo->lastInsertId();
    ob_end_clean();
    echo json_encode(["status" => "sukses", "id" => $id, "pesan" => "Laporan #$id berhasil dikirim. Menunggu verifikasi admin."]);
    exit;
}

// ─── 2. TAMPIL SEMUA LAPORAN (admin/walikota) ────────────────────────────────
if ($aksi === 'tampil') {
    if (!in_array($user_role, ['admin', 'walikota'])) {
        ob_end_clean();
        echo json_encode(["status" => "error", "pesan" => "Akses ditolak."]);
        exit;
    }
    $stmt = $pdo->query("
        SELECT l.*, u.username AS nama_pelapor
        FROM laporan_warga l
        LEFT JOIN users u ON l.pelapor_id = u.id
        ORDER BY l.created_at DESC
    ");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ob_end_clean();
    echo json_encode($rows);
    exit;
}

// ─── 3. CEK STATUS LAPORAN MILIK SENDIRI (warga) ────────────────────────────
if ($aksi === 'cek_status') {
    $stmt = $pdo->prepare("
        SELECT id, tipe_laporan, nama_kk, alamat, status, catatan_admin, created_at
        FROM laporan_warga
        WHERE pelapor_id = ?
        ORDER BY created_at DESC
    ");
    $stmt->execute([$user_id]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ob_end_clean();
    echo json_encode($rows);
    exit;
}

// ─── 4. VERIFIKASI → masuk ke warga_miskin (admin) ──────────────────────────
if ($aksi === 'verifikasi') {
    if ($user_role !== 'admin') {
        ob_end_clean();
        echo json_encode(["status" => "error", "pesan" => "Hanya admin yang dapat memverifikasi."]);
        exit;
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0) {
        ob_end_clean();
        echo json_encode(["status" => "error", "pesan" => "ID laporan tidak valid."]);
        exit;
    }

    // Ambil data laporan
    $stmt = $pdo->prepare("SELECT * FROM laporan_warga WHERE id = ?");
    $stmt->execute([$id]);
    $lap = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$lap) {
        ob_end_clean();
        echo json_encode(["status" => "error", "pesan" => "Laporan tidak ditemukan."]);
        exit;
    }
    if ($lap['status'] === 'diverifikasi') {
        ob_end_clean();
        echo json_encode(["status" => "error", "pesan" => "Laporan sudah pernah diverifikasi."]);
        exit;
    }

    // Insert ke warga_miskin
    $ins = $pdo->prepare("
        INSERT INTO warga_miskin
            (nama_kk, jumlah_anggota, alamat, lat, lng, pekerjaan,
             is_fakir_miskin, is_dhuafa, is_lansia_tunggal, is_anak_yatim, is_korban_bencana, is_disabilitas,
             diinput_oleh_id)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
    ");
    $ins->execute([
        $lap['nama_kk'], $lap['jumlah_anggota'], $lap['alamat'],
        $lap['lat'], $lap['lng'], $lap['pekerjaan'],
        $lap['is_fakir_miskin'], $lap['is_dhuafa'], $lap['is_lansia_tunggal'],
        $lap['is_anak_yatim'], $lap['is_korban_bencana'], $lap['is_disabilitas'],
        $lap['pelapor_id']
    ]);
    $warga_id = $pdo->lastInsertId();

    // Update status laporan
    $upd = $pdo->prepare("UPDATE laporan_warga SET status='diverifikasi', warga_id=? WHERE id=?");
    $upd->execute([$warga_id, $id]);

    ob_end_clean();
    echo json_encode(["status" => "sukses", "warga_id" => $warga_id, "pesan" => "Laporan diverifikasi. Data warga masuk ke peta."]);
    exit;
}

// ─── 5. TOLAK LAPORAN (admin) ────────────────────────────────────────────────
if ($aksi === 'tolak') {
    if ($user_role !== 'admin') {
        ob_end_clean();
        echo json_encode(["status" => "error", "pesan" => "Hanya admin yang dapat menolak laporan."]);
        exit;
    }
    $id     = (int)($_POST['id'] ?? 0);
    $catatan = trim($_POST['catatan_admin'] ?? '');
    if ($id <= 0) {
        ob_end_clean();
        echo json_encode(["status" => "error", "pesan" => "ID tidak valid."]);
        exit;
    }
    $stmt = $pdo->prepare("UPDATE laporan_warga SET status='ditolak', catatan_admin=? WHERE id=?");
    $stmt->execute([$catatan, $id]);
    ob_end_clean();
    echo json_encode(["status" => "sukses", "pesan" => "Laporan ditolak."]);
    exit;
}

// ─── 6. HITUNG LAPORAN MENUNGGU (admin, untuk badge) ────────────────────────
if ($aksi === 'hitung_menunggu') {
    if (!in_array($user_role, ['admin', 'walikota'])) {
        ob_end_clean();
        echo json_encode(["jumlah" => 0]);
        exit;
    }
    $stmt = $pdo->query("SELECT COUNT(*) FROM laporan_warga WHERE status='menunggu'");
    $n = (int)$stmt->fetchColumn();
    ob_end_clean();
    echo json_encode(["jumlah" => $n]);
    exit;
}

ob_end_clean();
echo json_encode(["status" => "error", "pesan" => "Aksi tidak dikenal: $aksi"]);
