<?php

    namespace Modules\Lpj\Http\Requests;

    use Illuminate\Foundation\Http\FormRequest;

    class PemilikJaminanRequest extends FormRequest
    {
        /**
         * Get the validation rules that apply to the request.
         */
        public function rules()
        : array
        {
            $rules = [
                'debiture_id'                 => 'required|exists:debitures,id',
                'npwp'                        => 'nullable|string|max:16',
                'email'                       => 'nullable|email|max:100',
                'phone'                       => 'nullable|string|max:20',
                'hubungan_pemilik_jaminan_id' => 'nullable|exists:hubungan_pemilik_jaminan,id',
                'province_code'               => 'nullable|exists:provinces,code',
                'city_code'                   => 'nullable|exists:cities,code',
                'district_code'               => 'nullable|exists:districts,code',
                'village_code'                => 'nullable|exists:villages,code',
                'name'                        => 'required',
                'address'                     => 'nullable|string',
                'postal_code'                 => 'nullable|string|max:10',
                'status'                      => 'nullable|boolean',
                'detail_sertifikat'           => 'nullable|string|max:255',
            ];

            //$rules['nomor_id'] = 'nullable|max:16|unique:pemilik_jaminan,nomor_id,debiture_id,' . $this->debiture_id;
	    $rules['nomor_id'] = 'nullable|max:16|unique:pemilik_jaminan,debiture_id,' . $this->debiture_id;
            return $rules;
        }

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

        public function prepareForValidation() {

            $detailSertifikat = [];
            $names = $this->input('detail_sertifikat.name', []);
            $nomorIds = $this->input('detail_sertifikat.nomor_id', []);

            foreach ($names as $index => $name) {
                if (isset($nomorIds[$index])) {
                    $detailSertifikat[] = [
                        'name' => $name,
                        'nomor_id' => $nomorIds[$index]
                    ];
                }
            }

            $this->merge([
                'detail_sertifikat' => json_encode($detailSertifikat),
            ]);
        }
    }
