<?php

namespace Modules\HR\Repositories;

use Modules\Core\Enums\StatusEnum;
use Modules\HR\DTO\HrSettingFilter;
use Modules\HR\Models\Holiday;

class HolidayRepository
{
    public function all(HrSettingFilter $filter, array $columns = ['*'])
    {
        return Holiday::query()
            ->search($filter->search)
            ->filterDateRange($filter->from_date, $filter->to_date)
            ->filterHolidayGroupIds($filter->holiday_group_ids)
            ->filterStatus($filter->status)
            ->orderBy('holiday_date', 'desc')
            ->select($columns)
            ->paginate($filter->perPage ?? 15);
    }

    public function find($id)
    {
        return Holiday::findOrFail($id);
    }

    public function create(array $data)
    {
        return Holiday::create([
            'holiday_group_id' => $data['holiday_group_id'] ?? null,
            'title'            => $data['title'],
            'holiday_date'     => $data['holiday_date'],
            'is_optional'      => $data['is_optional'] ?? false,
            'remarks'          => $data['remarks'] ?? null,
            'status'           => $data['status'] ?? StatusEnum::ACTIVE,
        ]);
    }

    public function createBulk(array $holidaysData)
    {
        $insertedHolidays = [];

        foreach ($holidaysData as $holidayRow) {
            $insertedHolidays[] = $this->create($holidayRow);
        }
        return collect($insertedHolidays);
    }

    public function update(Holiday $holiday, array $data)
    {
        $holiday->update([
            'holiday_group_id' => $data['holiday_group_id'] ?? null,
            'title'            => $data['title'],
            'holiday_date'     => $data['holiday_date'],
            'is_optional'      => $data['is_optional'] ?? false,
            'remarks'          => $data['remarks'] ?? null,
            'status'           => $data['status'] ?? StatusEnum::ACTIVE,
        ]);

        return $holiday;
    }

    public function updateStatus(Holiday $holiday, array $status)
    {
        $holiday->update([
            'status' => $status['status'] ?? StatusEnum::ACTIVE,
        ]);

        return $holiday;
    }
}
