<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'name', 'code', 'start_date', 'end_date', 'status', 'is_current',
        'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name'       => 'required|min_length[2]|max_length[100]',
        'code'       => 'required|max_length[30]',
        'start_date' => 'required|valid_date',
        'end_date'   => 'required|valid_date',
        'status'     => 'permit_empty|in_list[open,closed]',
    ];

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

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

        return $this;
    }

    public function getOpen(): array
    {
        return $this->where('status', 'open')->orderBy('start_date', 'DESC')->findAll();
    }

    public function getCurrent(): ?array
    {
        $row = $this->where('is_current', 1)->where('status', 'open')->first();

        return $row ?: null;
    }

    public function findForDate(string $date): ?array
    {
        $row = $this->where('start_date <=', $date)
            ->where('end_date >=', $date)
            ->where('status', 'open')
            ->orderBy('is_current', 'DESC')
            ->first();

        return $row ?: null;
    }

    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 clearCurrent(?int $exceptId = null): void
    {
        $builder = $this->builder()->set('is_current', 0);
        if ($exceptId) {
            $builder->where('id !=', $exceptId);
        }
        $builder->update();
    }
}
