<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'name', 'date', 'is_recurring', 'branch_id', 'description',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name' => 'required|min_length[2]|max_length[150]',
        'date' => 'required|valid_date[Y-m-d]',
    ];

    public function scopeForList(?string $search = null, ?int $year = null, ?int $branchId = null): self
    {
        if ($search) {
            $this->like('name', $search);
        }

        if ($year) {
            $this->where('YEAR(date)', $year);
        }

        if ($branchId) {
            $this->groupStart()
                ->where('branch_id', $branchId)
                ->orWhere('branch_id', null)
                ->groupEnd();
        }

        return $this;
    }

    public function getInRange(string $startDate, string $endDate, ?int $branchId = null): array
    {
        $builder = $this->where('date >=', $startDate)
            ->where('date <=', $endDate);

        if ($branchId) {
            $builder->groupStart()
                ->where('branch_id', $branchId)
                ->orWhere('branch_id', null)
                ->groupEnd();
        }

        return $builder->orderBy('date', 'ASC')->findAll();
    }
}
