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

class Jenis_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('Jenis_iuran_model');
        $this->load->model('User_model');
        check_login();
        require_admin(); // Hanya admin yang bisa akses
    }

    public function index() {
        $data['title']       = 'Jenis Iuran';
        $data['jenis_iuran'] = $this->Jenis_iuran_model->get_all();
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('jenis_iuran/index', $data);
        $this->load->view('templates/footer');
    }

    public function tambah() {
        if ($this->input->post()) {
            $this->form_validation->set_rules('nama_iuran', 'Nama Iuran', 'required|trim');
            $this->form_validation->set_rules('kode',       'Kode',       'required|trim|max_length[10]');
            $this->form_validation->set_rules('nominal',    'Nominal',    'required|numeric|greater_than[0]');
            $this->form_validation->set_rules('periode',    'Periode',    'required');
            $this->form_validation->set_rules('status',     'Status',     'required');

            if ($this->form_validation->run()) {
                // Cek duplikat kode
                if ($this->Jenis_iuran_model->kode_exists($this->input->post('kode'))) {
                    $this->session->set_flashdata('error', 'Kode iuran sudah digunakan!');
                    redirect('jenis_iuran/tambah');
                }

                $data = array(
                    'nama_iuran' => $this->input->post('nama_iuran'),
                    'kode'       => strtoupper($this->input->post('kode')),
                    'deskripsi'  => $this->input->post('deskripsi'),
                    'nominal'    => $this->input->post('nominal'),
                    'periode'    => $this->input->post('periode'),
                    'status'     => $this->input->post('status'),
                    'created_at' => app_now(),
                );

                if ($this->Jenis_iuran_model->insert($data)) {
                    $this->User_model->log_activity($this->session->userdata('user_id'), 'create', 'Menambah Jenis Iuran baru: ' . $data['nama_iuran'] . ' (' . $data['kode'] . ')');
                    $this->session->set_flashdata('success', 'Jenis iuran berhasil ditambahkan!');
                    redirect('jenis_iuran');
                } else {
                    $this->session->set_flashdata('error', 'Gagal menambahkan jenis iuran!');
                }
            } else {
                $this->session->set_flashdata('error', validation_errors());
            }
        }

        $data['title'] = 'Tambah Jenis Iuran';
        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('jenis_iuran/form', $data);
        $this->load->view('templates/footer');
    }

    public function edit($id) {
        $data['jenis'] = $this->Jenis_iuran_model->get_by_id($id);

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

        if ($this->input->post()) {
            $this->form_validation->set_rules('nama_iuran', 'Nama Iuran', 'required|trim');
            $this->form_validation->set_rules('kode',       'Kode',       'required|trim|max_length[10]');
            $this->form_validation->set_rules('nominal',    'Nominal',    'required|numeric|greater_than[0]');
            $this->form_validation->set_rules('periode',    'Periode',    'required');
            $this->form_validation->set_rules('status',     'Status',     'required');

            if ($this->form_validation->run()) {
                // Cek duplikat kode (kecuali milik sendiri)
                if ($this->Jenis_iuran_model->kode_exists($this->input->post('kode'), $id)) {
                    $this->session->set_flashdata('error', 'Kode iuran sudah digunakan!');
                    redirect('jenis_iuran/edit/' . $id);
                }

                $update = array(
                    'nama_iuran' => $this->input->post('nama_iuran'),
                    'kode'       => strtoupper($this->input->post('kode')),
                    'deskripsi'  => $this->input->post('deskripsi'),
                    'nominal'    => $this->input->post('nominal'),
                    'periode'    => $this->input->post('periode'),
                    'status'     => $this->input->post('status'),
                );

                if ($this->Jenis_iuran_model->update($id, $update)) {
                    $this->User_model->log_activity($this->session->userdata('user_id'), 'update', 'Mengubah data Jenis Iuran: ' . $update['nama_iuran'] . ' (' . $update['kode'] . ')');
                    $this->session->set_flashdata('success', 'Jenis iuran berhasil diperbarui!');
                    redirect('jenis_iuran');
                } else {
                    $this->session->set_flashdata('error', 'Gagal memperbarui jenis iuran!');
                }
            } else {
                $this->session->set_flashdata('error', validation_errors());
            }
        }

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

    public function toggle_status($id) {
        $jenis = $this->Jenis_iuran_model->get_by_id($id);
        if (!$jenis) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan!');
            redirect('jenis_iuran');
        }

        $new_status = ($jenis->status === 'aktif') ? 'nonaktif' : 'aktif';
        $this->Jenis_iuran_model->update($id, ['status' => $new_status]);
        $this->User_model->log_activity($this->session->userdata('user_id'), 'update', 'Mengubah status Jenis Iuran: ' . $jenis->nama_iuran . ' jadi ' . $new_status);
        $label = ($new_status === 'aktif') ? 'diaktifkan' : 'dinonaktifkan';
        $this->session->set_flashdata('success', "Jenis iuran berhasil {$label}!");
        redirect('jenis_iuran');
    }

    public function hapus($id) {
        // Cek apakah sudah digunakan di tagihan iuran
        $this->load->model('Iuran_model');
        $this->db->where('jenis_iuran_id', $id);
        $used = $this->db->count_all_results('pembayaran_iuran');

        if ($used > 0) {
            $this->session->set_flashdata('error', "Jenis iuran tidak bisa dihapus karena sudah memiliki {$used} tagihan!");
            redirect('jenis_iuran');
        }

        $jenis = $this->Jenis_iuran_model->get_by_id($id);
        if ($this->Jenis_iuran_model->delete($id)) {
            $this->User_model->log_activity($this->session->userdata('user_id'), 'delete', 'Menghapus Jenis Iuran: ' . ($jenis->nama_iuran ?? $id));
            $this->session->set_flashdata('success', 'Jenis iuran berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus jenis iuran!');
        }
        redirect('jenis_iuran');
    }
}