<?php

namespace App\Models;

use CodeIgniter\Model;

class TransaksiKasModel extends Model
{
    protected $table            = 'transaksi_kas';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $allowedFields    = ['tanggal', 'kode', 'uraian', 'jenis', 'jumlah'];
    protected $useTimestamps    = true;

    protected $validationRules = [
        'tanggal' => 'required|valid_date[Y-m-d]',
        'kode'    => 'required|max_length[30]',
        'uraian'  => 'required|max_length[255]',
        'jenis'   => 'required|in_list[masuk,keluar]',
        'jumlah'  => 'required|numeric|greater_than[0]',
    ];

    protected $validationMessages = [
        'jumlah' => [
            'greater_than' => 'Jumlah harus lebih dari 0.',
        ],
    ];

    public function findFiltered(array $filters = []): array
    {
        $builder = $this->builder();
        $this->terapkanFilter($builder, $filters);

        return $builder
            ->orderBy('tanggal', 'DESC')
            ->orderBy('id', 'DESC')
            ->get()
            ->getResultArray();
    }

    public function ringkasan(array $filters = []): array
    {
        $builder = $this->builder();
        $this->terapkanFilter($builder, $filters);

        $row = $builder
            ->select("COALESCE(SUM(CASE WHEN jenis = 'masuk' THEN jumlah ELSE 0 END), 0) AS masuk", false)
            ->select("COALESCE(SUM(CASE WHEN jenis = 'keluar' THEN jumlah ELSE 0 END), 0) AS keluar", false)
            ->get()
            ->getRowArray();

        $masuk  = (float) ($row['masuk'] ?? 0);
        $keluar = (float) ($row['keluar'] ?? 0);

        return [
            'masuk'  => $masuk,
            'keluar' => $keluar,
            'saldo'  => $masuk - $keluar,
        ];
    }

    public function buatKodeOtomatis(string $jenis): string
    {
        $prefix = $jenis === 'keluar' ? 'BKK' : 'BKM';
        $rows   = $this->select('kode')
            ->like('kode', $prefix . '-', 'after')
            ->findAll();

        $nomorTerakhir = 0;

        foreach ($rows as $row) {
            if (preg_match('/^' . $prefix . '-(\d+)$/', $row['kode'], $matches) === 1) {
                $nomorTerakhir = max($nomorTerakhir, (int) $matches[1]);
            }
        }

        return $prefix . '-' . str_pad((string) ($nomorTerakhir + 1), 3, '0', STR_PAD_LEFT);
    }

    private function terapkanFilter($builder, array $filters): void
    {
        if (($filters['q'] ?? '') !== '') {
            $builder
                ->groupStart()
                ->like('kode', $filters['q'])
                ->orLike('uraian', $filters['q'])
                ->groupEnd();
        }

        if (($filters['tanggal_mulai'] ?? '') !== '') {
            $builder->where('tanggal >=', $filters['tanggal_mulai']);
        }

        if (($filters['tanggal_sampai'] ?? '') !== '') {
            $builder->where('tanggal <=', $filters['tanggal_sampai']);
        }

        if (in_array($filters['jenis'] ?? '', ['masuk', 'keluar'], true)) {
            $builder->where('jenis', $filters['jenis']);
        }
    }
}
