<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'code', 'name', 'type', 'parent_id', 'is_postable', 'status',
        'description', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'code'   => 'required|max_length[30]',
        'name'   => 'required|min_length[2]|max_length[150]',
        'type'   => 'required|in_list[asset,liability,equity,revenue,expense]',
        'status' => 'permit_empty|in_list[active,inactive]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?string $type = null): self
    {
        if ($search) {
            $this->groupStart()
                ->like('name', $search)
                ->orLike('code', $search)
                ->orLike('description', $search)
                ->groupEnd();
        }

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

        if ($type) {
            $this->where('type', $type);
        }

        return $this;
    }

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

    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;
    }

    public function hasChildren(int $id): bool
    {
        return $this->where('parent_id', $id)->countAllResults() > 0;
    }
}
