<?php

namespace App\Models;

use CodeIgniter\Model;

class ExpenseModel extends Model
{
    protected $table         = 'expenses';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'number', 'expense_date', 'amount', 'expense_account_id', 'pay_from_type',
        'pay_from_id', 'cost_center_id', 'payee', 'reference', 'notes', 'status',
        'journal_entry_id', 'approved_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'             => 'required|max_length[40]',
        'expense_date'       => 'required|valid_date',
        'amount'             => 'required|decimal',
        'expense_account_id' => 'required|is_natural_no_zero',
        'pay_from_type'      => 'required|in_list[bank,cash]',
        'pay_from_id'        => 'required|is_natural_no_zero',
        'status'             => 'permit_empty|in_list[draft,approved,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('expenses.*, chart_of_accounts.code as account_code, chart_of_accounts.name as account_name, cost_centers.code as cost_center_code, cost_centers.name as cost_center_name')
            ->join('chart_of_accounts', 'chart_of_accounts.id = expenses.expense_account_id', 'left')
            ->join('cost_centers', 'cost_centers.id = expenses.cost_center_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('expenses.number', $search)
                ->orLike('expenses.payee', $search)
                ->orLike('expenses.reference', $search)
                ->orLike('expenses.notes', $search)
                ->groupEnd();
        }

        if ($status) {
            $this->where('expenses.status', $status);
        }

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'EXP-' . date('Ymd') . '-';
        $row = $this->like('number', $prefix, 'after')
            ->orderBy('id', 'DESC')
            ->first();

        $seq = 1;
        if ($row && preg_match('/-(\d+)$/', $row['number'], $m)) {
            $seq = (int) $m[1] + 1;
        }

        return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
    }
}
