<?php

declare(strict_types=1);

namespace App\Services\Leave;

use Carbon\Carbon;

class LeaveDaysCalculator
{
    public function between(Carbon $start, Carbon $end): int
    {
        $startDate = $start->copy()->startOfDay();
        $endDate = $end->copy()->startOfDay();

        if ($endDate->lt($startDate)) {
            return 0;
        }

        return match (config('hr.leave_calculation')) {
            'business' => $this->businessDaysBetween($startDate, $endDate),
            default => (int) ($startDate->diffInDays($endDate) + 1),
        };
    }

    private function businessDaysBetween(Carbon $startDate, Carbon $endDate): int
    {
        $days = 0;
        $current = $startDate->copy();

        while ($current->lte($endDate)) {
            if (! $current->isWeekend()) {
                $days++;
            }

            $current->addDay();
        }

        return $days;
    }
}
