<?php

namespace App\Modules\HR\Leave\Services;

use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Leave\Repositories\LeaveRequestRepository;

/**
 * Sums approved leave days clipped to a payroll (or other) date range.
 */
class LeavePayrollDaysService
{
    public function __construct(
        private readonly LeaveRequestRepository $leaves,
        private readonly LeaveWorkingDaysCalculator $calculator,
    ) {}

    public function sumApprovedDaysInRange(
        int $tenantId,
        int $employeeId,
        string $rangeStart,
        string $rangeEnd,
        ?bool $isPaid = null,
    ): float {
        $rows = $this->leaves->approvedOverlappingRange(
            $tenantId,
            $employeeId,
            $rangeStart,
            $rangeEnd,
            $isPaid,
        );
        $sum = 0.0;
        foreach ($rows as $row) {
            $employee = $row->employee instanceof Employee
                ? $row->employee
                : new Employee(['id' => $employeeId, 'tenant_id' => $tenantId]);
            $sum += $this->calculator->clipped(
                $employee,
                $row->start_date->toDateString(),
                $row->end_date->toDateString(),
                $rangeStart,
                $rangeEnd,
                (bool) $row->is_half_day,
            );
        }

        return round($sum, 2);
    }
}
