<?php

namespace App\Modules\HR\Attendance\Repositories;

use App\Modules\HR\Attendance\Models\Holiday;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class HolidayRepository
{
    public function isHoliday(int $tenantId, CarbonImmutable $day): bool
    {
        return Holiday::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->where(function ($query) use ($day): void {
                $query->whereDate('date', $day->toDateString())
                    ->orWhere(function ($recurring) use ($day): void {
                        $recurring->where('is_recurring_yearly', true)
                            ->whereMonth('date', $day->month)
                            ->whereDay('date', $day->day);
                    });
            })
            ->exists();
    }

    public function paginate(int $tenantId): LengthAwarePaginator
    {
        return Holiday::query()
            ->where('tenant_id', $tenantId)
            ->orderBy('date')
            ->paginate(25);
    }

    public function find(int $tenantId, int $id): ?Holiday
    {
        return Holiday::query()->where('tenant_id', $tenantId)->find($id);
    }

    public function save(int $tenantId, array $data, ?Holiday $holiday = null): Holiday
    {
        $holiday ??= new Holiday;
        $holiday->fill($data + ['tenant_id' => $tenantId])->save();

        return $holiday;
    }

    public function delete(Holiday $holiday): void
    {
        $holiday->delete();
    }
}
