<?php

namespace App\Http\Requests\Admin\HR;

use App\Enums\LeaveRequestStatus;
use App\Models\LeaveRequest;
use Illuminate\Foundation\Http\FormRequest;

class LeaveRequestRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('leave_requests.create')
            || $this->user()->can('leave_requests.update');
    }

    public function rules(): array
    {
        $leaveRequest = $this->route('leaveRequest');

        return [
            'start_date' => [
                'required',
                'date',
                'after:today',
                function ($attribute, $value, $fail) use ($leaveRequest) {
                    $employee = $this->user()->employee;

                    if (! $employee) {
                        return;
                    }

                    $query = LeaveRequest::where('employee_id', $employee->id)
                        ->where('start_date', $value)
                        ->where('status', '!=', LeaveRequestStatus::CANCELLED);

                    if ($leaveRequest) {
                        $query->where('id', '!=', $leaveRequest->id);
                    }

                    if ($query->exists()) {
                        $fail('Anda sudah mengajukan cuti pada tanggal ini.');
                    }
                },
            ],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
        ];
    }

    public function attributes(): array
    {
        return [
            'start_date' => 'tanggal mulai',
            'end_date' => 'tanggal selesai',
        ];
    }
}
