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

class Pinjaman extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        $this->load->model([
            'Pinjaman_model',
            'Warga_model',
            'Jenis_pinjaman_model',
            'Kas_model',
            'Master_kas_model',
            'Tabungan_model'
        ]);
        $this->load->library('form_validation');
        $this->load->helper('authorization');
    }

 // ==================== DASHBOARD ====================
public function index() {
    $data['title'] = 'Manajemen Pinjaman';

    if (is_warga()) {
        $user_id = $this->session->userdata('user_id');
        $warga   = $this->Warga_model->get_by_user_id($user_id);
        if (!$warga) {
            $this->session->set_flashdata('error', 'Data warga tidak ditemukan!');
            redirect('dashboard');
        }$data['total_pinjaman_aktif']    = $this->Pinjaman_model->count_pinjaman_aktif_by_warga($warga->id);
        $data['total_pengajuan_pending'] = $this->Pinjaman_model->count_pengajuan_pending_by_warga($warga->id);
        $data['total_piutang']           = $this->Pinjaman_model->get_total_piutang_by_warga($warga->id);
        $data['angsuran_bulan_ini']      = $this->Pinjaman_model->get_angsuran_bulan_ini_by_warga($warga->id);
        $data['pinjaman_macet']          = $this->Pinjaman_model->get_pinjaman_macet_by_warga($warga->id);
        
    } else {
        // ========== DATA UNTUK ADMIN ==========
        
        $data['total_pinjaman_aktif']    = $this->Pinjaman_model->count_pinjaman_aktif();
        $data['total_pengajuan_pending'] = $this->Pinjaman_model->count_pengajuan_pending();
        $data['total_piutang']           = $this->Pinjaman_model->get_total_piutang();
        $data['angsuran_bulan_ini']      = $this->Pinjaman_model->get_angsuran_bulan_ini();
        $data['pinjaman_macet']          = $this->Pinjaman_model->get_pinjaman_macet();
        
        // ============================================================
        // TAMBAHAN INI: Data pembayaran pending untuk notifikasi
        // ============================================================
        $data['total_pending_verifikasi'] = $this->Pinjaman_model->count_pembayaran_pending();
        $data['pending_payments_global']  = $this->Pinjaman_model->get_pembayaran_pending_terbaru(5);
    }

    $this->load->view('templates/header', $data);
    $this->load->view('templates/sidebar', $data);
    $this->load->view('pinjaman/dashboard', $data);  // atau 'pinjaman/index' tergantung nama view Anda
    $this->load->view('templates/footer');
}

    // ==================== PENGAJUAN ====================
    public function pengajuan() {
        $data['title'] = is_warga() ? 'Pengajuan Pinjaman Saya' : 'Pengajuan Pinjaman';

        if (is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $warga   = $this->Warga_model->get_by_user_id($user_id);
            if (!$warga) {
                $this->session->set_flashdata('error', 'Data warga tidak ditemukan!');
                redirect('dashboard');
            }
            $data['pengajuan'] = $this->Pinjaman_model->get_pengajuan_by_warga($warga->id);
        } else {
            $data['pengajuan'] = $this->Pinjaman_model->get_all_pengajuan();
        }

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

    public function ajukan() {
        $data['title']          = 'Form Pengajuan Pinjaman';
        $data['jenis_pinjaman'] = $this->Jenis_pinjaman_model->get_all();

        if (is_warga()) {
            $user_id            = $this->session->userdata('user_id');
            $data['warga_saya'] = $this->Warga_model->get_by_user_id($user_id);
            if (!$data['warga_saya']) {
                $this->session->set_flashdata('error', 'Data warga tidak ditemukan!');
                redirect('pinjaman');
            }
        } else {
            $data['warga'] = $this->Warga_model->get_all();
        }

        $this->form_validation->set_rules('jenis_pinjaman_id', 'Jenis Pinjaman', 'required');
        $this->form_validation->set_rules('nominal_pengajuan', 'Nominal', 'required|numeric|greater_than[0]');
        $this->form_validation->set_rules('tenor', 'Tenor', 'required|numeric|greater_than[0]');
        $this->form_validation->set_rules('keperluan', 'Keperluan', 'required');
        if (is_admin()) {
            $this->form_validation->set_rules('warga_id', 'Warga', 'required');
        }

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('pinjaman/ajukan', $data);
            $this->load->view('templates/footer');
        } else {
            $warga_id           = is_warga() ? $data['warga_saya']->id : $this->input->post('warga_id');
            $jenis              = $this->Jenis_pinjaman_model->get_by_id($this->input->post('jenis_pinjaman_id'));
            $nominal            = (float)$this->input->post('nominal_pengajuan');
            $tenor              = (int)$this->input->post('tenor');
            $bunga              = (float)$jenis->bunga_persen;
            $bunga_total        = ($nominal * $bunga / 100) * $tenor;
            $total_pinjaman     = $nominal + $bunga_total;
            $angsuran_per_bulan = $total_pinjaman / $tenor;
            $kode_pengajuan     = 'PGJ-' . date('Ymd') . '-' . rand(100, 999);

            $this->Pinjaman_model->insert_pengajuan([
                'kode_pengajuan'     => $kode_pengajuan,
                'warga_id'           => $warga_id,
                'jenis_pinjaman_id'  => $this->input->post('jenis_pinjaman_id'),
                'nominal_pengajuan'  => $nominal,
                'tenor'              => $tenor,
                'bunga_persen'       => $bunga,
                'total_pinjaman'     => $total_pinjaman,
                'angsuran_per_bulan' => $angsuran_per_bulan,
                'keperluan'          => $this->input->post('keperluan'),
                'jaminan'            => $this->input->post('jaminan'),
                'status_pengajuan'   => 'pending',
                'tanggal_pengajuan'  => date('Y-m-d'),
            ]);

            $this->session->set_flashdata('success', 'Pengajuan berhasil dengan kode: ' . $kode_pengajuan);
            redirect('pinjaman/pengajuan');
        }
    }

    // ==================== PROSES PENGAJUAN ====================
    public function proses_pengajuan($id) {
        if (is_warga()) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('pinjaman');
        }

        $pengajuan = $this->Pinjaman_model->get_pengajuan_by_id($id);
        if (!$pengajuan) {
            $this->session->set_flashdata('error', 'Data pengajuan tidak ditemukan!');
            redirect('pinjaman/pengajuan');
        }

        if ($pengajuan->status_pengajuan !== 'pending') {
            $this->session->set_flashdata('error', 'Pengajuan ini sudah diproses!');
            redirect('pinjaman/pengajuan');
        }

        $data['title']     = 'Proses Pengajuan';
        $data['pengajuan'] = $pengajuan;
        $data['warga']     = $this->Warga_model->get_by_id($pengajuan->warga_id);
        $data['jenis']     = $this->Jenis_pinjaman_model->get_by_id($pengajuan->jenis_pinjaman_id);

        $kas_tabungan_list    = $this->Master_kas_model->get_ringkasan_saldo_tabungan();
        $kas_operasional_list = $this->Master_kas_model->get_ringkasan_saldo_operasional();
        $total_saldo_tabungan = array_sum(array_column((array)$kas_tabungan_list, 'saldo_realtime'));

        $nominal_cair  = $pengajuan->nominal_pengajuan;
        $dari_tabungan = min($nominal_cair, max(0, $total_saldo_tabungan));
        $dari_kas_rt   = $nominal_cair - $dari_tabungan;

        $total_saldo_rt = 0;
        foreach ($kas_operasional_list as $k) {
            $total_saldo_rt += max(0, $k->saldo_realtime);
        }
        $total_tersedia = max(0, $total_saldo_tabungan) + $total_saldo_rt;
        $dana_mencukupi = $total_tersedia >= $nominal_cair;

        $cek_dana = [
            'mencukupi'      => $dana_mencukupi,
            'total_tersedia' => $total_tersedia,
            'total_tabungan' => $total_saldo_tabungan,
            'total_rt'       => $total_saldo_rt,
            'kekurangan'     => max(0, $nominal_cair - $total_tersedia),
        ];

        $data['kas_tabungan_list']    = $kas_tabungan_list;
        $data['kas_operasional_list'] = $kas_operasional_list;
        $data['total_saldo_tabungan'] = $total_saldo_tabungan;
        $data['preview_dari_tabungan']= $dari_tabungan;
        $data['preview_dari_kas_rt']  = $dari_kas_rt;
        $data['cek_dana']             = $cek_dana;
        $data['dana_mencukupi']       = $dana_mencukupi;

        if ($this->input->post()) {
            $status   = $this->input->post('status_pengajuan');
            $admin_id = $this->session->userdata('user_id');

            if ($status == 'disetujui') {
                if (!$dana_mencukupi) {
                    $this->session->set_flashdata('error',
                        'Dana tidak mencukupi! Kekurangan: Rp ' .
                        number_format($cek_dana['kekurangan'], 0, ',', '.') .
                        '. Tambah saldo kas terlebih dahulu.'
                    );
                    redirect('pinjaman/proses_pengajuan/' . $id);
                }

                $mode         = $this->input->post('mode_pencairan') ?: 'auto';
                $sumber_dana  = [];

                if ($mode === 'auto') {
                    $sumber_dana = $this->_hitung_sumber_dana_otomatis($nominal_cair);
                } else {
                    $kas_ids      = $this->input->post('kas_id')      ?: [];
                    $kas_nominals = $this->input->post('kas_nominal')  ?: [];
                    $total_manual = 0;

                    foreach ($kas_ids as $idx => $kas_id) {
                        $nom = (float)($kas_nominals[$idx] ?? 0);
                        if ($kas_id && $nom > 0) {
                            $sumber_dana[] = ['kas_id' => $kas_id, 'nominal' => $nom];
                            $total_manual += $nom;
                        }
                    }

                    if (abs($total_manual - $nominal_cair) > 1) {
                        $this->session->set_flashdata('error',
                            'Total pencairan manual tidak sesuai! ' .
                            'Target: Rp ' . number_format($nominal_cair, 0, ',', '.') .
                            ', Total input: Rp ' . number_format($total_manual, 0, ',', '.')
                        );
                        redirect('pinjaman/proses_pengajuan/' . $id);
                    }

                    foreach ($sumber_dana as $item) {
                        $saldo_kas = $this->Master_kas_model->hitung_saldo($item['kas_id']);
                        if ($saldo_kas < $item['nominal']) {
                            $kas_info = $this->Master_kas_model->get_by_id($item['kas_id']);
                            $this->session->set_flashdata('error',
                                'Saldo kas ' . $kas_info->kode . ' tidak mencukupi! ' .
                                'Saldo tersedia: Rp ' . number_format(max(0,$saldo_kas), 0, ',', '.')
                            );
                            redirect('pinjaman/proses_pengajuan/' . $id);
                        }
                    }
                }

                if (empty($sumber_dana)) {
                    $this->session->set_flashdata('error', 'Tidak ada kas tersedia untuk pencairan!');
                    redirect('pinjaman/proses_pengajuan/' . $id);
                }

                $this->db->trans_start();

                $this->Pinjaman_model->update_pengajuan($id, [
                    'status_pengajuan'  => 'disetujui',
                    'disetujui_oleh'    => $admin_id,
                    'tanggal_disetujui' => date('Y-m-d'),
                ]);

                $kode_pinjaman = 'PJM-' . date('Ymd') . '-' . rand(1000, 9999);

                $pinjaman_id = $this->Pinjaman_model->insert_pinjaman([
                    'kode_pinjaman'      => $kode_pinjaman,
                    'pengajuan_id'       => $id,
                    'warga_id'           => $pengajuan->warga_id,
                    'nominal_disetujui'  => $nominal_cair,
                    'bunga_total'        => $pengajuan->total_pinjaman - $nominal_cair,
                    'total_pinjaman'     => $pengajuan->total_pinjaman,
                    'tenor'              => $pengajuan->tenor,
                    'angsuran_per_bulan' => $pengajuan->angsuran_per_bulan,
                    'sisa_pinjaman'      => $pengajuan->total_pinjaman,
                    'sisa_tenor'         => $pengajuan->tenor,
                    'status_pinjaman'    => 'aktif',
                    'sudah_diterima'     => 'ya',
                    'tanggal_pencairan'  => date('Y-m-d'),
                ]);

                $this->_generate_jadwal_angsuran($pinjaman_id, $pengajuan);

                $nama_warga = $data['warga']->nama_lengkap;
                $mode_text  = strtoupper($mode);
                $msg_detail = [];

                foreach ($sumber_dana as $item) {
                    if ($item['nominal'] <= 0) continue;
                    $kas_info = $this->Master_kas_model->get_by_id($item['kas_id']);

                    $this->db->insert('kas_rt', [
                        'tanggal'       => date('Y-m-d'),
                        'jenis'         => 'pengeluaran',
                        'kategori'      => 'Pencairan Pinjaman',
                        'master_kas_id' => $item['kas_id'],
                        'nominal'       => $item['nominal'],
                        'keterangan'    => sprintf(
                            'Pencairan pinjaman %s a.n. %s dari kas %s (%s) - Mode: %s',
                            $kode_pinjaman, $nama_warga,
                            $kas_info->kode, $kas_info->nama, $mode_text
                        ),
                        'input_oleh'    => $admin_id,
                    ]);

                    $this->Master_kas_model->update_saldo($item['kas_id']);
                    $msg_detail[] = $kas_info->kode . ': Rp ' . number_format($item['nominal'], 0, ',', '.');
                }

                $this->db->trans_complete();

                if ($this->db->trans_status()) {
                    $this->session->set_flashdata('success',
                        'Pengajuan disetujui (' . $mode_text . '). ' .
                        'Kode Pinjaman: <strong>' . $kode_pinjaman . '</strong>. ' .
                        'Dana dicairkan dari: ' . implode(', ', $msg_detail)
                    );
                } else {
                    $this->session->set_flashdata('error', 'Gagal memproses persetujuan. Silakan coba lagi.');
                }

            } else {
                $keterangan = $this->input->post('keterangan_penolakan');
                if (empty(trim($keterangan))) {
                    $this->session->set_flashdata('error', 'Alasan penolakan wajib diisi!');
                    redirect('pinjaman/proses_pengajuan/' . $id);
                }

                $this->Pinjaman_model->update_pengajuan($id, [
                    'status_pengajuan'     => 'ditolak',
                    'keterangan_penolakan' => $keterangan,
                    'disetujui_oleh'       => $admin_id,
                    'tanggal_disetujui'    => date('Y-m-d'),
                ]);
                $this->session->set_flashdata('success', 'Pengajuan berhasil ditolak.');
            }

            redirect('pinjaman/pengajuan');
        }

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

    // ==================== HELPER PRIVATE ====================
    private function _hitung_sumber_dana_otomatis($nominal_cair) {
        $sisa  = $nominal_cair;
        $hasil = [];

        $kas_tab = $this->Master_kas_model->get_ringkasan_saldo_tabungan();
        usort($kas_tab, fn($a, $b) => $b->saldo_realtime - $a->saldo_realtime);

        foreach ($kas_tab as $kas) {
            if ($sisa <= 0) break;
            $tersedia = max(0, $kas->saldo_realtime);
            if ($tersedia > 0) {
                $ambil   = min($sisa, $tersedia);
                $hasil[] = ['kas_id' => $kas->id, 'nominal' => $ambil];
                $sisa   -= $ambil;
            }
        }

        if ($sisa > 0) {
            $kas_rt = $this->Master_kas_model->get_ringkasan_saldo_operasional();
            usort($kas_rt, function($a, $b) {
                if (strtoupper($a->kode) === 'TUNAI') return -1;
                if (strtoupper($b->kode) === 'TUNAI') return  1;
                return $b->saldo_realtime - $a->saldo_realtime;
            });

            foreach ($kas_rt as $kas) {
                if ($sisa <= 0) break;
                $tersedia = max(0, $kas->saldo_realtime);
                if ($tersedia > 0) {
                    $ambil   = min($sisa, $tersedia);
                    $hasil[] = ['kas_id' => $kas->id, 'nominal' => $ambil];
                    $sisa   -= $ambil;
                }
            }
        }

        return $hasil;
    }

    private function _generate_jadwal_angsuran($pinjaman_id, $pengajuan) {
        for ($i = 1; $i <= $pengajuan->tenor; $i++) {
            $bulan = date('Y-m', strtotime(date('Y-m-d') . " +{$i} months"));
            $this->Pinjaman_model->insert_angsuran([
                'pinjaman_id'         => $pinjaman_id,
                'angsuran_ke'         => $i,
                'tanggal_jatuh_tempo' => $bulan . '-05',
                'nominal_angsuran'    => $pengajuan->angsuran_per_bulan,
                'total_bayar'         => $pengajuan->angsuran_per_bulan,
                'status_bayar'        => 'belum',
            ]);
        }
    }

    // ==================== DATA PINJAMAN ====================
    public function data_pinjaman() {
        $data['title'] = is_warga() ? 'Pinjaman Saya' : 'Data Pinjaman Aktif';

        if (is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $warga   = $this->Warga_model->get_by_user_id($user_id);
            if (!$warga) {
                $this->session->set_flashdata('error', 'Data warga tidak ditemukan!');
                redirect('dashboard');
            }
            $data['pinjaman'] = $this->Pinjaman_model->get_pinjaman_by_warga($warga->id);
        } else {
            $data['pinjaman'] = $this->Pinjaman_model->get_pinjaman_aktif();
        }

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

    // ==================== DETAIL PINJAMAN ====================
    public function detail($id) {
        $data['title']    = 'Detail Pinjaman';
        $data['pinjaman'] = $this->Pinjaman_model->get_pinjaman_by_id($id);

        if (!$data['pinjaman']) {
            $this->session->set_flashdata('error', 'Data pinjaman tidak ditemukan!');
            redirect('pinjaman/data_pinjaman');
        }

        if (is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $warga   = $this->Warga_model->get_by_user_id($user_id);
            if (!$warga || $data['pinjaman']->warga_id != $warga->id) {
                $this->session->set_flashdata('error', 'Akses ditolak!');
                redirect('pinjaman');
            }
        }

        $data['warga']         = $this->Warga_model->get_by_id($data['pinjaman']->warga_id);
        $data['angsuran']      = $this->Pinjaman_model->get_angsuran_by_pinjaman($id);
        $data['riwayat_bayar'] = $this->Pinjaman_model->get_riwayat_pembayaran($id);
        
        // Data tambahan untuk warga
        if (is_warga()) {
            $data['sisa_angsuran_count'] = $this->Pinjaman_model->count_sisa_angsuran($id);
            $data['total_sisa_bayar'] = 0;
            foreach($data['angsuran'] as $a) {
                if($a->status_bayar == 'belum') {
                    $data['total_sisa_bayar'] += $a->nominal_angsuran;
                }
            }
            // Cek pending payment
            $data['pending_payments'] = $this->Pinjaman_model->get_pembayaran_pending_by_pinjaman($id);
        }

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

    // ==================== PENCAIRAN MANUAL ====================
    public function pencairan($id) {
        if (is_warga()) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('pinjaman');
        }

        $pinjaman = $this->Pinjaman_model->get_pinjaman_by_id($id);

        if ($pinjaman->sudah_diterima == 'ya') {
            $this->session->set_flashdata('error', 'Pinjaman sudah pernah dicairkan.');
            redirect('pinjaman/detail/' . $id);
        }

        $nominal_cair    = $pinjaman->nominal_disetujui;
        $kas_tabungan    = $this->Master_kas_model->get_ringkasan_saldo_tabungan();
        $kas_operasional = $this->Master_kas_model->get_ringkasan_saldo_operasional();

        $total_saldo_tabungan = array_sum(array_column((array)$kas_tabungan, 'saldo_realtime'));
        $dari_tabungan        = min($nominal_cair, max(0, $total_saldo_tabungan));
        $dari_kas_rt          = $nominal_cair - $dari_tabungan;

        usort($kas_tabungan, fn($a, $b) => $b->saldo_realtime - $a->saldo_realtime);
        $kas_tabungan_dipilih = !empty($kas_tabungan) ? $kas_tabungan[0] : null;

        $kas_rt_dipilih = null;
        foreach ($kas_operasional as $k) {
            if (strtoupper($k->kode) === 'TUNAI') { $kas_rt_dipilih = $k; break; }
        }
        if (!$kas_rt_dipilih && !empty($kas_operasional)) $kas_rt_dipilih = $kas_operasional[0];

        $data['title']                = 'Proses Pencairan Pinjaman';
        $data['pinjaman']             = $pinjaman;
        $data['kas_tabungan']         = $kas_tabungan;
        $data['kas_operasional']      = $kas_operasional;
        $data['kas_tabungan_dipilih'] = $kas_tabungan_dipilih;
        $data['kas_rt_dipilih']       = $kas_rt_dipilih;
        $data['dari_tabungan']        = $dari_tabungan;
        $data['dari_kas_rt']          = $dari_kas_rt;
        $data['total_saldo_tabungan'] = $total_saldo_tabungan;

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

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

        $pinjaman = $this->Pinjaman_model->get_pinjaman_by_id($id);

        if ($pinjaman->sudah_diterima == 'ya') {
            $this->session->set_flashdata('error', 'Pinjaman sudah pernah dicairkan.');
            redirect('pinjaman/detail/' . $id);
        }

        $kas_tabungan_id  = $this->input->post('kas_tabungan_id') ?: null;
        $nominal_tabungan = (float)($this->input->post('nominal_dari_tabungan') ?: 0);
        $kas_rt_id        = $this->input->post('kas_rt_id') ?: null;
        $nominal_kas_rt   = (float)($this->input->post('nominal_dari_kas_rt') ?: 0);
        $admin_id         = $this->session->userdata('user_id');
        $nama_warga       = $pinjaman->nama_lengkap;

        $total = $nominal_tabungan + $nominal_kas_rt;
        if (abs($total - $pinjaman->nominal_disetujui) > 1) {
            $this->session->set_flashdata('error', 'Total sumber dana tidak sesuai nominal pencairan.');
            redirect('pinjaman/pencairan/' . $id);
        }

        $this->db->trans_start();

        $this->Pinjaman_model->update_pinjaman($id, [
            'sudah_diterima'        => 'ya',
            'tanggal_pencairan'     => date('Y-m-d'),
            'kas_tabungan_id'       => $kas_tabungan_id,
            'nominal_dari_tabungan' => $nominal_tabungan,
            'kas_rt_id'             => $kas_rt_id,
            'nominal_dari_kas_rt'   => $nominal_kas_rt,
        ]);

        if ($kas_tabungan_id && $nominal_tabungan > 0) {
            $this->db->insert('kas_rt', [
                'tanggal'       => date('Y-m-d'),
                'jenis'         => 'pengeluaran',
                'kategori'      => 'Pencairan Pinjaman',
                'master_kas_id' => $kas_tabungan_id,
                'nominal'       => $nominal_tabungan,
                'keterangan'    => 'Pencairan pinjaman ' . $pinjaman->kode_pinjaman . ' a.n. ' . $nama_warga . ' (dari kas tabungan)',
                'input_oleh'    => $admin_id,
            ]);
            $this->Master_kas_model->update_saldo($kas_tabungan_id);
        }

        if ($kas_rt_id && $nominal_kas_rt > 0) {
            $this->db->insert('kas_rt', [
                'tanggal'       => date('Y-m-d'),
                'jenis'         => 'pengeluaran',
                'kategori'      => 'Pencairan Pinjaman',
                'master_kas_id' => $kas_rt_id,
                'nominal'       => $nominal_kas_rt,
                'keterangan'    => 'Pencairan pinjaman ' . $pinjaman->kode_pinjaman . ' a.n. ' . $nama_warga . ' (dari kas RT)',
                'input_oleh'    => $admin_id,
            ]);
            $this->Master_kas_model->update_saldo($kas_rt_id);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status()) {
            $this->session->set_flashdata('success',
                'Pencairan berhasil. Tabungan: Rp ' . number_format($nominal_tabungan, 0, ',', '.') .
                ', Kas RT: Rp ' . number_format($nominal_kas_rt, 0, ',', '.')
            );
        } else {
            $this->session->set_flashdata('error', 'Gagal memproses pencairan.');
        }

        redirect('pinjaman/detail/' . $id);
    }

    // ==================== BAYAR ANGSURAN ====================
    // Method untuk menampilkan form pembayaran (digunakan warga dan admin)
    public function bayar_angsuran($angsuran_id) {
        // Cek akses
        $angsuran = $this->Pinjaman_model->get_angsuran_by_id($angsuran_id);
        if (!$angsuran) {
            $this->session->set_flashdata('error', 'Data angsuran tidak ditemukan!');
            redirect('pinjaman');
        }
        
        $pinjaman = $this->Pinjaman_model->get_pinjaman_by_id($angsuran->pinjaman_id);
        
        // Validasi akses warga
        if (is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $warga = $this->Warga_model->get_by_user_id($user_id);
            if (!$warga || $pinjaman->warga_id != $warga->id) {
                $this->session->set_flashdata('error', 'Akses ditolak!');
                redirect('pinjaman');
            }
        }
        
        // Cek status angsuran
        if ($angsuran->status_bayar == 'dibayar') {
            $this->session->set_flashdata('error', 'Angsuran ini sudah dibayar!');
            redirect('pinjaman/detail/' . $pinjaman->id);
        }

        $data['title'] = is_warga() ? 'Pembayaran Angsuran Online' : 'Input Pembayaran Angsuran';
        $data['angsuran'] = $angsuran;
        $data['pinjaman'] = $pinjaman;
        $data['warga'] = $this->Warga_model->get_by_id($pinjaman->warga_id);
        $data['kas_list'] = $this->Master_kas_model->get_aktif();

        // Hitung denda
        $denda = 0;
        $today = date('Y-m-d');
        if ($today > $angsuran->tanggal_jatuh_tempo) {
            $telat = (strtotime($today) - strtotime($angsuran->tanggal_jatuh_tempo)) / 86400;
            $jenis = $this->Jenis_pinjaman_model->get_by_id($pinjaman->jenis_pinjaman_id);
            $denda = ($angsuran->nominal_angsuran * ($jenis->denda_persen ?? 0) / 100) * $telat;
        }
        $data['denda'] = $denda;
        $data['total_bayar'] = $angsuran->nominal_angsuran + $denda;

        // Cek pending payment untuk warga
        if (is_warga()) {
            $data['pending_exists'] = $this->Pinjaman_model->get_pending_by_angsuran($angsuran_id);
        }

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

    // Method untuk warga submit pembayaran (transfer dengan bukti)
  public function submit_pembayaran_warga() {
    if (!is_warga()) {
        $this->session->set_flashdata('error', 'Akses ditolak!');
        redirect('pinjaman');
    }

    $user_id = $this->session->userdata('user_id');
    $warga = $this->Warga_model->get_by_user_id($user_id);
    
    $angsuran_id = $this->input->post('angsuran_id');
    $angsuran = $this->Pinjaman_model->get_angsuran_by_id($angsuran_id);
    $pinjaman = $this->Pinjaman_model->get_pinjaman_by_id($angsuran->pinjaman_id);
    
    // Validasi kepemilikan
    if ($pinjaman->warga_id != $warga->id) {
        $this->session->set_flashdata('error', 'Akses ditolak!');
        redirect('pinjaman');
    }

    // Konfigurasi upload
    $config['upload_path'] = './uploads/bukti_transfer/';
    $config['allowed_types'] = 'jpg|jpeg|png|pdf';
    $config['max_size'] = 2048;
    $config['file_name'] = 'BUKTI_' . time() . '_' . $angsuran_id;
    
    // Buat folder jika belum ada
    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('pinjaman/bayar_angsuran/' . $angsuran_id);
    }
    
    $upload_data = $this->upload->data();
    
    // Data sesuai struktur tabel pengajuan_bayar_angsuran
 // Di controller submit_pembayaran_warga
$data_insert = [
    'angsuran_id' => $angsuran_id,
    'pinjaman_id' => $pinjaman->id,
    'warga_id' => $warga->id,
    'nominal_bayar' => $this->input->post('nominal_bayar'),
    'denda' => $this->input->post('denda') ?? 0, // Tambahkan ini
    'metode' => $this->input->post('metode'),
    'bukti_transfer' => $upload_data['file_name'],
    'keterangan' => $this->input->post('keterangan'),
];
    
    $this->Pinjaman_model->insert_pembayaran_pending($data_insert);
    
    $this->session->set_flashdata('success', 'Pembayaran berhasil dikirim! Menunggu verifikasi admin.');
    redirect('pinjaman/detail/' . $pinjaman->id);
}

    // Method untuk admin input pembayaran langsung (tanpa upload)
    public function proses_bayar_admin() {
        if (is_warga()) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('pinjaman');
        }
        
        $angsuran_id = $this->input->post('angsuran_id');
        $angsuran = $this->Pinjaman_model->get_angsuran_by_id($angsuran_id);
        $pinjaman = $this->Pinjaman_model->get_pinjaman_by_id($angsuran->pinjaman_id);
        
        $bayar = (float)$this->input->post('nominal_bayar');
        $denda_bayar = (float)$this->input->post('denda');
        $total = $bayar + $denda_bayar;
        $master_kas_id = $this->input->post('master_kas_id');

        $this->db->trans_start();

        // Update angsuran
        $this->Pinjaman_model->update_angsuran($angsuran_id, [
            'denda' => $denda_bayar,
            'total_bayar' => $total,
            'tanggal_bayar' => date('Y-m-d'),
            'status_bayar' => 'dibayar',
            'metode_pembayaran' => $this->input->post('metode_pembayaran'),
            'keterangan' => $this->input->post('keterangan'),
            'petugas_id' => $this->session->userdata('user_id'),
        ]);

        // Update pinjaman
        $sisa_baru = $pinjaman->sisa_pinjaman - $bayar;
        $sisa_tenor = $pinjaman->sisa_tenor - 1;
        $upd = ['sisa_pinjaman' => $sisa_baru, 'sisa_tenor' => $sisa_tenor];
        if ($sisa_baru <= 0 || $sisa_tenor <= 0) $upd['status_pinjaman'] = 'lunas';
        $this->Pinjaman_model->update_pinjaman($pinjaman->id, $upd);

        // Riwayat
        $this->Pinjaman_model->insert_riwayat_pembayaran([
            'angsuran_id' => $angsuran_id,
            'pinjaman_id' => $pinjaman->id,
            'nominal_bayar' => $total,
            'metode' => $this->input->post('metode_pembayaran'),
            'petugas_id' => $this->session->userdata('user_id'),
        ]);

        // Catat ke kas
        $this->db->insert('kas_rt', [
            'tanggal' => date('Y-m-d'),
            'jenis' => 'pemasukan',
            'kategori' => 'Angsuran Pinjaman',
            'master_kas_id' => $master_kas_id,
            'nominal' => $total,
            'keterangan' => 'Angsuran ke-' . $angsuran->angsuran_ke .
                         ' pinjaman ' . $pinjaman->kode_pinjaman .
                         ' a.n. ' . $pinjaman->nama_lengkap . ' (' . $this->input->post('metode_pembayaran') . ')',
            'input_oleh' => $this->session->userdata('user_id'),
        ]);
        $this->Master_kas_model->update_saldo($master_kas_id);

        $this->db->trans_complete();

        if ($this->db->trans_status()) {
            $this->session->set_flashdata('success', 'Pembayaran berhasil dicatat dan masuk ke kas!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menyimpan pembayaran.');
        }

        redirect('pinjaman/detail/' . $pinjaman->id);
    }

    // ==================== VERIFIKASI PEMBAYARAN (ADMIN) ====================
    public function verifikasi_pembayaran_list() {
        if (is_warga()) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('pinjaman');
        }
        
        $data['title'] = 'Verifikasi Pembayaran Warga';
        $data['pending_list'] = $this->Pinjaman_model->get_all_pembayaran_pending();
        
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('pinjaman/verifikasi_list', $data);
        $this->load->view('templates/footer');
    }
public function verifikasi_pembayaran($pending_id) {
    if (is_warga()) {
        $this->session->set_flashdata('error', 'Akses ditolak!');
        redirect('pinjaman');
    }
    
    $pending = $this->Pinjaman_model->get_pembayaran_pending_by_id($pending_id);
    if (!$pending) {
        $this->session->set_flashdata('error', 'Data tidak ditemukan!');
        redirect('pinjaman/verifikasi_pembayaran_list');
    }
    
    if ($this->input->post()) {
        $status = $this->input->post('status');
        $master_kas_id = $this->input->post('master_kas_id');
        
        if ($status == 'verified') {
            $this->db->trans_start();
            
            // Update angsuran
            $this->Pinjaman_model->update_angsuran($pending->angsuran_id, [
                'denda' => 0, // Sesuaikan jika ada denda
                'total_bayar' => $pending->nominal_bayar,
                'tanggal_bayar' => date('Y-m-d'),
                'status_bayar' => 'dibayar',
                'metode_pembayaran' => $pending->metode_bayar,
                'keterangan' => 'Transfer - ' . ($pending->catatan_warga ?? ''),
                'petugas_id' => $this->session->userdata('user_id'),
            ]);
            
            // Update pinjaman
            $pinjaman = $this->Pinjaman_model->get_pinjaman_by_id($pending->pinjaman_id);
            $sisa_baru = $pinjaman->sisa_pinjaman - $pending->nominal_bayar;
            $sisa_tenor = $pinjaman->sisa_tenor - 1;
            $upd = ['sisa_pinjaman' => $sisa_baru, 'sisa_tenor' => $sisa_tenor];
            if ($sisa_baru <= 0 || $sisa_tenor <= 0) $upd['status_pinjaman'] = 'lunas';
            $this->Pinjaman_model->update_pinjaman($pending->pinjaman_id, $upd);
            
            // Riwayat
            $this->Pinjaman_model->insert_riwayat_pembayaran([
                'angsuran_id' => $pending->angsuran_id,
                'pinjaman_id' => $pending->pinjaman_id,
                'nominal_bayar' => $pending->nominal_bayar,
                'metode' => $pending->metode_bayar,
                'petugas_id' => $this->session->userdata('user_id'),
            ]);
            
            // Masukkan ke kas
            $this->db->insert('kas_rt', [
                'tanggal' => date('Y-m-d'),
                'jenis' => 'pemasukan',
                'kategori' => 'Angsuran Pinjaman',
                'master_kas_id' => $master_kas_id,
                'nominal' => $pending->nominal_bayar,
                'keterangan' => 'Angsuran ke-' . $pending->angsuran_ke . 
                             ' pinjaman ' . $pinjaman->kode_pinjaman . 
                             ' a.n. ' . $pending->nama_lengkap . ' (Transfer)',
                'input_oleh' => $this->session->userdata('user_id'),
            ]);
            $this->Master_kas_model->update_saldo($master_kas_id);
            
            // Update status pending
            $this->Pinjaman_model->update_pembayaran_pending($pending_id, [
                'status' => 'diverifikasi',
                'verified_by' => $this->session->userdata('user_id'),
                'verified_at' => date('Y-m-d H:i:s'),
                'master_kas_id' => $master_kas_id
            ]);
            
            $this->db->trans_complete();
            
            if ($this->db->trans_status()) {
                $this->session->set_flashdata('success', 'Pembayaran berhasil diverifikasi dan dicatat ke kas!');
            } else {
                $this->session->set_flashdata('error', 'Gagal memproses verifikasi.');
            }
        } else {
            // Rejected
            $this->Pinjaman_model->update_pembayaran_pending($pending_id, [
                'status' => 'ditolak',
                'verified_by' => $this->session->userdata('user_id'),
                'verified_at' => date('Y-m-d H:i:s'),
                'catatan_admin' => $this->input->post('alasan_reject')
            ]);
            $this->session->set_flashdata('success', 'Pembayaran ditolak.');
        }
        
        redirect('pinjaman/verifikasi_pembayaran_list');
    }
    
    $data['title'] = 'Verifikasi Pembayaran';
    $data['pending'] = $pending;
    $data['kas_list'] = $this->Master_kas_model->get_aktif();
    
    $this->load->view('templates/header', $data);
    $this->load->view('templates/sidebar', $data);
    $this->load->view('pinjaman/verifikasi_pembayaran', $data);
    $this->load->view('templates/footer');
}

    // ==================== PELUNASAN DIPERCEPAT ====================
    public function pelunasan_dipercepat($pinjaman_id) {
        if (is_warga()) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('pinjaman');
        }

        $pinjaman        = $this->Pinjaman_model->get_pinjaman_by_id($pinjaman_id);
        $diskon          = $pinjaman->sisa_pinjaman * 0.1;
        $total_pelunasan = $pinjaman->sisa_pinjaman - $diskon;

        if ($this->input->post()) {
            $master_kas_id = $this->input->post('master_kas_id');
            $nominal_bayar = (float)$this->input->post('nominal_dibayar');

            $this->db->trans_start();

            $this->Pinjaman_model->lunas_semua_angsuran($pinjaman_id);
            $this->Pinjaman_model->update_pinjaman($pinjaman_id, [
                'sisa_pinjaman'   => 0,
                'sisa_tenor'      => 0,
                'status_pinjaman' => 'lunas',
            ]);

            $this->db->insert('kas_rt', [
                'tanggal'       => date('Y-m-d'),
                'jenis'         => 'pemasukan',
                'kategori'      => 'Angsuran Pinjaman',
                'master_kas_id' => $master_kas_id,
                'nominal'       => $nominal_bayar,
                'keterangan'    => 'Pelunasan dipercepat ' . $pinjaman->kode_pinjaman . ' oleh ' . $pinjaman->nama_lengkap,
                'input_oleh'    => $this->session->userdata('user_id'),
            ]);
            $this->Master_kas_model->update_saldo($master_kas_id);

            $this->db->trans_complete();

            if ($this->db->trans_status()) {
                $this->session->set_flashdata('success', 'Pelunasan dipercepat berhasil. Pinjaman lunas.');
            } else {
                $this->session->set_flashdata('error', 'Gagal memproses pelunasan.');
            }

            redirect('pinjaman/detail/' . $pinjaman_id);
        }

        $data['title']           = 'Pelunasan Dipercepat';
        $data['pinjaman']        = $pinjaman;
        $data['diskon']          = $diskon;
        $data['total_pelunasan'] = $total_pelunasan;
        $data['kas_list']        = $this->Master_kas_model->get_aktif();

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

    // ==================== LAPORAN ====================
    public function laporan() {
        $data['title'] = is_warga() ? 'Laporan Pinjaman Saya' : 'Laporan Pinjaman';
        
        if (is_warga()) {
            $user_id = $this->session->userdata('user_id');
            $warga = $this->Warga_model->get_by_user_id($user_id);
            
            if (!$warga) {
                $this->session->set_flashdata('error', 'Data warga tidak ditemukan!');
                redirect('dashboard');
            }
            
            $data['pinjaman_saya'] = $this->Pinjaman_model->get_pinjaman_by_warga($warga->id);
            
            $data['pinjaman_lunas_count'] = 0;
            $data['pinjaman_aktif_count'] = 0;
            
            foreach ($data['pinjaman_saya'] as $p) {
                if ($p->status_pinjaman == 'lunas') {
                    $data['pinjaman_lunas_count']++;
                } else {
                    $data['pinjaman_aktif_count']++;
                }
            }
            
            $data['angsuran_bulan_ini'] = $this->Pinjaman_model->get_angsuran_bulan_ini_detail_by_warga($warga->id);
            $data['tunggakan_saya'] = $this->Pinjaman_model->get_tunggakan_by_warga($warga->id);
            
        } else {
            $bulan = $this->input->get('bulan') ?: date('m');
            $tahun = $this->input->get('tahun') ?: date('Y');
            
            $data['bulan'] = $bulan;
            $data['tahun'] = $tahun;
            $data['statistik'] = $this->Pinjaman_model->get_statistik_periode($bulan, $tahun);
            $data['pinjaman_lunas'] = $this->Pinjaman_model->get_pinjaman_lunas_periode($bulan, $tahun);
            $data['tunggakan'] = $this->Pinjaman_model->get_tunggakan($bulan, $tahun);
        }

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

    // ==================== AJAX ====================
    public function get_simulasi() {
        $nominal     = (float)$this->input->post('nominal');
        $tenor       = (int)$this->input->post('tenor');
        $bunga       = (float)$this->input->post('bunga');
        $bunga_total = ($nominal * $bunga / 100) * $tenor;
        $total       = $nominal + $bunga_total;
        $angsuran    = $tenor > 0 ? $total / $tenor : 0;

        echo json_encode([
            'bunga_total'        => number_format($bunga_total, 0, ',', '.'),
            'total_pinjaman'     => number_format($total, 0, ',', '.'),
            'angsuran_per_bulan' => number_format($angsuran, 0, ',', '.'),
            'angsuran_raw'       => $angsuran,
        ]);
    }

    /**
     * AJAX: Cek angsuran jatuh tempo hari ini
     * Support cek pending payment untuk admin
     */
    public function cek_angsuran_hari_ini() {
        $tanggal = date('Y-m-d');
        
        if (is_warga()) {
            $warga  = $this->Warga_model->get_by_user_id($this->session->userdata('user_id'));
            $result = $this->Pinjaman_model->get_angsuran_jatuh_tempo_by_warga($tanggal, $warga->id);
        } else {
            $result = $this->Pinjaman_model->get_angsuran_jatuh_tempo($tanggal);
            
            // TAMBAHAN: Untuk admin, cek apakah ada pending payment untuk setiap angsuran
            foreach($result as &$a) {
                $pending = $this->Pinjaman_model->get_pending_by_angsuran($a->id);
                if($pending) {
                    $a->is_pending = true;
                    $a->pending_id = $pending->id;
                    $a->pending_time = $pending->created_at;
                } else {
                    $a->is_pending = false;
                }
            }
        }
        
        echo json_encode($result);
    }

    // ==================== AKHIR CLASS ====================

    // ==================== JENIS PINJAMAN ====================

public function jenis_pinjaman() {
    if (is_warga()) {
        $this->session->set_flashdata('error', 'Akses ditolak!');
        redirect('pinjaman');
    }
    
    $data['title'] = 'Jenis Pinjaman';
    $data['jenis_pinjaman'] = $this->Jenis_pinjaman_model->get_all_admin();
    
    // DEBUG: Uncomment untuk melihat struktur data
    // echo '<pre>'; print_r($data['jenis_pinjaman']); die();
    
    $this->load->view('templates/header', $data);
    $this->load->view('templates/sidebar', $data);
    $this->load->view('pinjaman/jenis_pinjaman', $data);
    $this->load->view('templates/footer');
}

public function simpan_jenis() {
    if (is_warga()) {
        $this->session->set_flashdata('error', 'Akses ditolak!');
        redirect('pinjaman');
    }
    
    // HAPUS is_unique[jenis_pinjaman.nama_jenis] dari sini
    $this->form_validation->set_rules('nama_jenis', 'Nama Jenis', 'required|trim');
    $this->form_validation->set_rules('bunga_persen', 'Bunga Persen', 'required|numeric|greater_than_equal_to[0]|less_than_equal_to[100]');
    $this->form_validation->set_rules('denda_persen', 'Denda Persen', 'required|numeric|greater_than_equal_to[0]|less_than_equal_to[100]');
    $this->form_validation->set_rules('tenor_maksimal', 'Tenor Maksimal', 'required|integer|greater_than[0]|less_than_equal_to[60]');
    
    if ($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('error', validation_errors());
        redirect('pinjaman/jenis_pinjaman');
    }
    
    $data = [
        'nama_pinjaman'    => $this->input->post('nama_jenis'),
        'bunga_persen'     => $this->input->post('bunga_persen'),
        'denda_persen'     => $this->input->post('denda_persen'),
        'tenor_max'        => $this->input->post('tenor_maksimal'),
        'status'           => $this->input->post('status'),
        'syarat_ketentuan' => $this->input->post('keterangan'),
        'created_at'       => date('Y-m-d H:i:s')
    ];
    
    if ($this->Jenis_pinjaman_model->insert($data)) {
        $this->session->set_flashdata('success', 'Jenis pinjaman berhasil ditambahkan!');
    } else {
        $this->session->set_flashdata('error', 'Gagal menambahkan jenis pinjaman.');
    }
    
    redirect('pinjaman/jenis_pinjaman');
}

public function update_jenis() {
    if (is_warga()) {
        $this->session->set_flashdata('error', 'Akses ditolak!');
        redirect('pinjaman');
    }
    
    $id = $this->input->post('id');
    if (!$id) {
        $this->session->set_flashdata('error', 'ID tidak valid!');
        redirect('pinjaman/jenis_pinjaman');
    }
    
    // Cek unique nama_jenis kecuali untuk ID ini sendiri
    $this->form_validation->set_rules('nama_jenis', 'Nama Jenis', 'required|trim|callback_check_unique_nama['.$id.']');
    $this->form_validation->set_rules('bunga_persen', 'Bunga Persen', 'required|numeric|greater_than_equal_to[0]|less_than_equal_to[100]');
    $this->form_validation->set_rules('denda_persen', 'Denda Persen', 'required|numeric|greater_than_equal_to[0]|less_than_equal_to[100]');
    $this->form_validation->set_rules('tenor_maksimal', 'Tenor Maksimal', 'required|integer|greater_than[0]|less_than_equal_to[60]');
    
    if ($this->form_validation->run() == FALSE) {
        $this->session->set_flashdata('error', validation_errors());
        redirect('pinjaman/jenis_pinjaman');
    }
    
  $data = [
    'nama_pinjaman' => $this->input->post('nama_jenis'),
    'bunga_persen'  => $this->input->post('bunga_persen'),
    'denda_persen'  => $this->input->post('denda_persen'),
    'tenor_max'     => $this->input->post('tenor_maksimal'),
    'status'        => $this->input->post('status'),
    'syarat_ketentuan' => $this->input->post('keterangan'),
    'updated_at'    => date('Y-m-d H:i:s')
];
    
    if ($this->Jenis_pinjaman_model->update($id, $data)) {
        $this->session->set_flashdata('success', 'Jenis pinjaman berhasil diupdate!');
    } else {
        $this->session->set_flashdata('error', 'Gagal mengupdate jenis pinjaman.');
    }
    
    redirect('pinjaman/jenis_pinjaman');
}
public function hapus_jenis($id) {
    if (is_warga()) {
        $this->session->set_flashdata('error', 'Akses ditolak!');
        redirect('pinjaman');
    }

    
    
    if ($this->Jenis_pinjaman_model->delete($id)) {
        $this->session->set_flashdata('success', 'Jenis pinjaman berhasil dihapus!');
    } else {
        $this->session->set_flashdata('error', 'Gagal menghapus jenis pinjaman.');
    }
    
    redirect('pinjaman/jenis_pinjaman');
}
// Callback untuk cek unique nama
public function check_unique_nama($nama, $id) {
    $exists = $this->Jenis_pinjaman_model->cek_nama_exists($nama, $id);
    if ($exists) {
        $this->form_validation->set_message('check_unique_nama', 'Nama jenis pinjaman sudah ada!');
        return FALSE;
    }
    return TRUE;
}
}