<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'code', 'name', 'parent_id', 'status', 'notes',
        'created_by', 'updated_by',
    ];

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

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('cost_centers.*, parent.code as parent_code, parent.name as parent_name')
            ->join('cost_centers as parent', 'parent.id = cost_centers.parent_id', 'left');

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

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

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

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