<?php

namespace App\Http\Requests\Admin\Master;

use App\Traits\NotificationTrait;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class UserRequest extends FormRequest
{
    use NotificationTrait;

    public function authorize(): bool
    {
        return Auth::check();
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'base_salary' => removeRupiahFormatting($this->base_salary),
        ]);
    }

    public function rules(): array
    {
        $userId = $this->user->id ?? null;
        $isEdit = $this->isMethod('put');
        $isUserUrl = $this->is('dashboard/master/user*');

        $rules = [
            'full_name' => ['required', 'string',  'max:255'],
            'username' => ['required', 'string', 'min:5', 'max:15', Rule::unique('users', 'username')->ignore($userId)],
            'email' => ['required', 'email', 'max:255', Rule::unique('users', 'email')->ignore($userId)],
            'contact_number' => ['required', 'string', 'regex:/^\+?[0-9]{10,15}$/'],
            'pob' => ['required', 'string', 'max:75'],
            'dob' => ['required', 'date', 'before:today'],
            'address' => ['required', 'string', 'max:65535'],
            'avatar' => $isEdit
                ? ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048']
                : ['required', 'image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
            'ktp' => $isEdit
                ? ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048']
                : ['required', 'image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
            'gender' => ['required', Rule::in(['1', '2'])],
        ];

        if ($isUserUrl) {
            $rules = array_merge($rules, [
                'entry_date' => ['required', 'date'],
                'base_salary' => ['required', 'numeric', 'min:0', 'max:9999999999.99'],
                'sop' => ['nullable', 'string', 'max:65535'],
                'barbershop' => ['required', Rule::exists('barbershop', 'id')],
                'role' => ['required', Rule::exists('roles', 'id')],
            ]);
        }

        return $rules;
    }

    protected function failedValidation(Validator $validator): void
    {
        $this->handleValidationFailure($validator);
    }
}
