<?php

    namespace Modules\Lpj\Http\Requests;

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

    class JenisJaminanRequest extends FormRequest
    {
        /**
         * Get the validation rules that apply to the request.
         */
        public function rules()
        : array
        {
            return [
                'code'                       => 'required|max:5',
                'name'                       => 'required|max:255',
                'slug'                       => 'required|max:255',
                'jenis_legalitas_jaminan_id' => 'nullable',
                'form_kategori'              => 'required',
            ];
        }

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

        public function prepareForValidation()
        : void
        {
            if ($this->method() == 'POST') {
                $this->merge([
                    'code' => IdGenerator::generate(
                        ['table' => 'jenis_jaminan', 'length' => 5, 'prefix' => 'JJ', 'field' => 'code'],
                    ),
                ]);
            }

            $this->merge([
                'jenis_legalitas_jaminan_id' => json_encode($this->jenis_legalitas_jaminan_id),
                'form_kategori'              => json_encode($this->form_kategori),
                'slug'                       => Str::slug($this->name),
            ]);
        }
    }
