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

class Master_kas extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        // Hanya admin/bendahara yang bisa kelola master kas
        $role = $this->session->userdata('role');
        if (!in_array($role, ['admin', 'ketua_rt', 'bendahara'])) {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses ke halaman ini.');
            redirect('dashboard');
        }
        $this->load->model('Master_kas_model');
        $this->load->model('User_model');
        $this->load->library('form_validation');
        $this->load->helper('url');
    }

    // ─────────────────────────────────────────────
    // INDEX - Daftar Master Kas
    // ─────────────────────────────────────────────
    public function index() {
        $data['title']        = 'Master Kas';
        $data['kas_list']     = $this->Master_kas_model->get_ringkasan_saldo();
        $data['total_saldo']  = $this->Master_kas_model->get_total_saldo_semua();

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

    // ─────────────────────────────────────────────
    // TAMBAH Master Kas
    // ─────────────────────────────────────────────
    public function tambah() {
        $data['title'] = 'Tambah Master Kas';

        $this->form_validation->set_rules('kode',  'Kode Kas',  'required|max_length[20]');
        $this->form_validation->set_rules('nama',  'Nama Kas',  'required|max_length[100]');
        $this->form_validation->set_rules('jenis', 'Jenis Kas', 'required|in_list[bank,tunai,ewallet]');
        $this->form_validation->set_rules('saldo_awal', 'Saldo Awal', 'required|numeric');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('master_kas/tambah', $data);
            $this->load->view('templates/footer');
        } else {
            $kode = strtoupper(trim($this->input->post('kode')));

            // Cek kode unik
            if ($this->Master_kas_model->is_kode_exists($kode)) {
                $this->session->set_flashdata('error', 'Kode kas "' . $kode . '" sudah digunakan!');
                redirect('master_kas/tambah');
            }

            $insert = [
                'kode'           => $kode,
                'nama'           => $this->input->post('nama'),
                'jenis'          => $this->input->post('jenis'),
                'nomor_rekening' => $this->input->post('nomor_rekening'),
                'atas_nama'      => $this->input->post('atas_nama'),
                'saldo_awal'     => $this->input->post('saldo_awal'),
                'warna'          => $this->input->post('warna') ?: '#6c757d',
                'icon'           => $this->input->post('icon') ?: 'bi-wallet2',
                'is_tabungan'    => $this->input->post('is_tabungan') ? 1 : 0,
                'status'         => $this->input->post('status') ?: 'aktif',
                'keterangan'     => $this->input->post('keterangan'),
            ];

            $this->Master_kas_model->insert($insert);
            $this->User_model->log_activity($this->session->userdata('user_id'), 'create', 'Menambah Master Kas baru: ' . $insert['nama'] . ' (' . $insert['kode'] . ')');
            $this->session->set_flashdata('success', 'Master kas berhasil ditambahkan!');
            redirect('master_kas');
        }
    }

    // ─────────────────────────────────────────────
    // EDIT Master Kas
    // ─────────────────────────────────────────────
    public function edit($id) {
        $data['title'] = 'Edit Master Kas';
        $data['kas']   = $this->Master_kas_model->get_by_id($id);

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

        $this->form_validation->set_rules('kode',  'Kode Kas',  'required|max_length[20]');
        $this->form_validation->set_rules('nama',  'Nama Kas',  'required|max_length[100]');
        $this->form_validation->set_rules('jenis', 'Jenis Kas', 'required|in_list[bank,tunai,ewallet]');
        $this->form_validation->set_rules('saldo_awal', 'Saldo Awal', 'required|numeric');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('master_kas/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $kode = strtoupper(trim($this->input->post('kode')));

            if ($this->Master_kas_model->is_kode_exists($kode, $id)) {
                $this->session->set_flashdata('error', 'Kode kas "' . $kode . '" sudah digunakan!');
                redirect('master_kas/edit/' . $id);
            }

            $update = [
                'kode'           => $kode,
                'nama'           => $this->input->post('nama'),
                'jenis'          => $this->input->post('jenis'),
                'nomor_rekening' => $this->input->post('nomor_rekening'),
                'atas_nama'      => $this->input->post('atas_nama'),
                'saldo_awal'     => $this->input->post('saldo_awal'),
                'warna'          => $this->input->post('warna') ?: '#6c757d',
                'icon'           => $this->input->post('icon') ?: 'bi-wallet2',
                'is_tabungan'    => $this->input->post('is_tabungan') ? 1 : 0,
                'status'         => $this->input->post('status') ?: 'aktif',
                'keterangan'     => $this->input->post('keterangan'),
            ];

            $this->Master_kas_model->update($id, $update);
            // Recalculate saldo setelah ubah saldo_awal
            $this->Master_kas_model->update_saldo($id);

            $this->User_model->log_activity($this->session->userdata('user_id'), 'update', 'Mengubah data Master Kas: ' . $update['nama'] . ' (' . $update['kode'] . ')');
            $this->session->set_flashdata('success', 'Master kas berhasil diperbarui!');
            redirect('master_kas');
        }
    }

    // ─────────────────────────────────────────────
    // TOGGLE STATUS (Aktif / Nonaktif)
    // ─────────────────────────────────────────────
    public function toggle($id) {
        $kas = $this->Master_kas_model->get_by_id($id);
        $this->Master_kas_model->toggle_status($id);
        $this->User_model->log_activity($this->session->userdata('user_id'), 'update', 'Mengubah status Master Kas: ' . $kas->nama . ' (' . ($kas->status == 'aktif' ? 'Nonaktifkan' : 'Aktifkan') . ')');
        $this->session->set_flashdata('success', 'Status kas berhasil diubah.');
        redirect('master_kas');
    }

    // ─────────────────────────────────────────────
    // HAPUS Master Kas
    // ─────────────────────────────────────────────
    public function hapus($id) {
        $kas = $this->Master_kas_model->get_by_id($id);
        $result = $this->Master_kas_model->delete($id);
        if ($result === false) {
            $this->session->set_flashdata('error', 'Kas tidak dapat dihapus karena masih memiliki transaksi!');
        } else {
            $this->User_model->log_activity($this->session->userdata('user_id'), 'delete', 'Menghapus Master Kas: ' . ($kas->nama ?? $id));
            $this->session->set_flashdata('success', 'Master kas berhasil dihapus.');
        }
        redirect('master_kas');
    }
}