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

class Tabungan extends CI_Controller {

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

        $this->data['user_role'] = $this->session->userdata('role');
        $this->data['user_id']   = $this->session->userdata('user_id');
    }

    // ─────────────────────────────────────────────
    // INDEX
    // ─────────────────────────────────────────────
    public function index() {
        $data['title']     = 'Data Tabungan Warga';
        $data['user_role'] = $this->data['user_role'];
        $data['user_id']   = $this->data['user_id'];

        if ($this->data['user_role'] == 'warga') {
            $warga = $this->Warga_model->get_by_user_id($this->data['user_id']);
            $data['tabungan'] = $warga
                ? $this->Tabungan_model->get_by_warga_id_single($warga->id)
                : [];
        } else {
            $data['tabungan'] = $this->Tabungan_model->get_all();
        }

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

    // ─────────────────────────────────────────────
    // DETAIL
    // ─────────────────────────────────────────────
    public function detail($warga_id = null) {
        $data['title']     = 'Detail Tabungan';
        $data['user_role'] = $this->data['user_role'];

        if ($this->data['user_role'] == 'warga') {
            $warga = $this->Warga_model->get_by_user_id($this->data['user_id']);
            if (!$warga) redirect('tabungan');
            $warga_id = $warga->id;
        }

        $data['tabungan'] = $this->Tabungan_model->get_by_warga($warga_id);
        if (!$data['tabungan']) {
            $this->session->set_flashdata('error', 'Data tabungan tidak ditemukan');
            redirect('tabungan');
        }

        $data['transaksi'] = $this->Tabungan_model->get_transaksi($data['tabungan']->id);
        $data['warga']     = $this->Warga_model->get_by_id($warga_id);

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

    // ─────────────────────────────────────────────
    // SETOR
    // ─────────────────────────────────────────────
    public function setor() {
        $data['title']     = 'Pengajuan Setoran Tabungan';
        $data['user_role'] = $this->data['user_role'];
        $data['kas_list']  = $this->Master_kas_model->get_aktif();

        if ($this->data['user_role'] == 'warga') {
            $data['warga_saya'] = $this->Warga_model->get_by_user_id($this->data['user_id']);
            if (!$data['warga_saya']) {
                $this->session->set_flashdata('error', 'Data warga tidak ditemukan');
                redirect('tabungan');
            }
            $tabungan = $this->Tabungan_model->get_by_warga($data['warga_saya']->id);
            $data['punya_tabungan'] = (bool) $tabungan;
            $data['tabungan_id']    = $tabungan ? $tabungan->id : null;
        } else {
            $data['warga'] = $this->Warga_model->get_all();
        }

        $this->form_validation->set_rules('nominal',       'Nominal',      'required|numeric|greater_than_equal_to[10000]');
        $this->form_validation->set_rules('master_kas_id', 'Rekening Kas', 'required|integer');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('tabungan/setor', $data);
            $this->load->view('templates/footer');
        } else {
            $bukti_file = '';
            if (!empty($_FILES['bukti_transfer']['name'])) {
                $config = [
                    'upload_path'   => './uploads/bukti_transfer/',
                    'allowed_types' => 'gif|jpg|png|jpeg|pdf',
                    'max_size'      => 2048,
                    'file_name'     => 'bukti_' . time() . '_' . $this->data['user_id'],
                ];
                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', $this->upload->display_errors());
                    redirect('tabungan/setor');
                }
            }

            if ($this->data['user_role'] == 'warga') {
                $warga_id       = $data['warga_saya']->id;
                $jenis_tabungan = $this->input->post('jenis_tabungan') ?: 'sukarela';
            } else {
                $warga_id       = $this->input->post('warga_id');
                $jenis_tabungan = $this->input->post('jenis_tabungan');
            }

            $tabungan = $this->Tabungan_model->get_by_warga($warga_id);
            if (!$tabungan) {
                $tabungan_id = $this->Tabungan_model->create([
                    'warga_id'       => $warga_id,
                    'jenis_tabungan' => $jenis_tabungan,
                    'saldo'          => 0,
                    'status'         => 'aktif',
                ]);
            } else {
                $tabungan_id = $tabungan->id;
            }

            $this->Tabungan_model->ajukan_transaksi([
                'tabungan_id'     => $tabungan_id,
                'jenis_transaksi' => 'setor',
                'nominal'         => $this->input->post('nominal'),
                'keterangan'      => $this->input->post('keterangan'),
                'petugas_id'      => $this->data['user_id'],
                'bukti_transfer'  => $bukti_file,
                'master_kas_id'   => $this->input->post('master_kas_id'),
                'status'          => 'pending',
            ]);

            $this->session->set_flashdata('success', 'Pengajuan setoran berhasil dikirim. Menunggu persetujuan admin.');
            redirect('tabungan');
        }
    }

    // ─────────────────────────────────────────────
    // TARIK
    // ─────────────────────────────────────────────
    public function tarik() {
        $data['title']     = 'Pengajuan Penarikan Tabungan';
        $data['user_role'] = $this->data['user_role'];

        if ($this->data['user_role'] == 'warga') {
            $data['warga_saya'] = $this->Warga_model->get_by_user_id($this->data['user_id']);
            if (!$data['warga_saya']) redirect('tabungan');

            $tabungan = $this->Tabungan_model->get_by_warga($data['warga_saya']->id);
            if (!$tabungan) {
                $this->session->set_flashdata('error', 'Anda belum memiliki tabungan');
                redirect('tabungan');
            }
            $data['saldo_saya']  = $tabungan->saldo;
            $data['tabungan_id'] = $tabungan->id;

        } else {
            // ✅ PERBAIKAN: JOIN tabungan agar $w->saldo tersedia di view
            $data['warga'] = $this->_get_warga_dengan_saldo();
        }

        $this->form_validation->set_rules('nominal', 'Nominal', 'required|numeric|greater_than_equal_to[10000]');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('tabungan/tarik', $data);
            $this->load->view('templates/footer');
        } else {
            $nominal = $this->input->post('nominal');

            if ($this->data['user_role'] == 'warga') {
                $warga_id    = $data['warga_saya']->id;
                $saldo       = $data['saldo_saya'];
                $tabungan_id = $data['tabungan_id'];
            } else {
                $warga_id = $this->input->post('warga_id');
                $tabungan = $this->Tabungan_model->get_by_warga($warga_id);
                if (!$tabungan) {
                    $this->session->set_flashdata('error', 'Warga belum memiliki tabungan');
                    redirect('tabungan/tarik');
                }
                $saldo       = $tabungan->saldo;
                $tabungan_id = $tabungan->id;
            }

            if ($saldo < $nominal) {
                $this->session->set_flashdata('error', 'Saldo tidak mencukupi untuk penarikan');
                redirect('tabungan/tarik');
            }

            $this->Tabungan_model->ajukan_transaksi([
                'tabungan_id'     => $tabungan_id,
                'jenis_transaksi' => 'tarik',
                'nominal'         => $nominal,
                'keterangan'      => $this->input->post('keterangan'),
                'petugas_id'      => $this->data['user_id'],
                'status'          => 'pending',
            ]);

            $this->session->set_flashdata('success', 'Pengajuan penarikan berhasil dikirim. Menunggu persetujuan admin.');
            redirect('tabungan');
        }
    }

    // ─────────────────────────────────────────────
    // HELPER PRIVATE: ambil warga yang punya tabungan aktif + saldo
    // ─────────────────────────────────────────────
    private function _get_warga_dengan_saldo() {
        // JOIN users/warga dengan tabungan agar $w->saldo tersedia
        // Sesuaikan nama tabel dan kolom dengan skema database Anda
        $this->db->select('w.id, w.nama_lengkap, w.nik, t.saldo, t.id as tabungan_id')
                 ->from('warga w')                          // ← ganti 'warga' jika nama tabelnya berbeda
                 ->join('tabungan t', 't.warga_id = w.id AND t.status = \'aktif\'', 'inner')
                 ->order_by('w.nama_lengkap', 'ASC');

        return $this->db->get()->result();
    }

    // ─────────────────────────────────────────────
    // VERIFIKASI — admin only
    // ─────────────────────────────────────────────
    public function verifikasi() {
        if ($this->data['user_role'] != 'admin') redirect('tabungan');

        $data['title']             = 'Verifikasi Transaksi Tabungan';
        $data['transaksi_pending'] = $this->Tabungan_model->get_transaksi_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('tabungan/verifikasi', $data);
        $this->load->view('templates/footer');
    }

public function proses_verifikasi($transaksi_id) {
    if ($this->data['user_role'] != 'admin') redirect('tabungan');

    $status  = $this->input->post('status');
    $catatan = $this->input->post('catatan_admin');
    $kas_id  = $this->input->post('kas_id'); // ← tambah ini

    if ($status == 'disetujui') {
        $result = $this->Tabungan_model->setujui_transaksi(
            $transaksi_id, 
            $this->data['user_id'], 
            $catatan,
            $kas_id  // ← teruskan ke model
        );
        if ($result) {
            $this->session->set_flashdata('success', 'Transaksi berhasil disetujui dan saldo diperbarui');
        } else {
            $this->session->set_flashdata('error', 'Gagal memproses transaksi');
        }
    } else {
        $this->Tabungan_model->tolak_transaksi($transaksi_id, $this->data['user_id'], $catatan);
        $this->session->set_flashdata('success', 'Transaksi berhasil ditolak');
    }

    redirect('tabungan/verifikasi');
}

    public function lihat_bukti($filename) {
        $path = './uploads/bukti_transfer/' . $filename;
        if (file_exists($path)) {
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            header('Content-Type: ' . (in_array($ext, ['jpg','jpeg','png','gif']) ? 'image/' . $ext : 'application/pdf'));
            readfile($path);
        } else {
            show_404();
        }
    }

    public function cetak_mutasi($warga_id = null) {

    // Warga hanya bisa cetak milik sendiri
    if ($this->data['user_role'] == 'warga') {
        $warga = $this->Warga_model->get_by_user_id($this->data['user_id']);
        if (!$warga) redirect('tabungan');
        $warga_id = $warga->id;
    }

    if (!$warga_id) redirect('tabungan');

    $data['user_role'] = $this->data['user_role'];
    $data['warga']     = $this->Warga_model->get_by_id($warga_id);
    $data['tabungan']  = $this->Tabungan_model->get_by_warga($warga_id);

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

    // Ambil transaksi yang sudah disetujui (untuk mutasi resmi)
    // Ganti ke get_transaksi_semua() jika ingin tampilkan semua status
    $data['transaksi'] = $this->Tabungan_model->get_transaksi_disetujui($data['tabungan']->id);

    // ★ Load view dari folder cetak/ (standalone, tanpa header/sidebar/footer)
    $this->load->view('cetak/cetak_mutasi_tabungan', $data);
}

}