<?php

namespace App\Modules\HR\Leave\Services;

use App\Modules\HR\Attendance\Services\AttendanceWorkingDayResolver;
use App\Modules\HR\Employees\Models\Employee;
use Carbon\CarbonImmutable;

class LeaveWorkingDaysCalculator
{
    public function __construct(
        private readonly AttendanceWorkingDayResolver $workingDays,
    ) {}

    public function resolve(Employee $employee, string $start, string $end, bool $allowHalf, bool $isHalf): float
    {
        if ($isHalf && $allowHalf) {
            return 0.5;
        }

        $cur = CarbonImmutable::parse($start)->startOfDay();
        $last = CarbonImmutable::parse($end)->startOfDay();
        $count = 0;
        while ($cur->lte($last)) {
            if ($this->workingDays->isWorkingDay($employee, $cur)) {
                $count++;
            }
            $cur = $cur->addDay();
        }

        return (float) max(0, $count);
    }

    /**
     * Working days of a leave clipped to an inclusive payroll date range.
     */
    public function clipped(
        Employee $employee,
        string $leaveStart,
        string $leaveEnd,
        string $rangeStart,
        string $rangeEnd,
        bool $isHalfDay,
    ): float {
        $clipStart = max($leaveStart, $rangeStart);
        $clipEnd = min($leaveEnd, $rangeEnd);
        if ($clipStart > $clipEnd) {
            return 0.0;
        }
        if ($isHalfDay) {
            return $clipStart === $leaveStart ? 0.5 : 0.0;
        }

        return $this->resolve($employee, $clipStart, $clipEnd, false, false);
    }
}
