<?php

namespace App\Modules\HR\EmployeeSelfService\Requests;

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

class MeStoreAttendanceCorrectionRequest extends FormRequest
{
    protected function prepareForValidation(): void
    {
        $m = [];
        foreach (['requested_check_in', 'requested_check_out'] as $k) {
            if ($this->input($k) === '') {
                $m[$k] = null;
            }
        }
        if ($m !== []) {
            $this->merge($m);
        }
    }

    public function authorize(): bool
    {
        $u = $this->user();

        return $u !== null
            && ! $u->is_admin
            && $u->tenant_id !== null
            && $u->employee_id !== null;
    }

    /**
     * @return array<string, array<int, string|\Illuminate\Validation\Rules\In>>
     */
    public function rules(): array
    {
        $tid = (int) $this->user()->tenant_id;
        $eid = (int) $this->user()->employee_id;

        return [
            'attendance_record_id' => [
                'required',
                'integer',
                Rule::exists('attendance_records', 'id')->where(
                    fn ($q) => $q->where('tenant_id', $tid)->where('employee_id', $eid),
                ),
            ],
            'type' => ['required', 'string', Rule::in(AttendanceCorrectionType::all())],
            'requested_check_in' => ['nullable', 'date'],
            'requested_check_out' => ['nullable', 'date'],
            'reason' => ['required', 'string', 'max:5000'],
        ];
    }
}
