<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'employee_id', 'leave_type_id', 'start_date', 'end_date', 'days',
        'reason', 'status', 'approved_by', 'approved_at', 'rejection_reason',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'employee_id'   => 'required|integer',
        'leave_type_id' => 'required|integer',
        'start_date'    => 'required|valid_date[Y-m-d]',
        'end_date'      => 'required|valid_date[Y-m-d]',
        'status'        => 'permit_empty|in_list[pending,approved,rejected,cancelled]',
    ];

    public function scopeForList(
        ?string $search = null,
        ?string $status = null,
        ?int $employeeId = null,
        ?int $leaveTypeId = null,
        ?string $dateFrom = null,
        ?string $dateTo = null
    ): self {
        if ($search) {
            $this->groupStart()
                ->like('reason', $search)
                ->groupEnd();
        }

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

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

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

        if ($dateFrom) {
            $this->where('end_date >=', $dateFrom);
        }

        if ($dateTo) {
            $this->where('start_date <=', $dateTo);
        }

        return $this;
    }

    public function getApprovedInRange(string $startDate, string $endDate): array
    {
        return $this->where('status', 'approved')
            ->where('end_date >=', $startDate)
            ->where('start_date <=', $endDate)
            ->orderBy('start_date', 'ASC')
            ->findAll();
    }

    public function hasOverlap(int $employeeId, string $startDate, string $endDate, ?int $excludeId = null): bool
    {
        $builder = $this->where('employee_id', $employeeId)
            ->whereIn('status', ['pending', 'approved'])
            ->where('start_date <=', $endDate)
            ->where('end_date >=', $startDate);

        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }

    public static function calculateDays(string $startDate, string $endDate): float
    {
        $start = new \DateTime($startDate);
        $end   = new \DateTime($endDate);

        if ($end < $start) {
            return 0;
        }

        return (float) ($start->diff($end)->days + 1);
    }
}
