<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'name', 'code', 'start_time', 'end_time', 'grace_period_minutes',
        'early_exit_grace_minutes', 'overtime_after_minutes', 'break_minutes',
        'auto_punch', 'description', 'status', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'name'       => 'required|min_length[2]|max_length[100]',
        'code'       => 'required|max_length[10]|is_unique[attendance_shifts.code,id,{id}]',
        'start_time' => 'required',
        'end_time'   => 'required',
        'status'     => 'permit_empty|in_list[active,inactive]',
    ];

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

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

        return $this;
    }

    public function getActive(): array
    {
        return $this->where('status', 'active')->orderBy('name', '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;
    }
}
