<?php

namespace Modules\HR\Repositories;

use Modules\HR\DTO\AttendanceFilter;
use Modules\HR\Enums\HolidayAllowancesStatus;
use Modules\HR\Enums\OvertimeStatusEnum;
use Modules\HR\Models\Attendance;
use Modules\HR\Models\HolidayAllowance;
use Modules\HR\Models\OvertimeEntry;

class AttendanceRepository
{
    public function all(AttendanceFilter $filter, $columns = ['*'], $relation = [])
    {
        return Attendance::query()
            ->select($columns)
            ->with($relation)
            ->search($filter->search)
            ->forEmployee($filter->employee_id)
            ->forDepartment($filter->department_id)
            ->forDesignation($filter->designation_id)
            ->forShift($filter->shift_id)
            ->filterStatus($filter->status)
            ->locked($filter->is_locked)
            ->hasOvertime($filter->has_overtime)
            ->minLateMinutes($filter->min_late_minutes)
            ->dateBetween($filter->from_date, $filter->to_date)
            ->forFiscalYear($filter->fiscal_year_id)
            ->forAccountingPeriod($filter->accounting_period_id)
            ->orderBy('date', 'asc')
            ->paginate($filter->perPage ?? 15);
    }

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

    public function getOvertimeEntries($filter, $columns = ['*'], $relation = [])
    {
        return OvertimeEntry::query()
            ->select($columns)
            ->with($relation)
            ->search($filter->search)
            ->employee($filter->employee_id)
            ->attendance($filter->attendance_id)
            ->otType($filter->ot_type)
            ->status($filter->status)
            ->locked($filter->is_locked)
            ->fiscalYear($filter->fiscal_year_id)
            ->accountingPeriod($filter->accounting_period_id)
            ->otDateFrom($filter->ot_date_from)
            ->otDateTo($filter->ot_date_to)
            ->paginate($filter->perPage ?? 15);
    }

    public function approveOvertime(OvertimeEntry $overtimeEntry)
    {
        $overtimeEntry->update([
            'status' => OvertimeStatusEnum::APPROVED,
            'approved_by'            => auth()->id(),
            'approved_at'            => now(),
        ]);

        return $overtimeEntry->fresh();
    }

    public function approveHolidayAllowance(HolidayAllowance $holidayAllowance)
    {
        $holidayAllowance->update([
            'status' => HolidayAllowancesStatus::APPROVED,
            'approved_by'            => auth()->id(),
            'approved_at'            => now(),
        ]);

        return $holidayAllowance->fresh();
    }
}
