<?php

namespace Modules\Lpj\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Modules\Lpj\Models\CustomField;
use Illuminate\Validation\Rule;

class CustomFieldRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'name' => 'required|max:255',
            'type' => 'required|in:text,select,radio,checkbox,date,number',
            'label' => 'nullable|max:255',
            'urutan_prioritas' => [
                'nullable',
                'integer',
                Rule::unique('custom_fields')->ignore($this->route('custom_field')),
            ],
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    public function prepareValidationData($data){
        if(!$this->type){
            $this->merge(['type' => 'text']);
        }

        if (!$this->urutan_prioritas) {
            $maxPrioritas = CustomField::max('urutan_prioritas') ?? 0;
            $this->merge(['urutan_prioritas' => $maxPrioritas + 1]);
        }
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'urutan_prioritas.unique' => 'Urutan prioritas sudah digunakan. Silakan pilih nomor lain.',
        ];
    }
}
