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

class Pembayaran extends CI_Controller
{
    /** 🔹 KONFIG: target pelunasan & status aktif */
    const TOTAL_BIAYA = 7500000;       // target pelunasan
    const STATUS_SISWA_AKTIF_ID = 2;   // sesuaikan dgn tabel StatusSiswa lo

    public function __construct()
    {
        parent::__construct();
        check_role([1,2,3]); // contoh: 1=admin, 2=staff, 3=siswa

        $this->load->model('Pembayaran_model', 'pembayaran');
        $this->load->model('PembayaranSiswa_model', 'ledger');
        $this->load->model('Siswa_model', 'siswa');

        $this->load->helper(['form','url']);
        $this->load->library(['form_validation','upload']);
    }

    // ==============================================================
    // ====================== AREA SISWA ============================
    // ==============================================================

    /** 🔹 Riwayat pembayaran siswa + form bayar */
    public function index()
{
    check_role([3]); // khusus role siswa / calon

    $siswa_id = $this->session->userdata('SiswaID');
    $user_id  = $this->session->userdata('UserID');

    if (!$user_id) {
        show_error('UserID tidak ditemukan di sesi login.');
    }

    // Ambil detail siswa, kalau sudah aktif pasti ada di tabel Siswa
    $siswa = $this->siswa->get_by_id(null, $user_id);

    if ($siswa) {
        // siswa sudah aktif -> pakai SiswaID
        $siswa_id = $siswa->SiswaID;
        $this->session->set_userdata('SiswaID', $siswa_id);

        $riwayat = $this->pembayaran->get_by_siswa($siswa_id);
        $ledger  = $this->ledger->get_ledger_by_siswa($siswa_id);
        $total_bayar = $this->ledger->sum_nominal_by_siswa($siswa_id);

    } else {
        // calon siswa -> pakai UserID
        $riwayat = $this->pembayaran->get_by_user($user_id);  // bikin method baru di model
        $ledger  = [];  // ledger baru aktif setelah approve
        $total_bayar = 0;
    }

    $data = [
        'title'        => 'Pembayaran',
        'riwayat'      => $riwayat,
        'ledger'       => $ledger,
        'total_bayar'  => $total_bayar,
        'total_biaya'  => self::TOTAL_BIAYA,
        'sisa_tagihan' => max(0, self::TOTAL_BIAYA - $total_bayar)
    ];

    $this->load->view('pembayaran/index', $data);
}

    /** 🔹 Siswa submit pembayaran (pending) */
    public function submit()
    {
        check_role([3]); // siswa
        $siswa_id = $this->session->userdata('SiswaID');
        if (!$siswa_id) show_error('SiswaID tidak ditemukan di sesi.');

        // validasi input
        $this->form_validation->set_rules('JumlahBayar', 'Jumlah Bayar', 'required|numeric|greater_than[0]');
        $this->form_validation->set_rules('MetodeBayar', 'Metode Bayar', 'required');

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

        // handle upload bukti
        $config = [
            'upload_path'   => './uploads/bukti_transfer/',
            'allowed_types' => 'jpg|jpeg|png|pdf',
            'max_size'      => 4096,
            'encrypt_name'  => TRUE,
        ];
        if (!is_dir($config['upload_path'])) @mkdir($config['upload_path'], 0777, true);
        $this->upload->initialize($config);

        $bukti = null;
        if (!empty($_FILES['BuktiTransfer']['name'])) {
            if (!$this->upload->do_upload('BuktiTransfer')) {
                $this->session->set_flashdata('error', $this->upload->display_errors());
                return redirect('pembayaran');
            }
            $bukti = $this->upload->data('file_name');
        }

        // insert ke tabel pembayaran
        $insert = [
            'SiswaID'       => $siswa_id,
            'JumlahBayar'   => $this->input->post('JumlahBayar', true),
            'MetodeBayar'   => $this->input->post('MetodeBayar', true),
            'BuktiTransfer' => $bukti,
        ];

        $this->db->trans_begin();
        $this->pembayaran->create_pending($insert);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $this->session->set_flashdata('error', 'Gagal menyimpan pembayaran.');
        } else {
            $this->db->trans_commit();
            $this->session->set_flashdata('success', 'Pembayaran dikirim. Menunggu verifikasi admin.');
        }

        return redirect('pembayaran');
    }

    // ==============================================================
    // ====================== AREA ADMIN ============================
    // ==============================================================

    /** 🔹 Halaman verifikasi pembayaran (list pending) */
    public function admin_index()
    {
        check_role([1,2]); // admin/staff

        $data = [
            'title' => 'Verifikasi Pembayaran',
            'list'  => $this->pembayaran->get_all_with_status(),
        ];

        $this->load->view('pembayaran/admin_index', $data);
    }

    /** 🔹 Approve pembayaran */
    public function approve($pembayaran_id)
    {
        check_role([1,2]);
        $admin_user_id = $this->session->userdata('UserID');

        $row = $this->pembayaran->get_by_id($pembayaran_id);
        if (!$row || $row->StatusBayar !== 'Pending') {
            return show_error('Pembayaran tidak ditemukan atau sudah diproses.');
        }

        $this->db->trans_begin();

        // 1) set status approved di tabel Pembayaran
        $this->pembayaran->set_status($pembayaran_id, 'Approved');

        // 2) masukkan ke ledger PembayaranSiswa
        $this->ledger->insert_from_pembayaran($row, $admin_user_id);

        // 3) cek total & update status siswa jika lunas
        $this->_recalculate_and_update_status($row->SiswaID);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $this->session->set_flashdata('error','Gagal approve pembayaran.');
        } else {
            $this->db->trans_commit();
            $this->session->set_flashdata('success','Pembayaran di-approve.');
        }

        return redirect('pembayaran/admin_index');
    }

    /** 🔹 Reject pembayaran */
    public function reject($pembayaran_id)
    {
        check_role([1,2]);
        $alasan = $this->input->post('alasan'); // optional form

        $row = $this->pembayaran->get_by_id($pembayaran_id);
        if (!$row || $row->StatusBayar !== 'Pending') {
            return show_error('Pembayaran tidak ditemukan atau sudah diproses.');
        }

        $ok = $this->pembayaran->set_status($pembayaran_id, 'Rejected', $alasan);
        $this->session->set_flashdata(
            $ok ? 'success' : 'error',
            $ok ? 'Pembayaran ditolak.' : 'Gagal menolak pembayaran.'
        );

        return redirect('pembayaran/admin_index');
    }

    // ==============================================================
    // ======================== UTILITIES ===========================
    // ==============================================================

    /** 🔹 Hitung total bayar & update status siswa bila lunas */
    private function _recalculate_and_update_status($siswa_id)
    {
        $total = $this->ledger->sum_nominal_by_siswa($siswa_id);

        if ($total >= self::TOTAL_BIAYA) {
            // update status siswa jadi Aktif
            $this->siswa->update_status($siswa_id, self::STATUS_SISWA_AKTIF_ID);
        }
    }
}
