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

class Iuran extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('authorization');
        $this->load->library('session');
        $this->load->library('form_validation');
        $this->load->model('Iuran_model');
        $this->load->model('Warga_model');
        $this->load->model('Master_kas_model');
        $this->load->model('User_model');
        check_login();
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── CICIL IURAN ────────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function cicil($id) {
        if(cannot('iuran', 'pay')) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('iuran');
        }

        $iuran = $this->Iuran_model->get_by_id($id);
        if(!$iuran) {
            $this->session->set_flashdata('error', 'Data iuran tidak ditemukan!');
            redirect('iuran');
        }
        if($iuran->status === 'lunas') {
            $this->session->set_flashdata('error', 'Tagihan ini sudah lunas!');
            redirect('iuran/history_cicilan/' . $id);
        }

        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            if($iuran->user_id != $user_id) {
                $this->session->set_flashdata('error', 'Akses ditolak!');
                redirect('iuran');
            }
        }

        $data['title']    = 'Bayar Cicilan';
        $data['iuran']    = $iuran;
        $data['cicilan']  = $this->Iuran_model->get_cicilan_by_iuran($id);
        $data['kas_list'] = is_warga() ? [] : $this->Master_kas_model->get_aktif();

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/cicil', $data);
        $this->load->view('templates/footer');
    }

    public function proses_cicil() {
        if(cannot('iuran', 'pay')) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('iuran');
        }

        $id    = $this->input->post('pembayaran_iuran_id');
        $iuran = $this->Iuran_model->get_by_id($id);

        if(!$iuran || $iuran->status === 'lunas') {
            $this->session->set_flashdata('error', 'Data tidak valid atau sudah lunas!');
            redirect('iuran');
        }

        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            if($iuran->user_id != $user_id) {
                $this->session->set_flashdata('error', 'Akses ditolak!');
                redirect('iuran');
            }
        }

        $this->form_validation->set_rules('nominal_cicilan',  'Nominal Cicilan', 'required|numeric|greater_than[0]');
        $this->form_validation->set_rules('tanggal_bayar',    'Tanggal Bayar',   'required');
        $this->form_validation->set_rules('metode_pembayaran','Metode',          'required');

        if($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('iuran/cicil/' . $id);
        }

        $nominal_cicilan = (float)$this->input->post('nominal_cicilan');
        $total_terbayar  = (float)($iuran->total_terbayar ?: 0);
        $sisa            = $iuran->nominal - $total_terbayar;

        if($nominal_cicilan > $sisa) {
            $this->session->set_flashdata('error',
                'Nominal cicilan (Rp ' . number_format($nominal_cicilan, 0, ',', '.')
                . ') melebihi sisa tagihan (Rp ' . number_format($sisa, 0, ',', '.') . ')!');
            redirect('iuran/cicil/' . $id);
        }

        $ke     = ((int)($iuran->jumlah_cicilan ?: 0)) + 1;
        $metode = $this->input->post('metode_pembayaran');

        // Upload bukti
        $bukti_file = null;
        if(!empty($_FILES['bukti_transfer']['name'])) {
            $config = [
                'upload_path'   => './uploads/iuran/',
                'allowed_types' => 'jpg|jpeg|png|pdf',
                'max_size'      => 2048,
                'file_name'     => 'cicil_' . $id . '_ke' . $ke . '_' . time(),
            ];
            if(!is_dir($config['upload_path'])) mkdir($config['upload_path'], 0777, true);
            $this->load->library('upload', $config);
            if($this->upload->do_upload('bukti_transfer')) {
                $bukti_file = $this->upload->data()['file_name'];
            } else {
                $this->session->set_flashdata('error', 'Gagal upload bukti: ' . $this->upload->display_errors());
                redirect('iuran/cicil/' . $id);
            }
        } elseif(is_warga()) {
    // Warga wajib upload bukti apapun metodenya (semua butuh verifikasi admin)
    $this->session->set_flashdata('error', 'Bukti pembayaran wajib diupload!');
    redirect('iuran/cicil/' . $id);
}

        // Admin → langsung lunas; warga transfer → menunggu_verifikasi
      $status_cicilan = is_warga() ? 'menunggu_verifikasi' : 'lunas';
        $master_kas_id  = is_warga() ? null : $this->input->post('master_kas_id');

        $data_cicilan = [
            'pembayaran_iuran_id' => $id,
            'ke'                  => $ke,
            'nominal_cicilan'     => $nominal_cicilan,
            'tanggal_bayar'       => $this->input->post('tanggal_bayar'),
            'metode_pembayaran'   => $metode,
            'bukti_transfer'      => $bukti_file,
            'master_kas_id'       => $master_kas_id,
            'keterangan'          => $this->input->post('keterangan'),
            'input_oleh'          => $this->session->userdata('user_id'),
            'status'              => $status_cicilan,
            'created_at'          => date('Y-m-d H:i:s'),
        ];

        if($this->Iuran_model->insert_cicilan($data_cicilan)) {
            if($status_cicilan === 'lunas') {
                $this->Iuran_model->recalc_iuran($id);

                if(!is_warga() && $master_kas_id) {
                    $this->_insert_kas_nominal($iuran, $master_kas_id,
                        $this->input->post('tanggal_bayar'), $nominal_cicilan, $ke, $bukti_file);
                    $this->Master_kas_model->update_saldo($master_kas_id);
                }

                $msg = 'Cicilan ke-' . $ke . ' sebesar Rp '
                       . number_format($nominal_cicilan, 0, ',', '.') . ' berhasil dicatat!';
                $iuran_updated = $this->Iuran_model->get_by_id($id);
                if($iuran_updated && $iuran_updated->status === 'lunas') {
                    $msg .= ' 🎉 Tagihan LUNAS!';
                }
                $this->session->set_flashdata('success', $msg);
                $this->User_model->log_activity($this->session->userdata('user_id'), 'create', 'Membayar cicilan iuran ke-' . $ke . ': ' . $iuran->nama_iuran . ' a.n. ' . $iuran->nama_lengkap . ' (Rp ' . number_format($nominal_cicilan, 0, ',', '.') . ')');
                $this->session->set_flashdata('success',
                    'Cicilan ke-' . $ke . ' berhasil dikirim! Menunggu verifikasi admin.');
            }
        } else {
            $this->session->set_flashdata('error', 'Gagal menyimpan cicilan!');
        }

        redirect('iuran/history_cicilan/' . $id);
    }

    public function history_cicilan($id) {
        $iuran = $this->Iuran_model->get_by_id($id);
        if(!$iuran) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan!');
            redirect('iuran');
        }

        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            if($iuran->user_id != $user_id) {
                $this->session->set_flashdata('error', 'Akses ditolak!');
                redirect('iuran');
            }
        }

        $data['title']   = 'History Cicilan';
        $data['iuran']   = $iuran;
        $data['cicilan'] = $this->Iuran_model->get_cicilan_by_iuran($id);

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/history_cicilan', $data);
        $this->load->view('templates/footer');
    }

    public function print_cicilan($id) {
        $iuran = $this->Iuran_model->get_by_id($id);
        if(!$iuran) show_404();

        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            if($iuran->user_id != $user_id) {
                $this->session->set_flashdata('error', 'Akses ditolak!');
                redirect('iuran');
            }
        }

        $data['title']   = 'Print Cicilan';
        $data['iuran']   = $iuran;
        $data['cicilan'] = $this->Iuran_model->get_cicilan_by_iuran($id);

        $this->load->view('iuran/print_cicilan', $data);
    }

    public function hapus_cicilan($cicilan_id) {
        require_admin();

        $cicilan = $this->Iuran_model->get_cicilan_by_id($cicilan_id);
        if(!$cicilan) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan!');
            redirect('iuran');
        }

        $iuran_id = $cicilan->pembayaran_iuran_id;

        if($cicilan->bukti_transfer && file_exists('./uploads/iuran/' . $cicilan->bukti_transfer)) {
            unlink('./uploads/iuran/' . $cicilan->bukti_transfer);
        }

        if($this->Iuran_model->hapus_cicilan($cicilan_id)) {
            $this->Iuran_model->recalc_iuran($iuran_id);
            $this->User_model->log_activity($this->session->userdata('user_id'), 'delete', 'Menghapus cicilan iuran ke-' . $cicilan->ke . ': ' . $cicilan->nama_iuran . ' a.n. ' . $cicilan->nama_lengkap . ' (Rp ' . number_format($cicilan->nominal_cicilan, 0, ',', '.') . ')');
            $this->session->set_flashdata('success', 'Cicilan berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus cicilan!');
        }

        redirect('iuran/history_cicilan/' . $iuran_id);
    }

    public function verifikasi_cicilan($cicilan_id) {
        require_admin();

        $cicilan = $this->Iuran_model->get_cicilan_by_id($cicilan_id);
        if(!$cicilan || $cicilan->status !== 'menunggu_verifikasi') {
            $this->session->set_flashdata('error', 'Data tidak valid!');
            redirect('iuran');
        }

        $iuran_id      = $cicilan->pembayaran_iuran_id;
        $master_kas_id = $this->input->post('master_kas_id');

        if(!$master_kas_id) {
            $data['title']    = 'Verifikasi Cicilan';
            $data['cicilan']  = $cicilan;
            $data['kas_list'] = $this->Master_kas_model->get_aktif();
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('iuran/verifikasi_cicilan', $data);
            $this->load->view('templates/footer');
            return;
        }

        $aksi = $this->input->post('aksi');

        if($aksi === 'terima') {
            $kas = $this->Master_kas_model->get_by_id($master_kas_id);
            if(!$kas) {
                $this->session->set_flashdata('error', 'Kas tidak valid!');
                redirect('iuran/verifikasi_cicilan/' . $cicilan_id);
            }

            $this->db->where('id', (int)$cicilan_id);
            $this->db->update('cicilan_iuran', [
                'status'            => 'lunas',
                'master_kas_id'     => $master_kas_id,
                'diverifikasi_oleh' => $this->session->userdata('user_id'),
            ]);

            $this->Iuran_model->recalc_iuran($iuran_id);

            $iuran = $this->Iuran_model->get_by_id($iuran_id);
            $bulan_nama = ['','Januari','Februari','Maret','April','Mei','Juni',
                           'Juli','Agustus','September','Oktober','November','Desember'];
            $data_kas = [
                'master_kas_id' => $master_kas_id,
                'tanggal'       => $cicilan->tanggal_bayar,
                'jenis'         => 'pemasukan',
                'kategori'      => 'Iuran Cicilan',
                'keterangan'    => 'Cicilan ke-' . $cicilan->ke . ' ' . $cicilan->nama_iuran
                                   . ' a.n. ' . $cicilan->nama_lengkap
                                   . ' periode ' . $bulan_nama[(int)$iuran->periode_bulan]
                                   . ' ' . $iuran->periode_tahun,
                'nominal'       => $cicilan->nominal_cicilan,
                'bukti_dokumen' => $cicilan->bukti_transfer,
                'input_oleh'    => $this->session->userdata('user_id'),
                'created_at'    => date('Y-m-d H:i:s'),
            ];
            $this->load->model('Kas_model');
            $this->Kas_model->insert($data_kas);
            $this->Master_kas_model->update_saldo($master_kas_id);

            $this->User_model->log_activity($this->session->userdata('user_id'), 'update', 'Verifikasi TERIMA cicilan iuran: ' . $cicilan->nama_iuran . ' a.n. ' . $cicilan->nama_lengkap . ' (Rp ' . number_format($cicilan->nominal_cicilan, 0, ',', '.') . ')');
            $this->session->set_flashdata('success', 'Cicilan berhasil diverifikasi!');
        } else {
            if($cicilan->bukti_transfer && file_exists('./uploads/iuran/' . $cicilan->bukti_transfer)) {
                unlink('./uploads/iuran/' . $cicilan->bukti_transfer);
            }
            $this->db->where('id', (int)$cicilan_id);
            $this->db->delete('cicilan_iuran');
            $this->User_model->log_activity($this->session->userdata('user_id'), 'delete', 'Verifikasi TOLAK cicilan iuran: ' . $cicilan->nama_iuran . ' a.n. ' . $cicilan->nama_lengkap . ' (Rp ' . number_format($cicilan->nominal_cicilan, 0, ',', '.') . ')');
            $this->session->set_flashdata('success', 'Cicilan ditolak dan dihapus!');
        }

        redirect('iuran/history_cicilan/' . $iuran_id);
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── INDEX ──────────────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    // public function index() {
    //     if(cannot('iuran', 'view')) {
    //         $this->session->set_flashdata('error', 'Anda tidak memiliki akses ke halaman ini!');
    //         redirect('dashboard');
    //     }

    //     $data['title'] = is_warga() ? 'Iuran Saya' : 'Iuran Warga';

    //     if(is_warga()) {
    //         $user_id = $this->session->userdata('user_id');
    //         $data['iuran']               = $this->Iuran_model->get_by_user($user_id);
    //         $data['tagihan_pending']     = $this->Iuran_model->get_tagihan_pending_by_user($user_id);
    //         $data['menunggu_verifikasi'] = $this->Iuran_model->get_tagihan_menunggu_verifikasi_by_user($user_id);
    //     } else {
    //         $data['iuran']               = $this->Iuran_model->get_all();
    //         $data['menunggu_verifikasi'] = $this->Iuran_model->get_all_menunggu_verifikasi();
    //     }

    //     $this->load->view('templates/header', $data);
    //     $this->load->view('templates/sidebar', $data);
    //     $this->load->view('iuran/index', $data);
    //     $this->load->view('templates/footer');
    // }

    public function index() {
        if(cannot('iuran', 'view')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses ke halaman ini!');
            redirect('dashboard');
        }

        $data['title'] = is_warga() ? 'Iuran Saya' : 'Iuran Warga';

        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $data['tagihan_pending']     = $this->Iuran_model->get_tagihan_pending_by_user($user_id);
            $data['menunggu_verifikasi'] = $this->Iuran_model->get_tagihan_menunggu_verifikasi_by_user($user_id);
            // Stat cards warga – ambil semua untuk summary (tidak di-paginate)
            $data['iuran']               = $this->Iuran_model->get_by_user($user_id);
        } else {
            $data['menunggu_verifikasi'] = $this->Iuran_model->get_all_menunggu_verifikasi();
            $data['iuran']               = []; // Tabel utama pakai server-side
        }

        $data['jenis_iuran_list'] = $this->Iuran_model->get_jenis_iuran();

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/index', $data);
        $this->load->view('templates/footer');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── AJAX DATATABLES ────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function ajax_datatables() {
        if(cannot('iuran', 'view')) {
            echo json_encode(['data' => [], 'recordsTotal' => 0, 'recordsFiltered' => 0]);
            return;
        }

        $draw   = (int)$this->input->post('draw');
        $start  = (int)$this->input->post('start');
        $length = (int)$this->input->post('length');

        // Baca nested array langsung dari $_POST (lebih aman di CI3)
        $searchArr = isset($_POST['search']) ? $_POST['search'] : [];
        $search    = isset($searchArr['value']) ? trim($searchArr['value']) : '';

        // Order
        $orderArr  = isset($_POST['order'][0]) ? $_POST['order'][0] : [];
        $order_idx = isset($orderArr['column']) ? (int)$orderArr['column'] : 0;
        $order_dir = strtoupper(isset($orderArr['dir']) ? $orderArr['dir'] : 'DESC');
        $order_dir = in_array($order_dir, ['ASC','DESC']) ? $order_dir : 'DESC';
        $columns   = ['pi.id','u.nama_lengkap','ji.nama_iuran','pi.periode_tahun','pi.nominal','pi.status','pi.tanggal_bayar'];
        $order_col = isset($columns[$order_idx]) ? $columns[$order_idx] : 'pi.periode_tahun';

        // Filter dari POST (dikirim view via ajax data)
        $filter = [
            'status'         => $this->input->post('f_status'),
            'bulan'          => $this->input->post('f_bulan'),
            'tahun'          => $this->input->post('f_tahun'),
            'jenis_iuran_id' => $this->input->post('f_jenis_iuran_id'),
            'search'         => $search,
        ];

        $user_id = is_warga() ? $this->session->userdata('user_id') : null;

        $total    = $this->Iuran_model->count_datatables([], $user_id);
        $filtered = $this->Iuran_model->count_datatables($filter, $user_id);
        $rows     = $this->Iuran_model->get_datatables($filter, $length, $start, $order_col, $order_dir, $user_id);

        $bulan_names = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
        $bulan_short = ['','Jan','Feb','Mar','Apr','Mei','Jun','Jul','Ags','Sep','Okt','Nov','Des'];

        $data = [];
        $no   = $start + 1;

        foreach($rows as $i) {
            // Status aktual
            $status = $i->status ?? 'pending';
            if($status === 'pending' && (float)($i->total_terbayar ?? 0) > 0 && (float)($i->sisa_tagihan ?? 0) > 0) {
                $status = 'cicil';
            }
            $nominal        = (float)($i->nominal ?? 0);
            $total_terbayar = (float)($i->total_terbayar ?? 0);
            $sisa           = (float)($i->sisa_tagihan ?? $nominal);
            $jml_cicilan    = (int)($i->jumlah_cicilan ?? 0);
            $pct            = ($nominal > 0) ? min(100, round($total_terbayar / $nominal * 100)) : 0;

            // Badge HTML
            $badge_map = [
                'lunas'               => ['sb-lunas','bi-check-circle','Lunas'],
                'cicil'               => ['sb-cicil','bi-hourglass-split','Cicil'],
                'menunggu_verifikasi' => ['sb-verifikasi','bi-clock-history','Menunggu Verifikasi'],
                'pending'             => ['sb-pending','bi-exclamation-triangle','Belum Dibayar'],
                'belum'               => ['sb-pending','bi-exclamation-triangle','Belum Dibayar'],
            ];
            $sb       = isset($badge_map[$status]) ? $badge_map[$status] : ['sb-other','bi-dash-circle', ucfirst($status)];
            $badge_html = '<span class="status-badge '.$sb[0].'"><i class="bi '.$sb[1].'"></i>'.$sb[2].'</span>';

            // Nominal HTML
            $nom_html = '<div class="fw-bold" style="color:#20c997;">Rp '.number_format($nominal,0,',','.').'</div>';
            if($status === 'cicil') {
                $nom_html .= '<div class="cicil-progress-wrap">'
                    .'<div class="cicil-bar-bg"><div class="cicil-bar-fill" style="width:'.$pct.'%;"></div></div>'
                    .'<div class="cicil-info">'
                    .'<span class="ci-bayar">Rp '.number_format($total_terbayar,0,',','.').' ('.$pct.'%)</span>'
                    .'<span class="ci-sisa">Sisa Rp '.number_format($sisa,0,',','.').'</span>'
                    .'</div>'
                    .'<div style="font-size:.67rem;color:#9ca3af;">'.$jml_cicilan.'x cicilan</div>'
                    .'</div>';
            } elseif($status === 'lunas' && $jml_cicilan > 0) {
                $nom_html .= '<div style="font-size:.7rem;color:#166534;margin-top:2px;"><i class="bi bi-check-all"></i> Lunas '.$jml_cicilan.'x cicilan</div>';
            }

            // Tanggal bayar
            $tgl = $i->tanggal_bayar ?? null;
            if($status === 'cicil') {
                $tgl_html = $tgl ? '<span style="font-size:.78rem;">'.date('d/m/Y',strtotime($tgl)).'</span><br><span style="font-size:.67rem;color:#7c3aed;">cicilan terakhir</span>' : '-';
            } else {
                $tgl_html = $tgl ? date('d/m/Y', strtotime($tgl)) : '-';
            }

            // Periode
            $periode = isset($i->periode_bulan,$i->periode_tahun) ? $bulan_names[(int)$i->periode_bulan].' '.$i->periode_tahun : '-';

            // Aksi
            $aksi = '<div class="d-flex gap-1 flex-wrap">';
            if($status === 'menunggu_verifikasi') {
                if(is_admin()) {
                    $aksi .= '<a href="'.base_url('iuran/verifikasi/'.$i->id).'" class="btn-act btn" style="background:#fef3c7;border:1px solid #fde68a;color:#92400e;"><i class="bi bi-check-square"></i> Verifikasi</a>';
                } else {
                    $aksi .= '<span class="status-badge sb-verifikasi"><i class="bi bi-hourglass-split"></i>Sedang Diproses</span>';
                }
            } elseif($status === 'cicil') {
                $aksi .= '<a href="'.base_url('iuran/cicil/'.$i->id).'" class="btn-act btn" style="background:#ede9fe;border:1px solid #c4b5fd;color:#5b21b6;"><i class="bi bi-plus-circle"></i> Lanjut Cicil</a>';
                $aksi .= '<a href="'.base_url('iuran/history_cicilan/'.$i->id).'" class="btn-act btn" style="background:#f3f4f6;border:1px solid #e5e7eb;color:#374151;"><i class="bi bi-clock-history"></i> History</a>';
            } elseif($status === 'pending') {
                $aksi .= '<a href="'.base_url('iuran/bayar/'.$i->id).'" class="btn-act btn" style="background:#d1fae5;border:1px solid #6ee7b7;color:#065f46;"><i class="bi bi-credit-card"></i> Bayar</a>';
                if(is_admin()) {
                    $aksi .= '<a href="'.base_url('iuran/bayar_per_warga/'.($i->warga_id??'')).'" class="btn-act btn" style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e40af;" title="Bayar Semua Tagihan"><i class="bi bi-collection"></i> Bayar Semua</a>';
                }
            }

            // ── Tombol Tagih WA (Admin Only) ──
            if(is_admin() && !empty($i->no_hp) && ($status === 'pending' || $status === 'cicil')) {
                $wa_no = preg_replace('/[^0-9]/', '', $i->no_hp);
                if(substr($wa_no, 0, 1) == '0') $wa_no = '62' . substr($wa_no, 1);
                
                $p_str = $bulan_names[(int)$i->periode_bulan] . ' ' . $i->periode_tahun;
                $t_str = ($status === 'cicil') ? 'Sisa tagihan: Rp ' . number_format($sisa,0,',','.') : 'Nominal: Rp ' . number_format($nominal,0,',','.');
                
                $wa_msg = rawurlencode("Assalamu'alaikum Bpk/Ibu *".$i->nama_lengkap."*!") . "%0A%0A" 
                        . rawurlencode("Mengingatkan untuk pembayaran *".$i->nama_iuran."* periode *".$p_str."*.") . "%0A" 
                        . rawurlencode($t_str) . ".%0A%0A" 
                        . rawurlencode("Mohon segera diselesaikan ya. Terima kasih.");
                
                // Tombol link wa.me (fallback)
                $aksi .= '<a href="https://wa.me/'.$wa_no.'?text='.$wa_msg.'" target="_blank" class="btn-act btn" style="background:#dcfce7;border:1px solid #86efac;color:#166534;" title="Tagih via WA Link"><i class="bi bi-whatsapp"></i></a>';
                // Tombol WAHA langsung (otomatis)
                $aksi .= '<button class="btn-act btn btn-kirim-tagihan-wa" style="background:#25d366;border:1px solid #1fa34a;color:#fff;" title="Kirim WA Otomatis via WAHA" data-id="'.$i->id.'" data-nama="'.addslashes($i->nama_lengkap ?? '').'" onclick="kirimTagihanWa(this)"><i class="bi bi-send-fill"></i> Tagih WA</button>';

            } elseif($status === 'lunas') {
                $aksi .= '<a href="'.base_url('iuran/detail/'.$i->id).'" class="btn-act btn" style="background:#dbeafe;border:1px solid #93c5fd;color:#1e40af;"><i class="bi bi-eye"></i> Detail</a>';
                if($jml_cicilan > 0) {
                    $aksi .= '<a href="'.base_url('iuran/history_cicilan/'.$i->id).'" class="btn-act btn" style="background:#f3f4f6;border:1px solid #e5e7eb;color:#374151;"><i class="bi bi-clock-history"></i> History</a>';
                }
            }
            if(is_admin()) {
                $aksi .= '<a href="'.base_url('iuran/edit/'.$i->id).'" class="btn-act btn" style="background:#fef3c7;border:1px solid #fde68a;color:#92400e;" title="Edit"><i class="bi bi-pencil"></i></a>';
                $aksi .= '<button class="btn-act btn" style="background:#fee2e2;border:1px solid #fecaca;color:#991b1b;" title="Hapus" onclick="konfirmasiHapusIuran(\''.base_url('iuran/hapus/'.$i->id).'\',\''.addslashes($i->nama_iuran??'').'\',\''.addslashes($i->nama_lengkap??'').'\')"><i class="bi bi-trash"></i></button>';
            }
            $aksi .= '</div>';

            // Data mobile card (JSON di-embed via data attribute, render di JS)
            $border_color = ['sb-lunas'=>'#20c997','sb-cicil'=>'#7c3aed','sb-verifikasi'=>'#f59e0b','sb-pending'=>'#ef4444','sb-other'=>'#e5e7eb'][$sb[0]] ?? '#e5e7eb';

            $mobile_html = '<div class="iuran-mobile-card" style="border-radius:12px;border-left:4px solid '.$border_color.';border:1.5px solid #f1f3f5;background:#fff;padding:13px 14px;">'
                .'<div class="d-flex justify-content-between align-items-start mb-1">'
                .'<div>'
                .(is_admin() ? '<div class="fw-semibold" style="font-size:.88rem;">'.htmlspecialchars($i->nama_lengkap??'-').'</div>' : '')
                .'<div style="font-size:.82rem;color:#374151;">'.htmlspecialchars($i->nama_iuran??'-').'</div>'
                .'</div>'
                .'<span class="status-badge '.$sb[0].' flex-shrink-0 ms-2"><i class="bi '.$sb[1].'"></i>'.$sb[2].'</span>'
                .'</div>'
                .'<div class="d-flex justify-content-between align-items-center mb-1" style="font-size:.78rem;color:#6b7280;">'
                .'<span><i class="bi bi-calendar3 me-1"></i>'.$periode.'</span>'
                .'<span class="fw-bold" style="color:#20c997;font-size:.88rem;">Rp '.number_format($nominal,0,',','.').'</span>'
                .'</div>';

            if($status === 'cicil') {
                $mobile_html .= '<div class="cicil-progress-wrap mb-2">'
                    .'<div class="cicil-bar-bg"><div class="cicil-bar-fill" style="width:'.$pct.'%;"></div></div>'
                    .'<div class="cicil-info">'
                    .'<span class="ci-bayar">Terbayar Rp '.number_format($total_terbayar,0,',','.').' ('.$pct.'%)</span>'
                    .'<span class="ci-sisa">Sisa Rp '.number_format($sisa,0,',','.').'</span>'
                    .'</div>'
                    .'<div style="font-size:.67rem;color:#9ca3af;">'.$jml_cicilan.'x cicilan tercatat</div>'
                    .'</div>';
            } elseif($status === 'lunas' && $jml_cicilan > 0) {
                $mobile_html .= '<div style="font-size:.72rem;color:#166534;margin-bottom:6px;"><i class="bi bi-check-all me-1"></i>Lunas dalam '.$jml_cicilan.'x cicilan</div>';
            }

            $mobile_html .= '<div class="d-flex gap-2" style="border-top:1px solid #f3f4f6;padding-top:10px;">'.$aksi.'</div>'
                .'</div>';

            $row = [
                $no++,
            ];
            if(is_admin()) $row[] = htmlspecialchars($i->nama_lengkap ?? '-');
            $row[] = htmlspecialchars($i->nama_iuran ?? '-');
            $row[] = $periode;
            $row[] = $nom_html;
            $row[] = $badge_html;
            $row[] = $tgl_html;
            $row[] = $aksi;
            $row[] = $mobile_html; // extra col untuk mobile (hidden from DT)

            $data[] = $row;
        }

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'draw'            => $draw,
                'recordsTotal'    => $total,
                'recordsFiltered' => $filtered,
                'data'            => $data,
            ]));
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── BAYAR (Admin: bisa lunas sekaligus atau cicil) ─────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function bayar($id = null) {
        if(cannot('iuran', 'pay')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses untuk membayar iuran!');
            redirect('iuran');
        }

        // Warga diarahkan ke halaman bayar khusus warga
        if(is_warga()) {
            redirect('iuran/bayar_warga/' . $id);
        }

        $iuran = $this->Iuran_model->get_by_id($id);
        if(!$iuran) {
            $this->session->set_flashdata('error', 'Data iuran tidak ditemukan!');
            redirect('iuran');
        }

        // Tagihan sudah lunas tidak perlu dibayar lagi
        if($iuran->status === 'lunas') {
            $this->session->set_flashdata('error', 'Tagihan ini sudah lunas!');
            redirect('iuran');
        }

        $data['kas_list'] = $this->Master_kas_model->get_aktif();

        if($this->input->post()) {
            $mode_bayar    = $this->input->post('mode_bayar'); // 'lunas' atau 'cicil'
            $master_kas_id = $this->input->post('master_kas_id');

            // Validasi umum
            $this->form_validation->set_rules('tanggal_bayar',     'Tanggal Bayar',     'required');
            $this->form_validation->set_rules('metode_pembayaran', 'Metode Pembayaran', 'required');
            $this->form_validation->set_rules('master_kas_id',     'Kas Tujuan',        'required|numeric');

            // Validasi tambahan jika cicil
            if($mode_bayar === 'cicil') {
                $this->form_validation->set_rules('nominal_cicilan', 'Nominal Cicilan', 'required|numeric|greater_than[0]');
            }

            if($this->form_validation->run() == FALSE) {
                $this->session->set_flashdata('error', validation_errors());
                redirect('iuran/bayar/' . $id);
            }

            $kas = $this->Master_kas_model->get_by_id($master_kas_id);
            if(!$kas) {
                $this->session->set_flashdata('error', 'Kas tujuan tidak valid!');
                redirect('iuran/bayar/' . $id);
            }

            // Upload bukti (opsional)
            $bukti_file = null;
            if(!empty($_FILES['bukti_transfer']['name'])) {
                $config = array(
                    'upload_path'   => './uploads/iuran/',
                    'allowed_types' => 'jpg|jpeg|png|pdf',
                    'max_size'      => 2048,
                    'file_name'     => 'bukti_' . $id . '_' . time(),
                );
                if(!is_dir($config['upload_path'])) mkdir($config['upload_path'], 0777, true);
                $this->load->library('upload', $config);
                if($this->upload->do_upload('bukti_transfer')) {
                    $bukti_file = $this->upload->data()['file_name'];
                }
            }

            // ── MODE CICIL ──────────────────────────────────────────────────
            if($mode_bayar === 'cicil') {

                $nominal_cicilan = (float)$this->input->post('nominal_cicilan');
                $total_terbayar  = (float)($iuran->total_terbayar ?: 0);
                $sisa            = $iuran->nominal - $total_terbayar;

                if($nominal_cicilan > $sisa) {
                    $this->session->set_flashdata('error',
                        'Nominal cicilan (Rp ' . number_format($nominal_cicilan, 0, ',', '.')
                        . ') melebihi sisa tagihan (Rp ' . number_format($sisa, 0, ',', '.') . ')!');
                    redirect('iuran/bayar/' . $id);
                }

                $ke = ((int)($iuran->jumlah_cicilan ?: 0)) + 1;

                $data_cicilan = [
                    'pembayaran_iuran_id' => $id,
                    'ke'                  => $ke,
                    'nominal_cicilan'     => $nominal_cicilan,
                    'tanggal_bayar'       => $this->input->post('tanggal_bayar'),
                    'metode_pembayaran'   => $this->input->post('metode_pembayaran'),
                    'bukti_transfer'      => $bukti_file,
                    'master_kas_id'       => $master_kas_id,
                    'keterangan'          => $this->input->post('keterangan'),
                    'input_oleh'          => $this->session->userdata('user_id'),
                    'status'              => 'lunas', // admin → langsung lunas
                    'created_at'          => date('Y-m-d H:i:s'),
                ];

                if($this->Iuran_model->insert_cicilan($data_cicilan)) {
                    // Hitung ulang sisa & status tagihan
                    $this->Iuran_model->recalc_iuran($id);

                    // Catat ke kas
                    $this->_insert_kas_nominal($iuran, $master_kas_id,
                        $this->input->post('tanggal_bayar'), $nominal_cicilan, $ke, $bukti_file);
                    $this->Master_kas_model->update_saldo($master_kas_id);

                    $iuran_updated = $this->Iuran_model->get_by_id($id);
                    $msg = 'Cicilan ke-' . $ke . ' sebesar Rp '
                           . number_format($nominal_cicilan, 0, ',', '.')
                           . ' berhasil dicatat masuk ke ' . $kas->nama . '!';

                    if($iuran_updated && $iuran_updated->status === 'lunas') {
                        $msg .= ' 🎉 Tagihan sudah LUNAS!';
                        $this->session->set_flashdata('success', $msg);
                        redirect('iuran');
                    } else {
                        $this->session->set_flashdata('success', $msg);
                        redirect('iuran/history_cicilan/' . $id);
                    }
                } else {
                    $this->session->set_flashdata('error', 'Gagal menyimpan cicilan!');
                    redirect('iuran/bayar/' . $id);
                }

            // ── MODE LUNAS ──────────────────────────────────────────────────
            // } else {
                

            //     $update_data = array(
            //         'tanggal_bayar'      => $this->input->post('tanggal_bayar'),
            //         'metode_pembayaran'  => $this->input->post('metode_pembayaran'),
            //         'status'             => 'lunas',
            //         'keterangan'         => $this->input->post('keterangan'),
            //         'diverifikasi_oleh'  => $this->session->userdata('user_id'),
            //         'tanggal_verifikasi' => date('Y-m-d H:i:s'),
            //         'bukti_transfer'     => $bukti_file,
            //         'total_terbayar'     => $iuran->nominal,
            //         'sisa_tagihan'       => 0,
            //     );

            //     if($this->Iuran_model->update($id, $update_data)) {
            //         $this->_insert_kas($iuran, $master_kas_id,
            //             $this->input->post('tanggal_bayar'), $bukti_file);
            //         $this->Master_kas_model->update_saldo($master_kas_id);
            //         $this->session->set_flashdata('success',
            //             'Pembayaran iuran berhasil dicatat LUNAS dan masuk ke ' . $kas->nama . '!');
            //         redirect('iuran');
            //     } else {
            //         $this->session->set_flashdata('error', 'Gagal melakukan pembayaran!');
            //     }
            // }
            // ── MODE LUNAS ──────────────────────────────────────────────────────
            // ── MODE LUNAS ──────────────────────────────────────────────────────────────

} else {

    // Validasi tambahan nominal_lunas
    $this->form_validation->set_rules('nominal_lunas', 'Nominal Bayar', 'required|numeric|greater_than[0]');
    if($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('error', validation_errors());
        redirect('iuran/bayar/' . $id);
    }

    $nominal_dibayar = (float)$this->input->post('nominal_lunas');
    $sisa_tagihan    = $iuran->nominal - (float)($iuran->total_terbayar ?: 0);
    $kelebihan       = round($nominal_dibayar - $sisa_tagihan, 2);

    if($nominal_dibayar < $sisa_tagihan) {
        $this->session->set_flashdata('error',
            'Nominal bayar tidak boleh kurang dari sisa tagihan (Rp '
            . number_format($sisa_tagihan, 0, ',', '.') . ')!');
        redirect('iuran/bayar/' . $id);
    }

    if($kelebihan > 0 && !$this->input->post('kas_kelebihan_id')) {
        $this->session->set_flashdata('error', 'Ada kelebihan bayar Rp '
            . number_format($kelebihan, 0, ',', '.')
            . '. Pilih kas tujuan untuk kelebihan!');
        redirect('iuran/bayar/' . $id);
    }

    $update_data = array(
        'tanggal_bayar'      => $this->input->post('tanggal_bayar'),
        'metode_pembayaran'  => $this->input->post('metode_pembayaran'),
        'status'             => 'lunas',
        'keterangan'         => $this->input->post('keterangan'),
        'diverifikasi_oleh'  => $this->session->userdata('user_id'),
        'tanggal_verifikasi' => date('Y-m-d H:i:s'),
        'bukti_transfer'     => $bukti_file,
        'total_terbayar'     => $iuran->nominal,
        'sisa_tagihan'       => 0,
    );

    // ── MULAI TRANSACTION ──────────────────────────────────────────
    $this->db->trans_start();

    $this->Iuran_model->update($id, $update_data);

    $this->_insert_kas(
        $iuran,
        $master_kas_id,
        $this->input->post('tanggal_bayar'),
        $bukti_file
    );

    if($kelebihan > 0) {
        $kas_kelebihan_id = (int)$this->input->post('kas_kelebihan_id');
        $this->load->model('Kas_model');
        $bulan_nama = ['','Januari','Februari','Maret','April','Mei','Juni',
                       'Juli','Agustus','September','Oktober','November','Desember'];
        $data_kas_lebih = array(
            'master_kas_id' => $kas_kelebihan_id,
            'tanggal'       => $this->input->post('tanggal_bayar'),
            'jenis'         => 'pemasukan',
            'kategori'      => 'Kelebihan Iuran',
            'keterangan'    => 'Kelebihan bayar ' . $iuran->nama_iuran
                               . ' a.n. ' . $iuran->nama_lengkap
                               . ' periode ' . $bulan_nama[(int)$iuran->periode_bulan]
                               . ' ' . $iuran->periode_tahun,
            'nominal'       => $kelebihan,
            'bukti_dokumen' => $bukti_file,
            'input_oleh'    => $this->session->userdata('user_id'),
            'created_at'    => date('Y-m-d H:i:s'),
        );
        $this->Kas_model->insert($data_kas_lebih);
    }

    $this->db->trans_complete();
    // ── AKHIR TRANSACTION ──────────────────────────────────────────

    if($this->db->trans_status() === FALSE) {
        if($bukti_file && file_exists('./uploads/iuran/' . $bukti_file)) {
            unlink('./uploads/iuran/' . $bukti_file);
        }
        $this->session->set_flashdata('error', 'Gagal melakukan pembayaran! Semua perubahan dibatalkan.');
        redirect('iuran/bayar/' . $id);
    }

    // Update saldo di luar transaction (hanya recalc)
    $this->Master_kas_model->update_saldo($master_kas_id);
    if($kelebihan > 0) {
        $this->Master_kas_model->update_saldo($kas_kelebihan_id);
        $this->session->set_flashdata('success',
            'Pembayaran iuran LUNAS! Kelebihan Rp '
            . number_format($kelebihan, 0, ',', '.')
            . ' dicatat ke kas.');
    } else {
        $this->session->set_flashdata('success',
            'Pembayaran iuran berhasil dicatat LUNAS dan masuk ke ' . $kas->nama . '!');
    }

    redirect('iuran');

} // ← tutup else MODE LUNAS, tidak ada else lagi setelah ini

        } // ← tutup if($this->input->post())

        $data['title'] = 'Bayar Iuran';
        $data['iuran'] = $iuran;
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/bayar_admin', $data);
        $this->load->view('templates/footer');
    }
    // ═══════════════════════════════════════════════════════════════════════
    // ─── BAYAR WARGA ────────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

   public function bayar_warga($id) {
    if(!is_warga()) {
        $this->session->set_flashdata('error', 'Akses ditolak!');
        redirect('iuran');
    }

    $iuran = $this->Iuran_model->get_by_id($id);
    if(!$iuran) {
        $this->session->set_flashdata('error', 'Data iuran tidak ditemukan!');
        redirect('iuran');
    }

    $user_id = $this->session->userdata('user_id');
    if($iuran->user_id != $user_id) {
        $this->session->set_flashdata('error', 'Anda tidak berhak membayar iuran ini!');
        redirect('iuran');
    }

    // Tagihan yang sudah lunas tidak bisa dibayar lagi
    if($iuran->status === 'lunas') {
        $this->session->set_flashdata('error', 'Tagihan ini sudah lunas!');
        redirect('iuran');
    }

    // Jika ada cicilan pending verifikasi, blokir pengiriman baru
    $cicilan_pending = $this->Iuran_model->get_cicilan_menunggu_by_iuran($id);
    if($cicilan_pending) {
        $this->session->set_flashdata('error', 'Masih ada cicilan yang menunggu verifikasi admin. Tunggu hingga diverifikasi sebelum mengirim pembayaran berikutnya.');
        redirect('iuran/history_cicilan/' . $id);
    }

    if($this->input->post()) {
        $mode_bayar = $this->input->post('mode_bayar'); // 'lunas' atau 'cicil'

        $this->form_validation->set_rules('metode_pembayaran', 'Metode Pembayaran', 'required');
        if($mode_bayar === 'cicil') {
            $this->form_validation->set_rules('nominal_cicilan', 'Nominal Cicilan', 'required|numeric|greater_than[0]');
        }

        if($this->form_validation->run()) {

            // Wajib upload bukti
            if(empty($_FILES['bukti_transfer']['name'])) {
                $this->session->set_flashdata('error', 'Bukti pembayaran wajib diupload!');
                redirect('iuran/bayar_warga/' . $id);
            }

            // Upload bukti
            $ke = ((int)($iuran->jumlah_cicilan ?: 0)) + 1;
            $prefix = $mode_bayar === 'cicil' ? 'cicil_' . $id . '_ke' . $ke : 'bukti_' . $id;
            $config = array(
                'upload_path'   => './uploads/iuran/',
                'allowed_types' => 'jpg|jpeg|png|pdf',
                'max_size'      => 2048,
                'file_name'     => $prefix . '_' . time(),
            );
            if(!is_dir($config['upload_path'])) mkdir($config['upload_path'], 0777, true);
            $this->load->library('upload', $config);

            if(!$this->upload->do_upload('bukti_transfer')) {
                $this->session->set_flashdata('error', 'Gagal upload bukti: ' . $this->upload->display_errors());
                redirect('iuran/bayar_warga/' . $id);
            }

            $bukti_file = $this->upload->data()['file_name'];

            // ── MODE CICIL ──────────────────────────────────────────────
            if($mode_bayar === 'cicil') {

                $nominal_cicilan = (float)$this->input->post('nominal_cicilan');
                $total_terbayar  = (float)($iuran->total_terbayar ?: 0);
                $sisa            = $iuran->nominal - $total_terbayar;

                if($nominal_cicilan > $sisa) {
                    $this->session->set_flashdata('error',
                        'Nominal cicilan (Rp ' . number_format($nominal_cicilan, 0, ',', '.')
                        . ') melebihi sisa tagihan (Rp ' . number_format($sisa, 0, ',', '.') . ')!');
                    redirect('iuran/bayar_warga/' . $id);
                }

                $data_cicilan = [
                    'pembayaran_iuran_id' => $id,
                    'ke'                  => $ke,
                    'nominal_cicilan'     => $nominal_cicilan,
                    'tanggal_bayar'       => date('Y-m-d'),
                    'metode_pembayaran'   => $this->input->post('metode_pembayaran'),
                    'bukti_transfer'      => $bukti_file,
                    'master_kas_id'       => null,
                    'keterangan'          => $this->input->post('keterangan'),
                    'input_oleh'          => $user_id,
                    'status'              => 'menunggu_verifikasi',
                    'created_at'          => date('Y-m-d H:i:s'),
                ];

                if($this->Iuran_model->insert_cicilan($data_cicilan)) {
                    $this->session->set_flashdata('success',
                        'Cicilan ke-' . $ke . ' sebesar Rp ' . number_format($nominal_cicilan, 0, ',', '.')
                        . ' berhasil dikirim! Menunggu verifikasi admin.');
                    redirect('iuran/history_cicilan/' . $id);
                } else {
                    $this->session->set_flashdata('error', 'Gagal menyimpan cicilan!');
                    redirect('iuran/bayar_warga/' . $id);
                }

            // ── MODE LUNAS ──────────────────────────────────────────────
            } else {

                // Cek apakah tagihan sudah ada cicilan sebelumnya (partial) → arahkan ke cicil saja
                // tapi tetap izinkan bayar lunas jika sisa = nominal (belum ada cicilan sama sekali)
                $update_data = array(
                    'tanggal_bayar'     => date('Y-m-d H:i:s'),
                    'metode_pembayaran' => $this->input->post('metode_pembayaran'),
                    'status'            => 'menunggu_verifikasi',
                    'keterangan'        => $this->input->post('keterangan'),
                    'bukti_transfer'    => $bukti_file,
                );

                if($this->Iuran_model->update($id, $update_data)) {
                    $this->session->set_flashdata('success',
                        'Pembayaran berhasil dikirim! Menunggu verifikasi admin dalam 1×24 jam.');
                    redirect('iuran');
                } else {
                    $this->session->set_flashdata('error', 'Gagal menyimpan data pembayaran!');
                    redirect('iuran/bayar_warga/' . $id);
                }
            }
        }
    }

    $data['title'] = 'Bayar Iuran';
    $data['iuran'] = $iuran;
    $this->load->view('templates/header', $data);
    $this->load->view('templates/sidebar', $data);
    $this->load->view('iuran/bayar_warga', $data);
    $this->load->view('templates/footer');
}
    // ═══════════════════════════════════════════════════════════════════════
    // ─── BAYAR SEMUA (Warga) ────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function bayar_semua() {
        if(!is_warga()) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('iuran');
        }

        $user_id         = $this->session->userdata('user_id');
        $tagihan_pending = $this->Iuran_model->get_all_pending_by_user($user_id);

        if(empty($tagihan_pending)) {
            $this->session->set_flashdata('error', 'Tidak ada tagihan yang perlu dibayar!');
            redirect('iuran');
        }

        if($this->input->post()) {
            $this->form_validation->set_rules('metode_pembayaran', 'Metode Pembayaran', 'required');

            if($this->form_validation->run()) {
                if(!empty($_FILES['bukti_transfer']['name'])) {
                    $config = array(
                        'upload_path'   => './uploads/iuran/',
                        'allowed_types' => 'jpg|jpeg|png|pdf',
                        'max_size'      => 2048,
                        'file_name'     => 'bukti_all_' . $user_id . '_' . time(),
                    );
                    if(!is_dir($config['upload_path'])) mkdir($config['upload_path'], 0777, true);
                    $this->load->library('upload', $config);

                    if($this->upload->do_upload('bukti_transfer')) {
                        $upload_data  = $this->upload->data();
                        $bukti_file   = $upload_data['file_name'];
                        $berhasil     = 0;
                        $selected_ids = $this->input->post('tagihan_ids');

                        foreach($tagihan_pending as $t) {
                            if(!empty($selected_ids) && !in_array($t->id, $selected_ids)) continue;
                            $update_data = array(
                                'tanggal_bayar'     => date('Y-m-d H:i:s'),
                                'metode_pembayaran' => $this->input->post('metode_pembayaran'),
                                'status'            => 'menunggu_verifikasi',
                                'keterangan'        => $this->input->post('keterangan'),
                                'bukti_transfer'    => $bukti_file,
                            );
                            if($this->Iuran_model->update($t->id, $update_data)) {
                                $berhasil++;
                            }
                        }

                        $this->session->set_flashdata('success', "Berhasil mengirim {$berhasil} pembayaran! Menunggu verifikasi admin.");
                        redirect('iuran');
                    } else {
                        $this->session->set_flashdata('error', 'Gagal upload bukti: ' . $this->upload->display_errors());
                    }
                } else {
                    $this->session->set_flashdata('error', 'Bukti transfer wajib diupload!');
                }
            }
        }

        $data['title']           = 'Bayar Semua Tagihan';
        $data['tagihan_pending'] = $tagihan_pending;
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/bayar_semua', $data);
        $this->load->view('templates/footer');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── VERIFIKASI (Admin) ─────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function verifikasi($id) {
        require_admin();

        $iuran = $this->Iuran_model->get_by_id($id);
        if(!$iuran) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan!');
            redirect('iuran');
        }
        if($iuran->status != 'menunggu_verifikasi') {
            $this->session->set_flashdata('error', 'Pembayaran ini tidak bisa diverifikasi!');
            redirect('iuran');
        }

        $data['kas_list'] = $this->Master_kas_model->get_aktif();

        if($this->input->post()) {
            $aksi = $this->input->post('aksi');

            if($aksi == 'terima') {
                $this->form_validation->set_rules('master_kas_id', 'Kas Tujuan', 'required|numeric');
                if($this->form_validation->run() == FALSE) {
                    $this->session->set_flashdata('error', validation_errors());
                    redirect('iuran/verifikasi/' . $id);
                }

                $master_kas_id = $this->input->post('master_kas_id');
                $kas = $this->Master_kas_model->get_by_id($master_kas_id);
                if(!$kas) {
                    $this->session->set_flashdata('error', 'Kas tujuan tidak valid!');
                    redirect('iuran/verifikasi/' . $id);
                }

                $update_data = array(
                    'status'             => 'lunas',
                    'diverifikasi_oleh'  => $this->session->userdata('user_id'),
                    'tanggal_verifikasi' => date('Y-m-d H:i:s'),
                    'keterangan'         => $this->input->post('keterangan'),
                    'total_terbayar'     => $iuran->nominal,
                    'sisa_tagihan'       => 0,
                );

                if($this->Iuran_model->update($id, $update_data)) {
                    $this->_insert_kas($iuran, $master_kas_id, date('Y-m-d'), $iuran->bukti_transfer);
                    $this->Master_kas_model->update_saldo($master_kas_id);
                    $this->session->set_flashdata('success', 'Pembayaran berhasil diverifikasi dan masuk ke ' . $kas->nama . '!');
                } else {
                    $this->session->set_flashdata('error', 'Gagal memproses verifikasi!');
                }
            } else {
                // TOLAK
                if($iuran->bukti_transfer && file_exists('./uploads/iuran/' . $iuran->bukti_transfer)) {
                    unlink('./uploads/iuran/' . $iuran->bukti_transfer);
                }
                $update_data = array(
                    'status'            => 'pending',
                    'bukti_transfer'    => null,
                    'tanggal_bayar'     => null,
                    'metode_pembayaran' => null,
                    'keterangan'        => $this->input->post('keterangan'),
                );
                if($this->Iuran_model->update($id, $update_data)) {
                    $this->session->set_flashdata('success', 'Pembayaran ditolak!');
                } else {
                    $this->session->set_flashdata('error', 'Gagal memproses penolakan!');
                }
            }
            redirect('iuran');
        }

        $data['title'] = 'Verifikasi Pembayaran';
        $data['iuran'] = $iuran;
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/verifikasi', $data);
        $this->load->view('templates/footer');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── TAMBAH ─────────────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function tambah() {
        require_admin();

        if($this->input->post()) {
            $this->form_validation->set_rules('warga_id',       'Warga',       'required');
            $this->form_validation->set_rules('jenis_iuran_id', 'Jenis Iuran', 'required');
            $this->form_validation->set_rules('bulan',          'Bulan',       'required');
            $this->form_validation->set_rules('tahun',          'Tahun',       'required');
            $this->form_validation->set_rules('nominal',        'Nominal',     'required|numeric');

            if($this->form_validation->run()) {
                $data = array(
                    'warga_id'       => $this->input->post('warga_id'),
                    'jenis_iuran_id' => $this->input->post('jenis_iuran_id'),
                    'periode_bulan'  => $this->input->post('bulan'),
                    'periode_tahun'  => $this->input->post('tahun'),
                    'nominal'        => $this->input->post('nominal'),
                    'status'         => 'pending',
                    'created_at'     => date('Y-m-d H:i:s'),
                );
                if($this->Iuran_model->insert($data)) {
                    $this->session->set_flashdata('success', 'Tagihan iuran berhasil ditambahkan!');
                    redirect('iuran');
                } else {
                    $this->session->set_flashdata('error', 'Gagal menambahkan tagihan iuran!');
                }
            }
        }

        $data['title']       = 'Tambah Tagihan Iuran';
        $data['warga']       = $this->Warga_model->get_all();
        $data['jenis_iuran'] = $this->Iuran_model->get_jenis_iuran();
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/tambah', $data);
        $this->load->view('templates/footer');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── GENERATE TAGIHAN ───────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function generate_tagihan() {
        require_admin();

        $data['title']       = 'Generate Tagihan Massal';
        $data['jenis_iuran'] = $this->Iuran_model->get_jenis_iuran();
        $data['warga']       = $this->Warga_model->get_all();
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/generate_tagihan', $data);
        $this->load->view('templates/footer');
    }

    public function proses_generate_tagihan() {
        require_admin();

        $this->form_validation->set_rules('jenis_iuran_id', 'Jenis Iuran', 'required');
        $this->form_validation->set_rules('periode_bulan_mulai', 'Bulan Mulai', 'required');
        $this->form_validation->set_rules('periode_tahun_mulai', 'Tahun Mulai', 'required');
        $this->form_validation->set_rules('periode_bulan_selesai', 'Bulan Selesai', 'required');
        $this->form_validation->set_rules('periode_tahun_selesai', 'Tahun Selesai', 'required');
        $this->form_validation->set_rules('nominal', 'Nominal', 'required|numeric|greater_than[0]');

        if($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect('iuran/generate_tagihan');
        }

        $warga_ids = $this->input->post('warga_ids');
        if(empty($warga_ids)) {
            $this->session->set_flashdata('error', 'Pilih minimal 1 warga untuk dibuatkan tagihan!');
            redirect('iuran/generate_tagihan');
        }

        $jenis_iuran_id = $this->input->post('jenis_iuran_id');
        $nominal        = $this->input->post('nominal');
        
        $b1 = (int)$this->input->post('periode_bulan_mulai');
        $t1 = (int)$this->input->post('periode_tahun_mulai');
        $b2 = (int)$this->input->post('periode_bulan_selesai');
        $t2 = (int)$this->input->post('periode_tahun_selesai');

        // Gunakan DateTime untuk iterasi yang aman
        $start = new DateTime("$t1-$b1-01");
        $end   = new DateTime("$t2-$b2-01");

        if($start > $end) {
            $this->session->set_flashdata('error', 'Periode mulai tidak boleh lebih besar dari periode selesai!');
            redirect('iuran/generate_tagihan');
        }

        $berhasil = 0;
        $gagal    = 0;

        // Loop melalui setiap bulan dalam range
        $current = clone $start;
        while ($current <= $end) {
            $curr_m = $current->format('m');
            $curr_y = $current->format('Y');
            
            foreach($warga_ids as $warga_id) {
                // Cek apakah tagihan sudah ada (duplikasi)
                $cek = $this->Iuran_model->cek_tagihan_exists($warga_id, $jenis_iuran_id, $curr_m, $curr_y);
                if(!$cek) {
                    $data_iuran = array(
                        'warga_id'       => $warga_id,
                        'jenis_iuran_id' => $jenis_iuran_id,
                        'periode_bulan'  => $curr_m,
                        'periode_tahun'  => $curr_y,
                        'nominal'        => $nominal,
                        'status'         => 'pending',
                        'created_at'     => date('Y-m-d H:i:s'),
                    );
                    if($this->Iuran_model->insert($data_iuran)) {
                        $berhasil++;
                    } else {
                        $gagal++;
                    }
                } else {
                    $gagal++;
                }
            }
            
            // Lanjut ke bulan berikutnya
            $current->modify('+1 month');
        }

        if($berhasil > 0) $this->session->set_flashdata('success', "Berhasil generate {$berhasil} tagihan iuran!");
        if($gagal > 0)    $this->session->set_flashdata('error', "{$gagal} tagihan dilewati (sudah ada atau gagal).");
        
        $this->User_model->log_activity($this->session->userdata('user_id'), 'create', "Generate massal iuran range periode: Berhasil $berhasil, Gagal $gagal");
        
        redirect('iuran');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── EDIT ────────────────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function edit($id) {
        require_admin();

        $data['iuran'] = $this->Iuran_model->get_by_id($id);
        if(!$data['iuran']) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan!');
            redirect('iuran');
        }

        if($this->input->post()) {
            $this->form_validation->set_rules('nominal', 'Nominal', 'required|numeric');
            if($this->form_validation->run()) {
                $update_data = array(
                    'nominal'    => $this->input->post('nominal'),
                    'keterangan' => $this->input->post('keterangan'),
                );
                if($this->Iuran_model->update($id, $update_data)) {
                    $this->session->set_flashdata('success', 'Data iuran berhasil diupdate!');
                    redirect('iuran');
                } else {
                    $this->session->set_flashdata('error', 'Gagal mengupdate data!');
                }
            }
        }

        $data['title'] = 'Edit Iuran';
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/edit', $data);
        $this->load->view('templates/footer');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── HAPUS ───────────────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function hapus($id) {
        require_admin();

        $iuran = $this->Iuran_model->get_by_id($id);
        if($iuran && $iuran->bukti_transfer) {
            if(file_exists('./uploads/iuran/' . $iuran->bukti_transfer)) {
                unlink('./uploads/iuran/' . $iuran->bukti_transfer);
            }
        }
        if($this->Iuran_model->delete($id)) {
            $this->session->set_flashdata('success', 'Data iuran berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus data!');
        }
        redirect('iuran');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── DETAIL ──────────────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function detail($id) {
        $iuran = $this->Iuran_model->get_by_id($id);
        if(!$iuran) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan!');
            redirect('iuran');
        }
        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            if($iuran->user_id != $user_id) {
                $this->session->set_flashdata('error', 'Anda tidak berhak melihat iuran ini!');
                redirect('iuran');
            }
        }

        $data['title'] = 'Detail Iuran';
        $data['iuran'] = $iuran;
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/detail', $data);
        $this->load->view('templates/footer');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── BAYAR MASSAL (Admin) ──────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function bayar_massal() {
        require_admin();

        $data['title']          = 'Pembayaran Iuran Massal';
        $data['tagihan']        = $this->Iuran_model->get_by_status('pending');
        $data['tagihan_arisan'] = $this->Iuran_model->get_arisan_iuran_pending();
        $data['kas_list']       = $this->Master_kas_model->get_aktif();

        $warga_map = [];
        foreach($data['tagihan'] as $t) {
            $warga_map[$t->warga_id] = $t->nama_lengkap;
        }
        foreach($data['tagihan_arisan'] as $t) {
            $warga_map[$t->warga_id] = $t->nama_lengkap;
        }
        asort($warga_map);
        $data['warga_map'] = $warga_map;

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/bayar_massal', $data);
        $this->load->view('templates/footer');
    }

    public function proses_bayar_massal() {
        require_admin();

        $tagihan_ids       = $this->input->post('tagihan_ids');
        $arisan_ids        = $this->input->post('arisan_ids');
        $metode_pembayaran = $this->input->post('metode_pembayaran');
        $master_kas_id     = $this->input->post('master_kas_id');

        if(empty($tagihan_ids) && empty($arisan_ids)) {
            $this->session->set_flashdata('error', 'Pilih minimal 1 tagihan untuk dibayar!');
            redirect('iuran/bayar_massal');
        }
        if(empty($master_kas_id)) {
            $this->session->set_flashdata('error', 'Pilih kas tujuan!');
            redirect('iuran/bayar_massal');
        }

        $kas = $this->Master_kas_model->get_by_id($master_kas_id);
        if(!$kas) {
            $this->session->set_flashdata('error', 'Kas tujuan tidak valid!');
            redirect('iuran/bayar_massal');
        }

        $this->load->model('Kas_model');
        $berhasil      = 0;
        $gagal         = 0;
        $total_nominal = 0;

        if(!empty($tagihan_ids)) {
            foreach($tagihan_ids as $id) {
                $iuran = $this->Iuran_model->get_by_id($id);
                if($iuran && $iuran->status === 'pending') {
                    $update_data = array(
                        'status'             => 'lunas',
                        'tanggal_bayar'      => date('Y-m-d H:i:s'),
                        'metode_pembayaran'  => $metode_pembayaran,
                        'diverifikasi_oleh'  => $this->session->userdata('user_id'),
                        'tanggal_verifikasi' => date('Y-m-d H:i:s'),
                        'keterangan'         => 'Pembayaran massal oleh admin',
                        'total_terbayar'     => $iuran->nominal,
                        'sisa_tagihan'       => 0,
                    );
                    if($this->Iuran_model->update($id, $update_data)) {
                        $this->_insert_kas($iuran, $master_kas_id, date('Y-m-d'), null);
                        $berhasil++;
                        $total_nominal += $iuran->nominal;
                    } else {
                        $gagal++;
                    }
                } else {
                    $gagal++;
                }
            }
        }

        if(!empty($arisan_ids)) {
            foreach($arisan_ids as $aid) {
                $this->db->select('ai.id, ai.nominal_bayar, ai.status_bayar, u.nama_lengkap, a.nama_arisan, ap.pertemuan_ke, ap.tanggal_pertemuan');
                $this->db->from('arisan_iuran ai');
                $this->db->join('warga w',            'w.id  = ai.warga_id');
                $this->db->join('users u',            'u.id  = w.user_id');
                $this->db->join('arisan_pertemuan ap','ap.id = ai.pertemuan_id');
                $this->db->join('arisan a',           'a.id  = ap.arisan_id');
                $this->db->where('ai.id', (int)$aid);
                $arisan_iuran = $this->db->get()->row();

                if($arisan_iuran && $arisan_iuran->status_bayar === 'belum') {
                    $ok = $this->db->update('arisan_iuran',
                        array(
                            'status_bayar'      => 'lunas',
                            'tanggal_bayar'     => date('Y-m-d'),
                            'metode_pembayaran' => $metode_pembayaran,
                        ),
                        array('id' => (int)$aid)
                    );
                    if($ok) {
                        $data_kas = array(
                            'master_kas_id' => $master_kas_id,
                            'tanggal'       => date('Y-m-d'),
                            'jenis'         => 'pemasukan',
                            'kategori'      => 'Arisan',
                            'keterangan'    => 'Iuran arisan ' . $arisan_iuran->nama_arisan
                                               . ' a.n. ' . $arisan_iuran->nama_lengkap
                                               . ' (Pertemuan Ke-' . $arisan_iuran->pertemuan_ke . ')',
                            'nominal'       => $arisan_iuran->nominal_bayar,
                            'bukti_dokumen' => null,
                            'input_oleh'    => $this->session->userdata('user_id'),
                            'created_at'    => date('Y-m-d H:i:s'),
                        );
                        $this->Kas_model->insert($data_kas);
                        $berhasil++;
                        $total_nominal += $arisan_iuran->nominal_bayar;
                    } else {
                        $gagal++;
                    }
                } else {
                    $gagal++;
                }
            }
        }

        if($berhasil > 0) {
            $this->Master_kas_model->update_saldo($master_kas_id);
            $this->session->set_flashdata('success',
                "Berhasil memproses {$berhasil} pembayaran dengan total Rp "
                . number_format($total_nominal, 0, ',', '.')
                . " masuk ke {$kas->nama}!");
        }
        if($gagal > 0) {
            $this->session->set_flashdata('error', "{$gagal} pembayaran gagal diproses.");
        }

        redirect('iuran');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── BAYAR PER WARGA (Admin) ────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function bayar_per_warga($warga_id = null) {
        require_admin();

        if(!$warga_id) {
            $this->session->set_flashdata('error', 'Warga tidak ditemukan!');
            redirect('iuran/bayar_massal');
        }

        $warga = $this->db->select('w.id, u.nama_lengkap, w.nik')
            ->from('warga w')
            ->join('users u', 'u.id = w.user_id')
            ->where('w.id', (int)$warga_id)
            ->get()->row();

        if(!$warga) {
            $this->session->set_flashdata('error', 'Warga tidak ditemukan!');
            redirect('iuran/bayar_massal');
        }

        $tagihan_rt = $this->Iuran_model->get_by_warga($warga_id);
        $tagihan_rt = array_filter((array)$tagihan_rt, function($t){ return $t->status === 'pending'; });

        $tagihan_arisan = $this->Iuran_model->get_arisan_iuran_pending_by_warga($warga_id);

        if(empty($tagihan_rt) && empty($tagihan_arisan)) {
            $this->session->set_flashdata('error', 'Tidak ada tagihan pending untuk warga ini!');
            redirect('iuran/bayar_massal');
        }

        $data['kas_list']       = $this->Master_kas_model->get_aktif();
        $data['warga']          = $warga;
        $data['tagihan_rt']     = $tagihan_rt;
        $data['tagihan_arisan'] = $tagihan_arisan;
        $data['title']          = 'Bayar Semua Tagihan: ' . $warga->nama_lengkap;

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/bayar_per_warga', $data);
        $this->load->view('templates/footer');
    }

    public function proses_bayar_per_warga() {
        require_admin();

        $warga_id          = $this->input->post('warga_id');
        $tagihan_ids       = $this->input->post('tagihan_ids')  ?: [];
        $arisan_ids        = $this->input->post('arisan_ids')   ?: [];
        $metode_pembayaran = $this->input->post('metode_pembayaran');
        $master_kas_id     = $this->input->post('master_kas_id');

        if(empty($tagihan_ids) && empty($arisan_ids)) {
            $this->session->set_flashdata('error', 'Pilih minimal 1 tagihan!');
            redirect('iuran/bayar_per_warga/' . $warga_id);
        }
        if(empty($master_kas_id)) {
            $this->session->set_flashdata('error', 'Pilih kas tujuan!');
            redirect('iuran/bayar_per_warga/' . $warga_id);
        }

        $kas = $this->Master_kas_model->get_by_id($master_kas_id);
        if(!$kas) {
            $this->session->set_flashdata('error', 'Kas tujuan tidak valid!');
            redirect('iuran/bayar_per_warga/' . $warga_id);
        }

        $this->load->model('Kas_model');
        $berhasil      = 0;
        $gagal         = 0;
        $total_nominal = 0;

        foreach($tagihan_ids as $id) {
            $iuran = $this->Iuran_model->get_by_id($id);
            if($iuran && $iuran->warga_id == $warga_id && $iuran->status === 'pending') {
                $update_data = array(
                    'status'             => 'lunas',
                    'tanggal_bayar'      => date('Y-m-d H:i:s'),
                    'metode_pembayaran'  => $metode_pembayaran,
                    'diverifikasi_oleh'  => $this->session->userdata('user_id'),
                    'tanggal_verifikasi' => date('Y-m-d H:i:s'),
                    'keterangan'         => 'Pembayaran massal per warga oleh admin',
                    'total_terbayar'     => $iuran->nominal,
                    'sisa_tagihan'       => 0,
                );
                if($this->Iuran_model->update($id, $update_data)) {
                    $this->_insert_kas($iuran, $master_kas_id, date('Y-m-d'), null);
                    $berhasil++;
                    $total_nominal += $iuran->nominal;
                } else {
                    $gagal++;
                }
            } else {
                $gagal++;
            }
        }

        foreach($arisan_ids as $aid) {
            $this->db->select('ai.id, ai.nominal_bayar, ai.status_bayar, u.nama_lengkap, a.nama_arisan, ap.pertemuan_ke');
            $this->db->from('arisan_iuran ai');
            $this->db->join('warga w',            'w.id  = ai.warga_id');
            $this->db->join('users u',            'u.id  = w.user_id');
            $this->db->join('arisan_pertemuan ap','ap.id = ai.pertemuan_id');
            $this->db->join('arisan a',           'a.id  = ap.arisan_id');
            $this->db->where('ai.id',       (int)$aid);
            $this->db->where('ai.warga_id', (int)$warga_id);
            $arisan_iuran = $this->db->get()->row();

            if($arisan_iuran && $arisan_iuran->status_bayar === 'belum') {
                $ok = $this->db->update('arisan_iuran',
                    array(
                        'status_bayar'      => 'lunas',
                        'tanggal_bayar'     => date('Y-m-d'),
                        'metode_pembayaran' => $metode_pembayaran,
                    ),
                    array('id' => (int)$aid)
                );
                if($ok) {
                    $data_kas = array(
                        'master_kas_id' => $master_kas_id,
                        'tanggal'       => date('Y-m-d'),
                        'jenis'         => 'pemasukan',
                        'kategori'      => 'Arisan',
                        'keterangan'    => 'Iuran arisan ' . $arisan_iuran->nama_arisan
                                           . ' a.n. ' . $arisan_iuran->nama_lengkap
                                           . ' (Pertemuan Ke-' . $arisan_iuran->pertemuan_ke . ')',
                        'nominal'       => $arisan_iuran->nominal_bayar,
                        'bukti_dokumen' => null,
                        'input_oleh'    => $this->session->userdata('user_id'),
                        'created_at'    => date('Y-m-d H:i:s'),
                    );
                    $this->Kas_model->insert($data_kas);
                    $berhasil++;
                    $total_nominal += $arisan_iuran->nominal_bayar;
                } else {
                    $gagal++;
                }
            } else {
                $gagal++;
            }
        }

        if($berhasil > 0) {
            $this->Master_kas_model->update_saldo($master_kas_id);
            $this->session->set_flashdata('success',
                "Berhasil memproses {$berhasil} pembayaran (Rp "
                . number_format($total_nominal, 0, ',', '.')
                . ") untuk warga ini masuk ke {$kas->nama}!");
        }
        if($gagal > 0) {
            $this->session->set_flashdata('error', "{$gagal} pembayaran gagal diproses.");
        }

        redirect('iuran/bayar_massal');
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── API AJAX: Cari tagihan warga ───────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    public function cari_tagihan_warga() {
        require_admin();
        header('Content-Type: application/json');

        $q = $this->input->get('q');
        if(strlen($q) < 2) {
            echo json_encode(['iuran_rt' => [], 'arisan' => [], 'warga_list' => []]);
            exit;
        }

        $warga_list = $this->db
            ->select('w.id as warga_id, u.nama_lengkap, w.nik')
            ->from('warga w')
            ->join('users u', 'u.id = w.user_id')
            ->like('u.nama_lengkap', $q)
            ->where('u.status', 'aktif')
            ->order_by('u.nama_lengkap', 'ASC')
            ->get()->result();

        if(empty($warga_list)) {
            echo json_encode(['iuran_rt' => [], 'arisan' => [], 'warga_list' => []]);
            exit;
        }

        $warga_ids = array_map(function($w){ return $w->warga_id; }, $warga_list);

        $this->db->select('pi.id, pi.warga_id, pi.nominal, u.nama_lengkap, w.nik, ji.nama_iuran, pi.periode_bulan, pi.periode_tahun');
        $this->db->from('pembayaran_iuran pi');
        $this->db->join('warga w', 'w.id = pi.warga_id');
        $this->db->join('users u', 'u.id = w.user_id');
        $this->db->join('jenis_iuran ji', 'ji.id = pi.jenis_iuran_id');
        $this->db->where('pi.status', 'pending');
        $this->db->where_in('pi.warga_id', $warga_ids);
        $iuran_rt = $this->db->get()->result();

        $this->db->select('ai.id, ai.warga_id, ai.nominal_bayar as nominal, u.nama_lengkap, w.nik, a.nama_arisan as nama_iuran, ap.pertemuan_ke, ap.tanggal_pertemuan');
        $this->db->from('arisan_iuran ai');
        $this->db->join('warga w',            'w.id  = ai.warga_id');
        $this->db->join('users u',            'u.id  = w.user_id');
        $this->db->join('arisan_pertemuan ap','ap.id = ai.pertemuan_id');
        $this->db->join('arisan a',           'a.id  = ap.arisan_id');
        $this->db->where('ai.status_bayar', 'belum');
        $this->db->where_in('ai.warga_id', $warga_ids);
        $iuran_arisan = $this->db->get()->result();

        echo json_encode([
            'warga_list' => $warga_list,
            'iuran_rt'   => $iuran_rt,
            'arisan'     => $iuran_arisan,
        ]);
        exit;
    }

    // ═══════════════════════════════════════════════════════════════════════
    // ─── HELPERS ────────────────────────────────────────────────────────────
    // ═══════════════════════════════════════════════════════════════════════

    /**
     * Insert pemasukan KAS untuk pembayaran LUNAS penuh
     * (menggunakan $iuran->nominal sebagai nominal)
     */
    private function _insert_kas($iuran, $master_kas_id, $tanggal, $bukti_file = null) {
        $this->load->model('Kas_model');
        $bulan_nama = ['','Januari','Februari','Maret','April','Mei','Juni',
                       'Juli','Agustus','September','Oktober','November','Desember'];
        $data_kas = array(
            'master_kas_id' => $master_kas_id,
            'tanggal'       => $tanggal,
            'jenis'         => 'pemasukan',
            'kategori'      => 'Iuran',
            'keterangan'    => 'Pembayaran ' . $iuran->nama_iuran
                               . ' a.n. ' . $iuran->nama_lengkap
                               . ' periode ' . $bulan_nama[(int)$iuran->periode_bulan]
                               . ' ' . $iuran->periode_tahun,
            'nominal'       => $iuran->nominal,
            'bukti_dokumen' => $bukti_file,
            'input_oleh'    => $this->session->userdata('user_id'),
            'created_at'    => date('Y-m-d H:i:s'),
        );
        $this->Kas_model->insert($data_kas);
    }

    /**
     * Insert pemasukan KAS untuk CICILAN
     * (menggunakan $nominal tertentu, bukan nominal penuh)
     */
    private function _insert_kas_nominal($iuran, $master_kas_id, $tanggal, $nominal, $ke, $bukti_file = null) {
        $this->load->model('Kas_model');
        $bulan_nama = ['','Januari','Februari','Maret','April','Mei','Juni',
                       'Juli','Agustus','September','Oktober','November','Desember'];
        $data_kas = array(
            'master_kas_id' => $master_kas_id,
            'tanggal'       => $tanggal,
            'jenis'         => 'pemasukan',
            'kategori'      => 'Iuran Cicilan',
            'keterangan'    => 'Cicilan ke-' . $ke . ' ' . $iuran->nama_iuran
                               . ' a.n. ' . $iuran->nama_lengkap
                               . ' periode ' . $bulan_nama[(int)$iuran->periode_bulan]
                               . ' ' . $iuran->periode_tahun,
            'nominal'       => $nominal,
            'bukti_dokumen' => $bukti_file,
            'input_oleh'    => $this->session->userdata('user_id'),
            'created_at'    => date('Y-m-d H:i:s'),
        );
        $this->Kas_model->insert($data_kas);
    }



    // ═══════════════════════════════════════════════════════════════════════
// ─── Statistik
// ═══════════════════════════════════════════════════════════════════════
 
    public function statistik() {
        if(cannot('iuran', 'view')) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses ke halaman ini!');
            redirect('dashboard');
        }
 
        // ── Kumpulkan filter dari GET ──────────────────────────────────
        $filter = [
            'status'         => $this->input->get('status'),
            'bulan'          => $this->input->get('bulan'),
            'tahun'          => $this->input->get('tahun'),
            'jenis_iuran_id' => $this->input->get('jenis_iuran_id'),
            'nama'           => $this->input->get('nama'), // admin only
        ];
 
        // Buang filter kosong agar tidak ikut di-WHERE
        $filter = array_filter($filter, function($v){ return $v !== '' && $v !== null; });
 
        // ── Ambil data ────────────────────────────────────────────────
        if(is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $data['iuran_list'] = $this->Iuran_model->get_by_user($user_id, $filter);
        } else {
            $data['iuran_list'] = $this->Iuran_model->get_all($filter);
        }
 
        $data['title']            = 'Statistik Iuran';
        $data['filter']           = $filter;
        $data['jenis_iuran_list'] = $this->Iuran_model->get_jenis_iuran();
 
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('iuran/statistik_iuran', $data);
        $this->load->view('templates/footer');
    }

    // ══════════════════════════════════════════════════════════════════════
    // ─── AJAX: Kirim Tagihan Iuran via WAHA WhatsApp ──────────────────────
    // POST: iuran/kirim_tagihan_wa
    // Body: { iuran_id: 123 }
    // ══════════════════════════════════════════════════════════════════════
    public function kirim_tagihan_wa() {
        if (!is_admin()) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'msg' => 'Akses ditolak.']));
        }

        if (!$this->input->is_ajax_request()) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'msg' => 'Invalid request.']));
        }

        $iuran_id = (int)$this->input->post('iuran_id');
        if (!$iuran_id) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'msg' => 'ID iuran tidak valid.']));
        }

        $iuran = $this->Iuran_model->get_by_id($iuran_id);
        if (!$iuran) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'msg' => 'Data iuran tidak ditemukan.']));
        }

        // Ambil no HP dari user warga
        $no_hp = null;
        if (!empty($iuran->user_id)) {
            $user = $this->db->select('no_hp')->where('id', $iuran->user_id)->get('users')->row();
            $no_hp = $user->no_hp ?? null;
        }

        if (empty($no_hp)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'msg' => 'Warga tidak memiliki nomor HP yang terdaftar.']));
        }

        $this->load->library('waha_lib');

        if (!$this->waha_lib->is_enabled()) {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'msg' => 'WAHA belum diaktifkan. Atur di menu Pengaturan → tab WhatsApp.']));
        }

        $this->load->model('Pengaturan_model');
        $p = $this->Pengaturan_model->get();
        $nama_rt = trim(($p->nama_rt ?? 'RT') . ' ' . ($p->nama_rw ?? ''));

        $bulan_nama = ['','Januari','Februari','Maret','April','Mei','Juni',
                       'Juli','Agustus','September','Oktober','November','Desember'];

        $nominal        = (float)($iuran->nominal ?? 0);
        $total_terbayar = (float)($iuran->total_terbayar ?? 0);
        $sisa           = $nominal - $total_terbayar;
        $periode        = ($bulan_nama[(int)($iuran->periode_bulan ?? 0)] ?? '') . ' ' . ($iuran->periode_tahun ?? '');
        $status         = $iuran->status ?? 'pending';

        if ($status === 'lunas') {
            return $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['status' => 'error', 'msg' => 'Tagihan ini sudah lunas, tidak perlu ditagih.']));
        }

        if ($status === 'cicil') {
            $nominal_str = 'Sisa tagihan: *Rp ' . number_format($sisa, 0, ',', '.') . '*';
        } else {
            $nominal_str = 'Nominal: *Rp ' . number_format($nominal, 0, ',', '.') . '*';
        }

        $pesan = "Assalamu'alaikum Bpk/Ibu *{$iuran->nama_lengkap}*,\n\n"
               . "Kami dari pengurus *{$nama_rt}* mengingatkan kewajiban:\n\n"
               . "📋 *{$iuran->nama_iuran}*\n"
               . "📅 Periode: *{$periode}*\n"
               . "💰 {$nominal_str}\n\n"
               . "Mohon segera diselesaikan pembayarannya. Terima kasih atas perhatian dan kerjasamanya. 🙏\n\n"
               . "_Pengurus {$nama_rt}_";

        $result = $this->waha_lib->send($no_hp, $pesan);

        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode([
                'status' => $result['success'] ? 'ok'    : 'error',
                'msg'    => $result['success'] ? 'Pesan tagihan berhasil dikirim ke ' . $iuran->nama_lengkap . '!' : $result['message'],
            ]));
    }


    public function cetak($id) {
    $iuran = $this->Iuran_model->get_by_id($id);
    if(!$iuran) show_404();

    if(is_warga()) {
        $user_id = $this->session->userdata('user_id');
        if($iuran->user_id != $user_id) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('iuran');
        }
    }

    $data['title'] = 'Cetak Bukti Iuran';
    $data['iuran'] = $iuran;
    $data['cicilan'] = $this->Iuran_model->get_cicilan_by_iuran($id);

    $this->load->view('iuran/cetak_iuran', $data);
}

 
}
