<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'code', 'name', 'rate', 'tax_type', 'account_id', 'is_recoverable',
        'status', 'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'code'     => 'required|max_length[30]',
        'name'     => 'required|min_length[2]|max_length[150]',
        'rate'     => 'required|decimal',
        'tax_type' => 'required|in_list[vat,sales,withholding,other]',
        'status'   => 'permit_empty|in_list[active,inactive]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?string $taxType = null): self
    {
        $this->select('tax_rates.*, chart_of_accounts.code as account_code, chart_of_accounts.name as account_name')
            ->join('chart_of_accounts', 'chart_of_accounts.id = tax_rates.account_id', 'left');

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

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

        if ($taxType) {
            $this->where('tax_rates.tax_type', $taxType);
        }

        return $this;
    }

    public function getActive(): array
    {
        return $this->where('status', 'active')->orderBy('code', 'ASC')->findAll();
    }

    public function isCodeTaken(string $code, ?int $excludeId = null): bool
    {
        $builder = $this->where('code', strtoupper($code));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }
}
