<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'name', 'fiscal_year', 'period_from', 'period_to',
        'account_id', 'cost_center_id', 'amount', 'status', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'      => 'required|max_length[40]',
        'name'        => 'required|min_length[2]|max_length[150]',
        'fiscal_year' => 'required|is_natural_no_zero',
        'period_from' => 'required|valid_date',
        'period_to'   => 'required|valid_date',
        'account_id'  => 'required|is_natural_no_zero',
        'amount'      => 'required|decimal',
        'status'      => 'permit_empty|in_list[draft,active,closed]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $fiscalYear = null): self
    {
        $this->select('budgets.*, 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 = budgets.account_id', 'left')
            ->join('cost_centers', 'cost_centers.id = budgets.cost_center_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('budgets.number', $search)
                ->orLike('budgets.name', $search)
                ->orLike('budgets.notes', $search)
                ->orLike('chart_of_accounts.code', $search)
                ->orLike('chart_of_accounts.name', $search)
                ->groupEnd();
        }

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

        if ($fiscalYear) {
            $this->where('budgets.fiscal_year', $fiscalYear);
        }

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'BUD-' . 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);
    }
}
