<?php

    namespace Modules\Lpj\Http\Requests;

    use daengdeni\LaravelIdGenerator\IdGenerator;
    use Illuminate\Foundation\Http\FormRequest;
    use Illuminate\Support\Str;

    class JenisLegalitasJaminanRequest extends FormRequest
    {
        /**
         * Get the validation rules that apply to the request.
         */
        public function rules()
        : array
        {
            return [
                'code'              => 'required|max:6',
                'name'              => 'required|max:255',
                'slug'              => 'required|max:255',
                'custom_field'      => 'nullable|max:255',
                'custom_field_type' => 'nullable|max:255',
                'custom_fields'     => 'nullable|array',
                'custom_fields.*' => 'required|string|max:255',
            ];
        }

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

        public function prepareForValidation()
        {
            if ($this->method() == 'POST' && $this->code == null) {
                $this->merge([
                    'code' => IdGenerator::generate(
                        ['table' => 'jenis_legalitas_jaminan', 'length' => 6, 'prefix' => 'JLJ', 'field' => 'code'],
                    ),
                    'slug' => Str::slug($this->name),
                ]);
            } else {
                $this->merge([
                    'slug' => Str::slug($this->name),
                ]);
            }

            // Ensure custom_fields is always an array
            if (!is_array($this->custom_fields)) {
                $this->merge(['custom_fields' => []]);
            }
        }
    }
