<?php

namespace App\Http\Requests;

use App\Libs\Security\XSSCleanFilter;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use App\Libs\Support\Sanitizer\Traits\SanitizesInput;
use Illuminate\Validation\ValidationException;

class UserAddress extends FormRequest
{
    use SanitizesInput;
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    public function validationData(): array
    {
        return [
            'id'            => $this->input('id'),
            'address'       => $this->input('address'),
            'houseNo'       => $this->input('houseNo'),
            'zip'           => $this->input('zip'),
            'city'          => $this->input('city'),
            'country'       => $this->input('country'),
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules():array
    {
        return [
            'id'            => 'required|numeric',
            'address'       => 'required|string|max:255',
            'houseNo'       => 'required|string|max:10',
            'zip'           => 'required|string|max:10',
            'city'          => 'required|string|max:50',
            'country'       => 'required|string|max:50'
        ];
    }

    public function filters() {
        return [
            'id'            => "trim|strip_tags|xss_clean",
            'address'       => "trim|strip_tags|xss_clean",
            'houseNo'       => "trim|strip_tags|xss_clean",
            'zip'           => "trim|strip_tags|xss_clean",
            'city'          => "trim|strip_tags|xss_clean",
            'country'       => "trim|strip_tags|xss_clean",
        ];
    }

    public function all($keys = null)
    {
        $data = parent::all();
        if ($this->route()->hasParameters()) {
            $parameterName = $this->route()->parameterNames()[0];
            $data['id'] = $this->route()->parameter($parameterName);
        }
        return $data;
    }

    public function customFilters()
    {
        return ['xss_clean' => XSSCleanFilter::class];
    }

    protected function failedValidation(Validator $validator)
    {
        throw (new ValidationException($validator))
            ->errorBag($this->errorBag);
    }
}
