<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Controller API RT
 * Auth: API Key via header X-Api-Key ATAU parameter ?api_key=
 * Key diambil dari tabel pengaturan (kolom api_key, row id=1)
 *
 * Endpoints:
 *   GET /api/info        - Info profil RT & statistik
 *   GET /api/warga       - Data kependudukan
 *   GET /api/keuangan    - Kas RT, pemasukan, pengeluaran
 *   GET /api/iuran       - Iuran warga (?bulan=&tahun=)
 *   GET /api/pinjaman    - Pinjaman aktif
 *   GET /api/tabungan    - Tabungan warga
 *   GET /api/inventaris  - Inventaris
 *   GET /api/pengumuman  - Pengumuman aktif (?limit=5)
 *   GET /api/kegiatan    - Kegiatan mendatang
 *   GET /api/dashboard   - Semua data sekaligus (untuk widget RW)
 */
class Api extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
    }

    // =========================================================================
    // PRIVATE HELPERS
    // =========================================================================

    private function _get_api_key()
    {
        $row = $this->db->select('api_key')->where('id', 1)->get('pengaturan')->row();
        return $row ? $row->api_key : null;
    }

    private function _auth()
    {
        $stored_key = $this->_get_api_key();

        if (empty($stored_key)) {
            $this->_json(['status' => 'error', 'message' => 'API Key belum dikonfigurasi di Pengaturan RT.'], 403);
            exit;
        }

        $submitted = $this->input->get_request_header('X-Api-Key', TRUE);
        if ( ! $submitted) $submitted = $this->input->get('api_key', TRUE);
        if ( ! $submitted) $submitted = $this->input->post('api_key', TRUE);

        if ($submitted !== $stored_key) {
            $this->_json(['status' => 'error', 'message' => 'Unauthorized'], 401);
            exit;
        }
    }

    private function _json($data, $code = 200)
    {
        $this->output
            ->set_status_header($code)
            ->set_content_type('application/json', 'utf-8')
            ->set_output(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }

    private function _profil_rt()
    {
        return $this->db
            ->select('nama_rt, nama_rw, nama_kelurahan, nama_kecamatan, nama_kota,
                      nama_provinsi, no_telp, alamat_sekretariat, sebutan_rt, sebutan_rw,
                      sebutan_ketua_rt, logo')
            ->where('id', 1)
            ->get('pengaturan')->row();
    }

    // =========================================================================
    // ENDPOINT: /api/info
    // =========================================================================
    public function info()
    {
        $this->_auth();
        $profil      = $this->_profil_rt();
        $total_warga = $this->db->where('status_meninggal', 0)->count_all_results('warga');
        $total_kk    = $this->db->count_all('kartu_keluarga');
        $total_user  = $this->db->where('status', 'aktif')->count_all_results('users');

        $this->_json([
            'status'    => 'ok',
            'profil'    => $profil,
            'statistik' => [
                'total_warga' => (int) $total_warga,
                'total_kk'    => (int) $total_kk,
                'total_user'  => (int) $total_user,
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // ENDPOINT: /api/warga
    // =========================================================================
    public function warga()
    {
        $this->_auth();

        $total     = $this->db->where('status_meninggal', 0)->count_all_results('warga');
        $laki      = $this->db->where('jenis_kelamin', 'L')->where('status_meninggal', 0)->count_all_results('warga');
        $perempuan = $this->db->where('jenis_kelamin', 'P')->where('status_meninggal', 0)->count_all_results('warga');
        $domisili  = $this->db->select('status_domisili, COUNT(*) as jumlah')->where('status_meninggal', 0)->group_by('status_domisili')->get('warga')->result();
        $agama     = $this->db->select('agama, COUNT(*) as jumlah')->where('status_meninggal', 0)->group_by('agama')->get('warga')->result();
        $meninggal = $this->db->where('status_meninggal', 1)->where('YEAR(tanggal_meninggal)', date('Y'))->count_all_results('warga');
        $pemilih   = $this->db->where('status_meninggal', 0)->where('(TIMESTAMPDIFF(YEAR, tanggal_lahir, CURDATE()) >= 17 OR status_perkawinan != "belum_kawin")', NULL, FALSE)->count_all_results('warga');

        $this->_json([
            'status' => 'ok',
            'data'   => [
                'total_warga'         => (int) $total,
                'laki_laki'           => (int) $laki,
                'perempuan'           => (int) $perempuan,
                'total_kk'            => (int) $this->db->count_all('kartu_keluarga'),
                'meninggal_tahun_ini' => (int) $meninggal,
                'pemilih'             => (int) $pemilih,
                'per_domisili'        => $domisili,
                'per_agama'           => $agama,
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // ENDPOINT: /api/keuangan
    // =========================================================================
    public function keuangan()
    {
        $this->_auth();

        $kas_list = $this->db->select('kode, nama, jenis, saldo_saat_ini, is_tabungan')->where('status', 'aktif')->get('master_kas')->result();
        $kas_operasional = 0; $kas_tabungan = 0;
        foreach ($kas_list as $k) { $k->is_tabungan ? $kas_tabungan += $k->saldo_saat_ini : $kas_operasional += $k->saldo_saat_ini; }

        $bln = date('m'); $thn = date('Y');

        // FIX: kolom `jenis_transaksi` -> `jenis`, nilai `masuk` -> `pemasukan`, kolom `tanggal_transaksi` -> `tanggal`
        $p_bln = $this->db->select('SUM(nominal) as total')->where('jenis','pemasukan')->where('MONTH(tanggal)',$bln)->where('YEAR(tanggal)',$thn)->get('kas_rt')->row();
        $k_bln = $this->db->select('SUM(nominal) as total')->where('jenis','pengeluaran')->where('MONTH(tanggal)',$bln)->where('YEAR(tanggal)',$thn)->get('kas_rt')->row();
        $p_thn = $this->db->select('SUM(nominal) as total')->where('jenis','pemasukan')->where('YEAR(tanggal)',$thn)->get('kas_rt')->row();
        $k_thn = $this->db->select('SUM(nominal) as total')->where('jenis','pengeluaran')->where('YEAR(tanggal)',$thn)->get('kas_rt')->row();

        $this->_json([
            'status' => 'ok',
            'data'   => [
                'total_kas_operasional'  => (float) $kas_operasional,
                'total_kas_tabungan'     => (float) $kas_tabungan,
                'total_kas_seluruh'      => (float) ($kas_operasional + $kas_tabungan),
                'pemasukan_bulan_ini'    => (float) ($p_bln->total ?? 0),
                'pengeluaran_bulan_ini'  => (float) ($k_bln->total ?? 0),
                'pemasukan_tahun_ini'    => (float) ($p_thn->total ?? 0),
                'pengeluaran_tahun_ini'  => (float) ($k_thn->total ?? 0),
                'detail_kas'             => $kas_list,
                'periode'                => ['bulan' => (int)$bln, 'tahun' => (int)$thn],
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // ENDPOINT: /api/iuran
    // =========================================================================
    public function iuran()
    {
        $this->_auth();
        $bln = $this->input->get('bulan') ?: date('m');
        $thn = $this->input->get('tahun') ?: date('Y');

        $terkumpul = $this->db->select('SUM(nominal) as total')->where_in('status',['lunas'])->where('periode_bulan',$bln)->where('periode_tahun',$thn)->get('pembayaran_iuran')->row();
        $tunggakan = $this->db->select('SUM(sisa_tagihan) as total')->where('sisa_tagihan >',0)->get('pembayaran_iuran')->row();
        $rekap     = $this->db->select('status, COUNT(*) as jumlah, SUM(nominal) as total_nominal')->where('periode_bulan',$bln)->where('periode_tahun',$thn)->group_by('status')->get('pembayaran_iuran')->result();
        $per_jenis = $this->db->select('ji.nama_iuran, SUM(pi.nominal) as terkumpul, COUNT(*) as transaksi')->from('pembayaran_iuran pi')->join('jenis_iuran ji','ji.id = pi.jenis_iuran_id','left')->where('pi.periode_bulan',$bln)->where('pi.periode_tahun',$thn)->where_in('pi.status',['lunas'])->group_by('pi.jenis_iuran_id')->get()->result();

        $this->_json([
            'status' => 'ok',
            'data'   => [
                'periode'         => ['bulan' => (int)$bln, 'tahun' => (int)$thn],
                'total_terkumpul' => (float) ($terkumpul->total ?? 0),
                'total_tunggakan' => (float) ($tunggakan->total ?? 0),
                'rekap_status'    => $rekap,
                'per_jenis_iuran' => $per_jenis,
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // ENDPOINT: /api/pinjaman
    // =========================================================================
    public function pinjaman()
    {
        $this->_auth();
        $aktif       = $this->db->where('status_pinjaman','aktif')->count_all_results('pinjaman');
        $sisa_total  = $this->db->select('SUM(sisa_pinjaman) as total')->where('status_pinjaman','aktif')->get('pinjaman')->row();
        $per_status  = $this->db->select('status_pinjaman, COUNT(*) as jumlah, SUM(sisa_pinjaman) as sisa')->group_by('status_pinjaman')->get('pinjaman')->result();
        $bln = date('m'); $thn = date('Y');
        $jt = $this->db->select('COUNT(*) as jumlah, SUM(nominal_angsuran) as total_tagihan')->where('status_bayar','belum')->where('MONTH(tanggal_jatuh_tempo)',$bln)->where('YEAR(tanggal_jatuh_tempo)',$thn)->get('angsuran_pinjaman')->row();

        $this->_json([
            'status' => 'ok',
            'data'   => [
                'pinjaman_aktif'        => (int) $aktif,
                'total_sisa_pinjaman'   => (float) ($sisa_total->total ?? 0),
                'per_status'            => $per_status,
                'jatuh_tempo_bulan_ini' => ['jumlah_angsuran' => (int)($jt->jumlah??0), 'total_tagihan' => (float)($jt->total_tagihan??0)],
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // ENDPOINT: /api/tabungan
    // =========================================================================
    public function tabungan()
    {
        $this->_auth();
        $bln = date('m'); $thn = date('Y');
        $total_saldo = $this->db->select('SUM(saldo) as total')->where('status','aktif')->get('tabungan')->row();
        $jumlah      = $this->db->where('status','aktif')->count_all_results('tabungan');
        $per_jenis   = $this->db->select('jenis_tabungan, COUNT(*) as jumlah_rekening, SUM(saldo) as total_saldo')->where('status','aktif')->group_by('jenis_tabungan')->get('tabungan')->result();
        $setoran     = $this->db->select('SUM(nominal) as total')->where('jenis_transaksi','setor')->where('status','disetujui')->where('MONTH(tanggal_transaksi)',$bln)->where('YEAR(tanggal_transaksi)',$thn)->get('transaksi_tabungan')->row();
        $tarik       = $this->db->select('SUM(nominal) as total')->where('jenis_transaksi','tarik')->where('status','disetujui')->where('MONTH(tanggal_transaksi)',$bln)->where('YEAR(tanggal_transaksi)',$thn)->get('transaksi_tabungan')->row();

        $this->_json([
            'status' => 'ok',
            'data'   => [
                'total_saldo'       => (float) ($total_saldo->total ?? 0),
                'jumlah_nasabah'    => (int) $jumlah,
                'per_jenis'         => $per_jenis,
                'setoran_bulan_ini' => (float) ($setoran->total ?? 0),
                'tarik_bulan_ini'   => (float) ($tarik->total ?? 0),
                'periode'           => ['bulan' => (int)$bln, 'tahun' => (int)$thn],
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // ENDPOINT: /api/inventaris
    // =========================================================================
    public function inventaris()
    {
        $this->_auth();
        $this->_json([
            'status' => 'ok',
            'data'   => [
                'total_barang'    => (int) $this->db->count_all('inventaris'),
                'barang_aktif'    => (int) $this->db->where('status','aktif')->count_all_results('inventaris'),
                'barang_rusak'    => (int) $this->db->where_in('kondisi',['rusak_ringan','rusak_berat'])->count_all_results('inventaris'),
                'sedang_dipinjam' => (int) $this->db->where('status','dipinjam')->count_all_results('inventaris'),
                'estimasi_nilai'  => (float) ($this->db->select('SUM(harga_pembelian*jumlah) as total')->get('inventaris')->row()->total ?? 0),
                'per_kategori'    => $this->db->select('kategori, COUNT(*) as jumlah')->group_by('kategori')->get('inventaris')->result(),
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    // =========================================================================
    // ENDPOINT: /api/pengumuman
    // =========================================================================
    public function pengumuman()
    {
        $this->_auth();
        $limit = (int)($this->input->get('limit') ?: 5);
        $data  = $this->db->select('id, judul, kategori, tanggal_publish, untuk_role')
            ->where('status','publish')->where('tanggal_publish <=', date('Y-m-d'))
            ->where('(tanggal_expired IS NULL OR tanggal_expired >= "'.date('Y-m-d').'")', NULL, FALSE)
            ->order_by('tanggal_publish','DESC')->limit($limit)->get('pengumuman')->result();

        $this->_json(['status' => 'ok', 'data' => $data, 'generated_at' => date('Y-m-d H:i:s')]);
    }

    // =========================================================================
    // ENDPOINT: /api/kegiatan
    // =========================================================================
    public function kegiatan()
    {
        $this->_auth();
        $limit     = (int)($this->input->get('limit') ?: 5);
        $mendatang = [];
        if ($this->db->table_exists('jadwal_kegiatan')) {
            $mendatang = $this->db->select('id, nama_kegiatan, tanggal, waktu_mulai, tempat, status')
                ->where('tanggal >=', date('Y-m-d'))->where('status !=','batal')
                ->order_by('tanggal','ASC')->limit($limit)->get('jadwal_kegiatan')->result();
        }
        $arisan = $this->db->select('ap.tanggal_pertemuan, a.nama_arisan, ap.tempat_pertemuan')
            ->from('arisan_pertemuan ap')->join('arisan a','a.id = ap.arisan_id','left')
            ->where('ap.tanggal_pertemuan >=', date('Y-m-d'))->where('ap.status_pertemuan','pending')
            ->order_by('ap.tanggal_pertemuan','ASC')->limit(3)->get()->result();

        $this->_json(['status'=>'ok','data'=>['kegiatan_mendatang'=>$mendatang,'arisan_mendatang'=>$arisan],'generated_at'=>date('Y-m-d H:i:s')]);
    }

    // =========================================================================
    // ENDPOINT: /api/dashboard — gabungan semua data
    // =========================================================================
    public function dashboard()
    {
        $this->_auth();
        $bln = date('m'); $thn = date('Y');

        $profil      = $this->_profil_rt();
        $total_warga = $this->db->where('status_meninggal',0)->count_all_results('warga');
        $total_kk    = $this->db->count_all('kartu_keluarga');
        $laki        = $this->db->where('jenis_kelamin','L')->where('status_meninggal',0)->count_all_results('warga');
        $perempuan   = $this->db->where('jenis_kelamin','P')->where('status_meninggal',0)->count_all_results('warga');

        $kas_list = $this->db->select('kode, nama, saldo_saat_ini, is_tabungan')->where('status','aktif')->get('master_kas')->result();
        $kas_op = 0; $kas_tb = 0;
        foreach ($kas_list as $k) { $k->is_tabungan ? $kas_tb += $k->saldo_saat_ini : $kas_op += $k->saldo_saat_ini; }

        $iuran_tk  = $this->db->select('SUM(nominal) as total')->where_in('status',['lunas'])->where('periode_bulan',$bln)->where('periode_tahun',$thn)->get('pembayaran_iuran')->row();
        $iuran_tg  = $this->db->select('SUM(sisa_tagihan) as total')->where('sisa_tagihan >',0)->get('pembayaran_iuran')->row();
        $pjm_aktif = $this->db->where('status_pinjaman','aktif')->count_all_results('pinjaman');
        $pjm_sisa  = $this->db->select('SUM(sisa_pinjaman) as total')->where('status_pinjaman','aktif')->get('pinjaman')->row();
        $tab_saldo = $this->db->select('SUM(saldo) as total')->where('status','aktif')->get('tabungan')->row();
        $inv_total = $this->db->count_all('inventaris');
        $inv_rusak = $this->db->where_in('kondisi',['rusak_ringan','rusak_berat'])->count_all_results('inventaris');
        $pengumuman= $this->db->select('id, judul, kategori, tanggal_publish')->where('status','publish')->where('tanggal_publish <=',date('Y-m-d'))->order_by('tanggal_publish','DESC')->limit(3)->get('pengumuman')->result();

        // FIX: kolom `jenis_transaksi` -> `jenis`, nilai `masuk` -> `pemasukan`, kolom `tanggal_transaksi` -> `tanggal`
        $p_bln = $this->db->select('SUM(nominal) as total')->where('jenis','pemasukan')->where('MONTH(tanggal)',$bln)->where('YEAR(tanggal)',$thn)->get('kas_rt')->row();
        $k_bln = $this->db->select('SUM(nominal) as total')->where('jenis','pengeluaran')->where('MONTH(tanggal)',$bln)->where('YEAR(tanggal)',$thn)->get('kas_rt')->row();

        $this->_json([
            'status' => 'ok',
            'data'   => [
                'profil_rt'  => $profil,
                'warga'      => ['total'=>(int)$total_warga,'laki_laki'=>(int)$laki,'perempuan'=>(int)$perempuan,'total_kk'=>(int)$total_kk],
                'keuangan'   => ['kas_operasional'=>(float)$kas_op,'kas_tabungan'=>(float)$kas_tb,'total_kas'=>(float)($kas_op+$kas_tb),'pemasukan_bulan_ini'=>(float)($p_bln->total??0),'pengeluaran_bulan_ini'=>(float)($k_bln->total??0)],
                'iuran'      => ['terkumpul_bulan_ini'=>(float)($iuran_tk->total??0),'total_tunggakan'=>(float)($iuran_tg->total??0),'periode'=>['bulan'=>(int)$bln,'tahun'=>(int)$thn]],
                'pinjaman'   => ['jumlah_aktif'=>(int)$pjm_aktif,'total_sisa'=>(float)($pjm_sisa->total??0)],
                'tabungan'   => ['total_saldo'=>(float)($tab_saldo->total??0)],
                'inventaris' => ['total_barang'=>(int)$inv_total,'barang_rusak'=>(int)$inv_rusak],
                'pengumuman_terbaru' => $pengumuman,
            ],
            'generated_at' => date('Y-m-d H:i:s'),
        ]);
    }
// =========================================================================
// ENDPOINT: /api/warga_list
// GET /api/warga_list?page=1&per_page=50&search=&domisili=&jenis_kelamin=
// =========================================================================
public function warga_list()
{
    $this->_auth();

    $page       = max(1, (int)($this->input->get('page') ?: 1));
    $per_page   = min(100, max(10, (int)($this->input->get('per_page') ?: 50)));
    $search     = trim($this->input->get('search') ?: '');
    $domisili   = $this->input->get('domisili') ?: '';
    $jk         = $this->input->get('jenis_kelamin') ?: '';
    $offset     = ($page - 1) * $per_page;

    // Base query
    $this->db->select('w.id, w.nik, w.nama_lengkap, w.jenis_kelamin, w.tanggal_lahir,
                       w.tempat_lahir, w.agama, w.pekerjaan, w.no_hp,
                       w.status_domisili, w.status_hubungan, w.status_perkawinan,
                       w.kk_id, kk.no_kk, kk.alamat as alamat_kk')
             ->from('warga w')
             ->join('kartu_keluarga kk', 'kk.id = w.kk_id', 'left')
             ->where('w.status_meninggal', 0);

    if ($search !== '') {
        $this->db->group_start()
                 ->like('w.nama_lengkap', $search)
                 ->or_like('w.nik', $search)
                 ->or_like('kk.no_kk', $search)
                 ->group_end();
    }
    if ($domisili !== '') $this->db->where('w.status_domisili', $domisili);
    if ($jk !== '')       $this->db->where('w.jenis_kelamin', $jk);

    // Count total (clone kondisi)
    $total = $this->db->count_all_results('', false); // false = jangan reset

    // Ambil data dengan pagination
    $list = $this->db->order_by('w.nama_lengkap', 'ASC')
                     ->limit($per_page, $offset)
                     ->get()->result();

    // Hitung umur
    foreach ($list as &$w) {
        $w->umur = $w->tanggal_lahir
            ? (int) date_diff(date_create($w->tanggal_lahir), date_create())->y
            : null;
    }
    unset($w);

    $this->_json([
        'status' => 'ok',
        'data'   => [
            'list'      => $list,
            'total'     => (int) $total,
            'page'      => $page,
            'per_page'  => $per_page,
            'total_page'=> (int) ceil($total / $per_page),
        ],
        'generated_at' => date('Y-m-d H:i:s'),
    ]);
}

}