<?php
// api/bantuan.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';
startSession();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'list';

// ── GET ───────────────────────────────────────────────────
if ($method === 'GET') {
    if ($action === 'list') {
        $where = "WHERE 1=1";
        if (isset($_GET['id_penduduk']) && $_GET['id_penduduk'])
            $where .= " AND b.id_penduduk=".(int)$_GET['id_penduduk'];
        if (!empty($_SESSION['role']) && $_SESSION['role']==='pengurus_ibadah') {
            $iid = (int)$_SESSION['id_rumah_ibadah'];
            $where .= " AND b.id_rumah_ibadah=$iid";
        }
        if (isset($_GET['id_ibadah']) && $_GET['id_ibadah'])
            $where .= " AND b.id_rumah_ibadah=".(int)$_GET['id_ibadah'];

        $res = $conn->query("SELECT b.*,
            p.nama_kepala_keluarga,p.alamat,p.kelurahan,p.kecamatan,
            kb.nama AS jenis_bantuan, kb.sumber AS sumber_bantuan,
            ri.nama AS nama_ibadah, rim.nama AS nama_mitra,
            u.nama_lengkap AS dicatat_oleh
            FROM bantuan b
            JOIN penduduk p             ON b.id_penduduk=p.id
            JOIN kategori_bantuan kb    ON b.id_kategori_bantuan=kb.id
            LEFT JOIN rumah_ibadah ri   ON b.id_rumah_ibadah=ri.id
            LEFT JOIN rumah_ibadah rim  ON b.id_rumah_ibadah_mitra=rim.id
            LEFT JOIN users u           ON b.id_pengurus_input=u.id
            $where ORDER BY b.tanggal_bantuan DESC LIMIT 500");
        $data = [];
        while ($r = $res->fetch_assoc()) $data[] = $r;
        jsonResponse($data);

    } elseif ($action === 'kategori') {
        $res = $conn->query("SELECT * FROM kategori_bantuan ORDER BY sumber,nama");
        $data = [];
        while ($r = $res->fetch_assoc()) $data[] = $r;
        jsonResponse($data);

    } elseif ($action === 'statistik') {
        $where = "WHERE status_bantuan='disalurkan'";
        if (!empty($_SESSION['role']) && $_SESSION['role'] === 'pengurus_ibadah') {
            $iid = (int)($_SESSION['id_rumah_ibadah'] ?? 0);
            $where .= " AND id_rumah_ibadah=$iid";
        }
        if (isset($_GET['id_ibadah']) && $_GET['id_ibadah']) {
            $where .= " AND id_rumah_ibadah=".(int)$_GET['id_ibadah'];
        }

        $total     = $conn->query("SELECT COUNT(*) c, COALESCE(SUM(jumlah_nominal),0) nom FROM bantuan $where")->fetch_assoc();
        $per_jenis = [];
        $res       = $conn->query("SELECT kb.nama,kb.sumber,COUNT(*) jumlah,COALESCE(SUM(b.jumlah_nominal),0) nominal
                                   FROM bantuan b JOIN kategori_bantuan kb ON b.id_kategori_bantuan=kb.id
                                   $where GROUP BY kb.id ORDER BY jumlah DESC");
        while ($r = $res->fetch_assoc()) $per_jenis[] = $r;

        $per_ibadah = [];
        $res2 = $conn->query("SELECT ri.nama,COUNT(b.id) jumlah FROM bantuan b
                              JOIN rumah_ibadah ri ON b.id_rumah_ibadah=ri.id
                              $where GROUP BY ri.id ORDER BY jumlah DESC");
        while ($r = $res2->fetch_assoc()) $per_ibadah[] = $r;

        jsonResponse([
            'total_bantuan'  => (int)$total['c'],
            'total_nominal'  => (float)$total['nom'],
            'per_jenis'      => $per_jenis,
            'per_ibadah'     => $per_ibadah,
        ]);
    }
}

// ── POST: tambah bantuan ──────────────────────────────────
if ($method === 'POST') {
    requireLogin(['admin','pengurus_ibadah']);
    $d            = json_decode(file_get_contents('php://input'), true) ?: $_POST;
    $id_penduduk  = (int)($d['id_penduduk']??0);
    $id_kategori  = (int)($d['id_kategori_bantuan']??0);
    $id_ibadah    = (int)($d['id_rumah_ibadah']??$_SESSION['id_rumah_ibadah']??0) ?: 'NULL';
    $id_mitra     = (int)($d['id_rumah_ibadah_mitra']??0) ?: 'NULL';
    $donatur      = esc($conn,$d['nama_donatur']??'');
    $tgl          = esc($conn,$d['tanggal_bantuan']??date('Y-m-d'));
    $nominal      = (float)($d['jumlah_nominal']??0) ?: 'NULL';
    $bentuk       = esc($conn,$d['bentuk_bantuan']??'');
    $kondisi      = esc($conn,$d['kondisi_saat_diberikan']??'');
    $catatan      = esc($conn,$d['catatan_tambahan']??'');
    $uid          = (int)$_SESSION['user_id'];
    $status       = esc($conn,$d['status_bantuan']??'disalurkan');

    $foto = uploadFile('foto_dokumentasi','bantuan');
    $foto_e = $foto ? esc($conn,$foto) : '';

    $sql = "INSERT INTO bantuan
            (id_penduduk,id_kategori_bantuan,id_rumah_ibadah,id_rumah_ibadah_mitra,nama_donatur,
             tanggal_bantuan,jumlah_nominal,bentuk_bantuan,kondisi_saat_diberikan,catatan_tambahan,
             foto_dokumentasi,status_bantuan,id_pengurus_input)
            VALUES ($id_penduduk,$id_kategori,$id_ibadah,$id_mitra,'$donatur','$tgl',$nominal,
            '$bentuk','$kondisi','$catatan','$foto_e','$status',$uid)";

    if ($conn->query($sql)) {
        $bid = $conn->insert_id;

        // Notif ke user masyarakat yang terdaftar pada KK ini
        $user_kk = $conn->query("SELECT id FROM users WHERE id_penduduk=$id_penduduk AND role='masyarakat'")->fetch_assoc();
        if ($user_kk) {
            kirimNotifikasi($conn,(int)$user_kk['id'],
                'Bantuan Baru Diterima',
                "Keluarga Anda menerima bantuan: $bentuk pada ".date('d/m/Y',strtotime($tgl)),
                'bantuan_baru',$bid);
        }

        logAktivitas($conn,'tambah_bantuan','bantuan',$bid,"KK ID:$id_penduduk - $bentuk");
        jsonResponse(['success'=>true,'id'=>$bid,'message'=>'Bantuan berhasil dicatat']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}

// ── PUT: update bantuan ───────────────────────────────────
if ($method === 'PUT') {
    requireLogin(['admin','pengurus_ibadah']);
    $d       = json_decode(file_get_contents('php://input'), true);
    $id      = (int)$d['id'];
    $bentuk  = esc($conn,$d['bentuk_bantuan']??'');
    $catatan = esc($conn,$d['catatan_tambahan']??'');
    $status  = esc($conn,$d['status_bantuan']??'disalurkan');
    $mitra   = (int)($d['id_rumah_ibadah_mitra']??0) ?: 'NULL';

    $sql = "UPDATE bantuan SET bentuk_bantuan='$bentuk',catatan_tambahan='$catatan',
            status_bantuan='$status',id_rumah_ibadah_mitra=$mitra WHERE id=$id";
    if ($conn->query($sql)) {
        logAktivitas($conn,'edit_bantuan','bantuan',$id,'');
        jsonResponse(['success'=>true,'message'=>'Bantuan diperbarui']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}

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