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

class Laporan_keuangan_model extends CI_Model
{
    public function get_pembayaran(array $filters = [])
    {
        $this->db->select('
            p.PembayaranID          AS id,
            p.TanggalBayar          AS tanggal_bayar,
            p.JumlahBayar           AS jumlah_bayar,
            p.MetodeBayar           AS metode_bayar,
            p.StatusBayar           AS status,
            p.JenisPembayaran       AS keterangan,
            p.NamaLengkap           AS nama_siswa
        ');
        $this->db->from('pembayaran p');
        // ga perlu join siswa karena sudah ada NamaLengkap di tabel pembayaran

        if (!empty($filters['date_from'])) {
            $this->db->where('DATE(p.TanggalBayar) >=', $filters['date_from']);
        }

        if (!empty($filters['date_to'])) {
            $this->db->where('DATE(p.TanggalBayar) <=', $filters['date_to']);
        }

        if (!empty($filters['status']) && $filters['status'] !== 'all') {
            // contoh: 'pending', 'lunas', dll.
            $this->db->where('p.StatusBayar', $filters['status']);
        }

        if (!empty($filters['metode']) && $filters['metode'] !== 'all') {
            // contoh: 'cash', 'transfer'
            $this->db->where('p.MetodeBayar', $filters['metode']);
        }

        $this->db->order_by('p.TanggalBayar', 'ASC');

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

    public function get_rekap_summary(array $filters = [])
    {
        $this->db->select('
            COUNT(p.PembayaranID)   AS total_transaksi,
            SUM(p.JumlahBayar)      AS total_pemasukan
        ');
        $this->db->from('pembayaran p');

        if (!empty($filters['date_from'])) {
            $this->db->where('DATE(p.TanggalBayar) >=', $filters['date_from']);
        }

        if (!empty($filters['date_to'])) {
            $this->db->where('DATE(p.TanggalBayar) <=', $filters['date_to']);
        }

        if (!empty($filters['status']) && $filters['status'] !== 'all') {
            $this->db->where('p.StatusBayar', $filters['status']);
        }

        if (!empty($filters['metode']) && $filters['metode'] !== 'all') {
            $this->db->where('p.MetodeBayar', $filters['metode']);
        }

        $row = $this->db->get()->row_array();

        return [
            'total_transaksi' => (int) ($row['total_transaksi'] ?? 0),
            'total_pemasukan' => (float) ($row['total_pemasukan'] ?? 0),
        ];
    }
}
