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

class Warga_kurang_mampu extends CI_Controller {

    protected $upload_path;
    protected $allowed_ext = ['jpg','jpeg','png','webp'];

    public function __construct() {
        parent::__construct();
        $this->load->model('Warga_kurang_mampu_model', 'wkm_model');
        $this->load->library(['session', 'form_validation', 'upload']);
        $this->load->helper(['url', 'form', 'file']);
        $this->upload_path = FCPATH . 'uploads/wkm/';
        if (!is_dir($this->upload_path)) mkdir($this->upload_path, 0755, true);
        if (!$this->session->userdata('user_id')) redirect('auth/login');
    }

    private function _is_admin() {
        return $this->session->userdata('role') === 'admin';
    }

    private function _render($view, $data = []) {
        $data['is_admin']            = $this->_is_admin();
        $data['count_polling_aktif'] = $this->db->where('status','aktif')->count_all_results('polling');
        $this->load->view('templates/header', $data);
        $this->load->view($view, $data);
        $this->load->view('templates/footer', $data);
    }

    private function _get_warga_id() {
        $warga_id = $this->session->userdata('warga_id');
        if (!$warga_id) {
            $user = $this->db->select('warga_id')->where('id', $this->session->userdata('user_id'))->get('users')->row();
            if ($user && $user->warga_id) {
                $warga_id = $user->warga_id;
                $this->session->set_userdata('warga_id', $warga_id);
            }
        }
        return $warga_id ?: null;
    }

    // ── INDEX ─────────────────────────────────────────────────
    public function index() {
        $status = $this->input->get('status');
        $q      = $this->input->get('q');
        $tahun  = $this->input->get('tahun');

        if ($this->_is_admin()) {
            $list = $this->wkm_model->get_all($status, $q, $tahun);
        } else {
            $warga_id = $this->_get_warga_id();
            $list     = $warga_id ? $this->wkm_model->get_by_warga($warga_id) : [];
        }

        $data = [
            'list'            => $list,
            'total_all'       => $this->wkm_model->count_all(),
            'total_menunggu'  => $this->wkm_model->count_by_status('menunggu'),
            'total_disetujui' => $this->wkm_model->count_by_status('disetujui'),
            'total_ditolak'   => $this->wkm_model->count_by_status('ditolak'),
            'title'           => 'Warga Kurang Mampu',
        ];
        $this->_render('bansos/warga_kurang_mampu', $data);
    }

    // ── TAMBAH FORM ───────────────────────────────────────────
    public function tambah() {
        $this->_render('bansos/wkm_form', [
            'edit_mode' => false,
            'item'      => null,
            'title'     => 'Tambah Pengajuan',
        ]);
    }

    // ── SIMPAN ────────────────────────────────────────────────
    public function simpan() {
        $warga_id = $this->_is_admin()
            ? (int)$this->input->post('warga_id')
            : $this->_get_warga_id();

        if (!$warga_id) show_error('Warga tidak ditemukan.', 404);

        $this->form_validation->set_rules('penghasilan_bulan', 'Penghasilan/Bulan', 'required|numeric');
        $this->form_validation->set_rules('jml_tanggungan',    'Jumlah Tanggungan', 'required|numeric');
        $this->form_validation->set_rules('kondisi_rumah',     'Kondisi Rumah',     'required');
        $this->form_validation->set_rules('alasan_pengajuan',  'Alasan Pengajuan',  'required');

        if (!$this->form_validation->run()) {
            return $this->_render('bansos/wkm_form', ['edit_mode' => false, 'item' => null, 'title' => 'Tambah Pengajuan']);
        }

        // Handle upload foto
        $fotos = $this->_upload_fotos('foto_rumah');

        $this->wkm_model->insert([
            'warga_id'          => $warga_id,
            'penghasilan_bulan' => $this->input->post('penghasilan_bulan'),
            'pekerjaan'         => $this->input->post('pekerjaan', true),
            'jml_tanggungan'    => $this->input->post('jml_tanggungan'),
            'kondisi_rumah'     => $this->input->post('kondisi_rumah'),
            'status_rumah'      => $this->input->post('status_rumah'),
            'alasan_pengajuan'  => $this->input->post('alasan_pengajuan', true),
            'keterangan_tambahan' => $this->input->post('keterangan_tambahan', true),
            'foto_rumah'        => json_encode($fotos, JSON_UNESCAPED_UNICODE),
            'status_pengajuan'  => 'menunggu',
            'tgl_pengajuan'     => date('Y-m-d'),
            'diajukan_oleh'     => $this->session->userdata('user_id'),
        ]);

        $this->session->set_flashdata('success', 'Pengajuan warga kurang mampu berhasil disubmit.');
        redirect('warga_kurang_mampu');
    }

    // ── EDIT FORM ─────────────────────────────────────────────
    public function edit($id = null) {
        if (!$id) redirect('warga_kurang_mampu');
        $item = $this->wkm_model->get_by_id($id);
        if (!$item) show_404();

        // Non-admin hanya bisa edit miliknya sendiri & status masih menunggu
        if (!$this->_is_admin()) {
            $warga_id = $this->_get_warga_id();
            if ($item->warga_id != $warga_id || $item->status_pengajuan !== 'menunggu') {
                $this->session->set_flashdata('error', 'Tidak dapat mengedit pengajuan ini.');
                return redirect('warga_kurang_mampu');
            }
        }

        $this->_render('bansos/wkm_form', ['edit_mode' => true, 'item' => $item, 'title' => 'Edit Pengajuan']);
    }

    // ── UPDATE ────────────────────────────────────────────────
    public function update($id = null) {
        if (!$id) redirect('warga_kurang_mampu');
        $item = $this->wkm_model->get_by_id($id);
        if (!$item) show_404();

        $fotos_lama = json_decode($item->foto_rumah ?? '[]', true) ?: [];

        // Upload foto baru jika ada
        $fotos_baru = $this->_upload_fotos('foto_rumah');

        // Hapus foto yang ditandai dihapus
        $hapus_idx = $this->input->post('hapus_foto') ?? [];
        foreach ((array)$hapus_idx as $idx) {
            if (isset($fotos_lama[$idx])) {
                $path = $this->upload_path . $fotos_lama[$idx];
                if (file_exists($path)) unlink($path);
                unset($fotos_lama[$idx]);
            }
        }
        $fotos_lama = array_values($fotos_lama);
        $semua_foto = array_merge($fotos_lama, $fotos_baru);

        $update_data = [
            'penghasilan_bulan'   => $this->input->post('penghasilan_bulan'),
            'pekerjaan'           => $this->input->post('pekerjaan', true),
            'jml_tanggungan'      => $this->input->post('jml_tanggungan'),
            'kondisi_rumah'       => $this->input->post('kondisi_rumah'),
            'status_rumah'        => $this->input->post('status_rumah'),
            'alasan_pengajuan'    => $this->input->post('alasan_pengajuan', true),
            'keterangan_tambahan' => $this->input->post('keterangan_tambahan', true),
            'foto_rumah'          => json_encode($semua_foto, JSON_UNESCAPED_UNICODE),
        ];

        // Admin bisa ubah status
        if ($this->_is_admin()) {
            $update_data['status_pengajuan'] = $this->input->post('status_pengajuan');
            $update_data['catatan_verifikasi'] = $this->input->post('catatan_verifikasi', true);
            $update_data['diverifikasi_oleh']  = $this->session->userdata('user_id');
            $update_data['tgl_verifikasi']     = date('Y-m-d');
        }

        $this->wkm_model->update($id, $update_data);
        $this->session->set_flashdata('success', 'Data pengajuan berhasil diperbarui.');
        redirect('warga_kurang_mampu');
    }

    // ── VERIFIKASI STATUS (AJAX quick action) ─────────────────
    public function verifikasi() {
        if (!$this->_is_admin()) show_error('Akses ditolak.', 403);
        $id     = (int)$this->input->post('id');
        $status = $this->input->post('status');
        $valid  = ['menunggu','diverifikasi','disetujui','ditolak'];
        if (!in_array($status, $valid)) { echo json_encode(['ok'=>false]); exit; }

        $this->wkm_model->update($id, [
            'status_pengajuan'   => $status,
            'diverifikasi_oleh'  => $this->session->userdata('user_id'),
            'tgl_verifikasi'     => date('Y-m-d'),
            'catatan_verifikasi' => $this->input->post('catatan', true),
        ]);
        echo json_encode(['ok' => true]);
        exit;
    }

    // ── HAPUS ─────────────────────────────────────────────────
    public function hapus($id = null) {
        if (!$this->_is_admin()) show_error('Akses ditolak.', 403);
        if (!$id) redirect('warga_kurang_mampu');
        $item = $this->wkm_model->get_by_id($id);
        if ($item) {
            $fotos = json_decode($item->foto_rumah ?? '[]', true) ?: [];
            foreach ($fotos as $f) {
                $p = $this->upload_path . $f;
                if (file_exists($p)) unlink($p);
            }
        }
        $this->wkm_model->delete($id);
        $this->session->set_flashdata('success', 'Data pengajuan berhasil dihapus.');
        redirect('warga_kurang_mampu');
    }

    // ── DETAIL / CETAK ────────────────────────────────────────
    public function detail($id = null) {
        if (!$id) redirect('warga_kurang_mampu');
        $item = $this->wkm_model->get_by_id($id);
        if (!$item) show_404();

        if (!$this->_is_admin()) {
            $warga_id = $this->_get_warga_id();
            if ($item->warga_id != $warga_id) show_error('Akses ditolak.', 403);
        }

        $this->_render('bansos/wkm_detail', ['item' => $item, 'title' => 'Detail Pengajuan – '.$item->nama_lengkap]);
    }

    // ── CETAK PDF (halaman print) ─────────────────────────────
    public function cetak($id = null) {
        if (!$id) redirect('warga_kurang_mampu');
        $item = $this->wkm_model->get_by_id($id);
        if (!$item) show_404();

        if (!$this->_is_admin()) {
            $warga_id = $this->_get_warga_id();
            if ($item->warga_id != $warga_id) show_error('Akses ditolak.', 403);
        }

        // Ambil data RT - fallback jika tabel tidak ada
        $rt_info = null;
        foreach (['pengaturan','settings','profil_rt','rt_info','config'] as $tbl) {
            if ($this->db->table_exists($tbl)) { $rt_info = $this->db->get($tbl)->row(); break; }
        }

        $this->load->view('bansos/wkm_cetak', [
            'item'    => $item,
            'rt_info' => $rt_info,
            'fotos'   => json_decode($item->foto_rumah ?? '[]', true) ?: [],
        ]);
    }

    // ── DOWNLOAD SEMUA FOTO (ZIP) ─────────────────────────────
    public function download_foto($id = null) {
        if (!$id) redirect('warga_kurang_mampu');
        $item = $this->wkm_model->get_by_id($id);
        if (!$item) show_404();

        if (!$this->_is_admin()) {
            $warga_id = $this->_get_warga_id();
            if ($item->warga_id != $warga_id) show_error('Akses ditolak.', 403);
        }

        $fotos = json_decode($item->foto_rumah ?? '[]', true) ?: [];
        if (empty($fotos)) {
            $this->session->set_flashdata('error', 'Tidak ada foto untuk diunduh.');
            return redirect('warga_kurang_mampu/detail/'.$id);
        }

        $zip_name = 'foto_rumah_' . preg_replace('/\s+/', '_', strtolower($item->nama_lengkap)) . '.zip';
        $zip_path = sys_get_temp_dir() . '/' . $zip_name;

        $zip = new ZipArchive();
        if ($zip->open($zip_path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            $this->session->set_flashdata('error', 'Gagal membuat file ZIP.');
            return redirect('warga_kurang_mampu/detail/'.$id);
        }

        foreach ($fotos as $i => $f) {
            $full = $this->upload_path . $f;
            if (file_exists($full)) {
                $ext = pathinfo($f, PATHINFO_EXTENSION);
                $zip->addFile($full, 'foto_' . ($i+1) . '.' . $ext);
            }
        }
        $zip->close();

        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zip_name . '"');
        header('Content-Length: ' . filesize($zip_path));
        header('Pragma: no-cache');
        readfile($zip_path);
        unlink($zip_path);
        exit;
    }

    // ── AJAX: CARI WARGA ──────────────────────────────────────
    public function cari_warga() {
        while (ob_get_level()) ob_end_clean();
        if (!$this->_is_admin()) { echo json_encode([]); exit; }
        $q = trim($this->input->get('q', true));
        if (mb_strlen($q) < 2) { echo json_encode([]); exit; }

        $rows = $this->db
            ->select('w.id, w.nama_lengkap, w.nik, kk.no_kk')
            ->from('warga w')
            ->join('kartu_keluarga kk', 'kk.id = w.kk_id', 'left')
            ->group_start()->like('w.nama_lengkap', $q)->or_like('w.nik', $q)->group_end()
            ->order_by('w.nama_lengkap')->limit(10)->get()->result();

        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($rows, JSON_UNESCAPED_UNICODE);
        exit;
    }

    // ── PRIVATE: UPLOAD MULTI FOTO ────────────────────────────
    private function _upload_fotos($field = 'foto_rumah') {
        $uploaded = [];
        if (empty($_FILES[$field]['name'][0])) return $uploaded;

        $files = $_FILES[$field];
        $count = count($files['name']);

        for ($i = 0; $i < $count; $i++) {
            if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;
            $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
            if (!in_array($ext, $this->allowed_ext)) continue;

            $new_name = 'wkm_' . time() . '_' . uniqid() . '.' . $ext;
            $dest     = $this->upload_path . $new_name;
            if (move_uploaded_file($files['tmp_name'][$i], $dest)) {
                $uploaded[] = $new_name;
            }
        }
        return $uploaded;
    }
}