<?php

namespace App\Modules\HR\Attendance\Requests;

use App\Modules\HR\Attendance\Support\AttendanceRecordStatus;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class StoreManualAttendanceRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('attendance.create') ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $tenantId = $this->user()?->tenant_id;

        return [
            'employee_id' => [
                'required',
                'integer',
                Rule::exists('employees', 'id')->where(fn ($q) => $q->where('tenant_id', $tenantId)),
            ],
            'attendance_date' => ['required', 'date'],
            'check_in_at' => ['nullable', 'date'],
            'check_out_at' => ['nullable', 'date', 'after_or_equal:check_in_at'],
            'status' => ['required', 'string', Rule::in([
                AttendanceRecordStatus::PRESENT,
                AttendanceRecordStatus::ABSENT,
                AttendanceRecordStatus::LATE,
                AttendanceRecordStatus::HALF_DAY,
                AttendanceRecordStatus::HOLIDAY,
            ])],
            'notes' => ['nullable', 'string', 'max:2000'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator): void {
            if ($validator->errors()->isNotEmpty()) {
                return;
            }
            $checkOut = $this->input('check_out_at');
            if ($checkOut === null || $checkOut === '') {
                return;
            }
            $user = $this->user();
            if ($user === null || ! $user->can('registerCheckout', \App\Modules\HR\Attendance\Models\AttendanceRecord::class)) {
                $validator->errors()->add('check_out_at', __('attendance.validation.checkout_register_denied'));
            }
        });
    }
}
