<?php
// app/controllers/RumahIbadahController.php

class RumahIbadahController extends Controller {

    private array $ri;

    public function __construct() {
        parent::__construct();
        Auth::require('rumah_ibadah');
        $user = Auth::user();
        if (!$user['rumah_ibadah_id']) {
            // Belum terhubung ke rumah ibadah
            die('<div style="padding:40px;font-family:sans-serif;"><h2>Akun belum terhubung ke Rumah Ibadah</h2><p>Hubungi Super Admin untuk menautkan akun Anda.</p></div>');
        }
        $this->ri = $this->db->fetchOne(
            "SELECT ri.*, ji.nama as jenis, k.nama as kelurahan, kec.nama as kecamatan
             FROM rumah_ibadah ri
             JOIN jenis_rumah_ibadah ji ON ri.id_jenis = ji.id
             JOIN kelurahan k ON ri.id_kelurahan = k.id
             JOIN kecamatan kec ON k.id_kecamatan = kec.id
             WHERE ri.id = ?",
            [$user['rumah_ibadah_id']]
        );
    }

    public function dashboard(): void {
        $riId = $this->ri['id'];

        $stats = $this->db->fetchOne("
            SELECT
                (SELECT COUNT(*) FROM warga_miskin WHERE id_rumah_ibadah=? AND status='aktif') as total_warga,
                (SELECT COUNT(*) FROM warga_miskin WHERE id_rumah_ibadah=? AND level_prioritas='Tinggi' AND status='aktif') as prioritas_tinggi,
                (SELECT COUNT(*) FROM warga_miskin WHERE id_rumah_ibadah=? AND level_prioritas='Sedang' AND status='aktif') as prioritas_sedang,
                (SELECT COUNT(*) FROM histori_bantuan WHERE id_rumah_ibadah=? AND status='disalurkan') as total_bantuan,
                (SELECT COUNT(*) FROM histori_bantuan WHERE id_rumah_ibadah=? AND status='disalurkan' AND MONTH(tanggal_penyaluran)=MONTH(CURDATE())) as bantuan_bulan_ini,
                (SELECT COUNT(*) FROM warga_miskin WHERE id_rumah_ibadah=? AND status_kemiskinan='Miskin Ekstrem' AND status='aktif') as ekstrem
        ", array_fill(0, 6, $riId));

        $wargaList = $this->db->fetchAll("
            SELECT w.id, w.nama, w.status_kemiskinan, w.level_prioritas, w.skor_prioritas,
                   w.penghasilan_bulanan, w.jumlah_tanggungan, w.lat, w.lng,
                   w.is_lansia, w.is_disabilitas, k.nama as kelurahan
            FROM warga_miskin w
            JOIN kelurahan k ON w.id_kelurahan = k.id
            WHERE w.id_rumah_ibadah = ? AND w.status = 'aktif'
            ORDER BY w.skor_prioritas DESC
            LIMIT 20
        ", [$riId]);

        $bantuanTerakhir = $this->db->fetchAll("
            SELECT hb.*, kb.nama as kategori, wm.nama as warga
            FROM histori_bantuan hb
            JOIN kategori_bantuan kb ON hb.id_kategori_bantuan = kb.id
            JOIN warga_miskin wm ON hb.id_warga = wm.id
            WHERE hb.id_rumah_ibadah = ?
            ORDER BY hb.tanggal_penyaluran DESC LIMIT 10
        ", [$riId]);

        $this->view('rumah_ibadah.dashboard', [
            'title'          => 'Dashboard Rumah Ibadah',
            'ri'             => $this->ri,
            'stats'          => $stats,
            'wargaList'      => $wargaList,
            'bantuanTerakhir'=> $bantuanTerakhir,
            'user'           => Auth::user()
        ], 'rumah_ibadah');
    }

    public function warga(): void {
        $riId  = $this->ri['id'];
        $level = $_GET['level'] ?? 'semua';
        $sql   = "SELECT w.*, k.nama as kelurahan FROM warga_miskin w
                  JOIN kelurahan k ON w.id_kelurahan = k.id
                  WHERE w.id_rumah_ibadah = ? AND w.status = 'aktif'";
        $params = [$riId];
        if ($level !== 'semua') {
            $sql .= " AND w.level_prioritas = ?";
            $params[] = $level;
        }
        $sql .= " ORDER BY w.skor_prioritas DESC";

        $data = $this->db->fetchAll($sql, $params);
        $this->view('rumah_ibadah.warga', [
            'title'  => 'Daftar Warga Binaan',
            'data'   => $data,
            'ri'     => $this->ri,
            'level'  => $level,
            'user'   => Auth::user()
        ], 'rumah_ibadah');
    }

    public function detailWarga(int $id): void {
        $warga = $this->db->fetchOne("
            SELECT w.*, k.nama as kelurahan, kec.nama as kecamatan
            FROM warga_miskin w
            JOIN kelurahan k ON w.id_kelurahan = k.id
            JOIN kecamatan kec ON k.id_kecamatan = kec.id
            WHERE w.id = ? AND w.id_rumah_ibadah = ?
        ", [$id, $this->ri['id']]);

        if (!$warga) {
            $this->flash('error', 'Warga tidak ditemukan dalam binaan Anda.');
            $this->redirect(APP_URL . '/rumah-ibadah/warga');
        }

        $bantuan = $this->db->fetchAll("
            SELECT hb.*, kb.nama as kategori
            FROM histori_bantuan hb
            JOIN kategori_bantuan kb ON hb.id_kategori_bantuan = kb.id
            WHERE hb.id_warga = ?
            ORDER BY hb.tanggal_penyaluran DESC
        ", [$id]);

        $this->view('rumah_ibadah.detail_warga', [
            'title'   => 'Detail Warga',
            'warga'   => $warga,
            'ri'      => $this->ri,
            'bantuan' => $bantuan,
            'user'    => Auth::user()
        ], 'rumah_ibadah');
    }

    public function prioritas(): void {
        $data = $this->db->fetchAll("
            SELECT w.*, k.nama as kelurahan,
                   (SELECT COUNT(*) FROM histori_bantuan WHERE id_warga=w.id AND status='disalurkan') as jml_bantuan,
                   (SELECT MAX(tanggal_penyaluran) FROM histori_bantuan WHERE id_warga=w.id AND status='disalurkan') as bantuan_terakhir
            FROM warga_miskin w
            JOIN kelurahan k ON w.id_kelurahan = k.id
            WHERE w.id_rumah_ibadah = ? AND w.status = 'aktif'
            ORDER BY w.skor_prioritas DESC, w.status_kemiskinan
        ", [$this->ri['id']]);

        $this->view('rumah_ibadah.prioritas', [
            'title' => 'Prioritas Bantuan',
            'data'  => $data,
            'ri'    => $this->ri,
            'user'  => Auth::user()
        ], 'rumah_ibadah');
    }

    public function bantuan(): void {
        $data = $this->db->fetchAll("
            SELECT hb.*, kb.nama as kategori, wm.nama as warga
            FROM histori_bantuan hb
            JOIN kategori_bantuan kb ON hb.id_kategori_bantuan = kb.id
            JOIN warga_miskin wm ON hb.id_warga = wm.id
            WHERE hb.id_rumah_ibadah = ?
            ORDER BY hb.tanggal_penyaluran DESC
        ", [$this->ri['id']]);

        $this->view('rumah_ibadah.bantuan', [
            'title' => 'Histori Bantuan',
            'data'  => $data,
            'ri'    => $this->ri,
            'user'  => Auth::user()
        ], 'rumah_ibadah');
    }

    public function formBantuan(): void {
        $wargaList = $this->db->fetchAll("
            SELECT id, nama, status_kemiskinan, level_prioritas, skor_prioritas
            FROM warga_miskin WHERE id_rumah_ibadah = ? AND status = 'aktif'
            ORDER BY skor_prioritas DESC
        ", [$this->ri['id']]);

        $kategori = $this->db->fetchAll("SELECT * FROM kategori_bantuan WHERE is_active = 1 ORDER BY nama");

        $this->view('rumah_ibadah.form_bantuan', [
            'title'     => 'Tambah Bantuan',
            'wargaList' => $wargaList,
            'kategori'  => $kategori,
            'ri'        => $this->ri,
            'user'      => Auth::user()
        ], 'rumah_ibadah');
    }

    public function storeBantuan(): void {
        if (!$this->verifyCsrf()) $this->redirect(APP_URL . '/rumah-ibadah/bantuan');

        // Pastikan warga memang binaan rumah ibadah ini
        $idWarga = (int)$_POST['id_warga'];
        $warga = $this->db->fetchOne("SELECT id FROM warga_miskin WHERE id = ? AND id_rumah_ibadah = ?", [$idWarga, $this->ri['id']]);
        if (!$warga) {
            $this->flash('error', 'Warga tidak valid.');
            $this->redirect(APP_URL . '/rumah-ibadah/bantuan/tambah');
        }

        $foto = null;
        if (!empty($_FILES['foto_bukti']['name'])) {
            $foto = $this->uploadFile($_FILES['foto_bukti'], 'bantuan');
        }

        $this->db->insert('histori_bantuan', [
            'id_warga'            => $idWarga,
            'id_rumah_ibadah'     => $this->ri['id'],
            'id_kategori_bantuan' => (int)$_POST['id_kategori_bantuan'],
            'id_user_pengurus'    => Auth::id(),
            'kode_bantuan'        => generateKodeBantuan(),
            'tanggal_penyaluran'  => $_POST['tanggal_penyaluran'],
            'jumlah'              => (float)($_POST['jumlah'] ?? 0),
            'satuan'              => trim($_POST['satuan'] ?? ''),
            'deskripsi'           => trim($_POST['deskripsi'] ?? ''),
            'foto_bukti'          => $foto,
            'status'              => 'disalurkan'
        ]);

        Auth::logActivity(Auth::id(), Auth::user()['nama'], 'rumah_ibadah', 'Salurkan Bantuan', 'bantuan', "Bantuan untuk warga ID $idWarga");
        $this->flash('success', 'Bantuan berhasil dicatat.');
        $this->redirect(APP_URL . '/rumah-ibadah/bantuan');
    }

    public function apiPeta(): void {
        $riId  = $this->ri['id'];
        $warga = $this->db->fetchAll("
            SELECT w.id, w.nama, w.lat, w.lng, w.status_kemiskinan, w.level_prioritas, w.skor_prioritas
            FROM warga_miskin w WHERE w.id_rumah_ibadah = ? AND w.status = 'aktif'
        ", [$riId]);
        $this->json([
            'rumah_ibadah' => $this->ri,
            'warga'        => $warga
        ]);
    }
}