<?php

namespace App\Http\Requests;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
 * @property mixed latitude
 * @property mixed images
 */
class LocationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (! Auth::check()) {
            return false;
        }
        if(Auth::user()->role == 'admin' )
        {
            return true;
        }

        if(Auth::user()->hasModule('locations'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $latitudeRegx= '/^((([0-8]?[0-9])(\.(\d{1,8}))?)|(90(\.0{1,8})?))$/';
        $longitudeRegx= '/^((((1[0-7][0-9])|([0-9]?[0-9]))(\.(\d{1,8}))?)|180(\.0{1,8})?)$/';
        $rules=[
            'latitude' => ['required', 'numeric', 'max:180'],
            'longitude' => ['required', 'numeric', 'max:180'],
            'phone' => ['required', 'max:180'],
            'fax' => ['required', 'max:180'],
            'email' => ['required', 'email', 'max:180'],
            // 'latitude' => ['required','regex:'.$latitudeRegx, 'min:7'],
            // 'longitude' => ['required','regex:'.$longitudeRegx,'min:7']
        ];

        foreach (languages() as $lang) {
            $lang_rules=[
                'name_'.$lang->local=> 'required|min:3|max:250',
                'address_'.$lang->local=> 'required|min:3|max:250',
                'box_'.$lang->local=> 'required|min:3|max:100',
                'slug_'.$lang->local=> 'required|min:3|max:100',
                'meta_description_'.$lang->local=> 'required|min:3|max:400',
                'keywords_'.$lang->local=> 'required|min:3|max:400',
                'description_'.$lang->local=> 'required|min:3',
            ];
            $rules= array_merge($rules, $lang_rules);
        }

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $field = metaFields('locations');
        $attributes=[
            'latitude' => $field->{'latitude'.getCurrentLocale()} ?? __('locations.latitude'),
            'longitude' => $field->{'longitude'.getCurrentLocale()} ?? __('locations.longitude'),
            'phone' => $field->{'phone'.getCurrentLocale()} ?? __('locations.phone'),
            'fax' => $field->{'fax'.getCurrentLocale()} ?? __('locations.fax'),
            'email' => $field->{'email'.getCurrentLocale()} ?? __('locations.email')
        ];

        foreach (languages() as $lang) {
            $lang_attributes=[
                'name_'.$lang->local => $field[$lang->local]['name'] ?? __('locations.name'),
                'address_'.$lang->local => $field[$lang->local]['address'] ?? __('locations.address'),
                'box_'.$lang->local => $field[$lang->local]['box'] ?? __('locations.box'),
                'slug_'.$lang->local => $field[$lang->local]['slug'] ?? __('locations.slug'),
                'meta_description_'.$lang->local => $field[$lang->local]['meta_description'] ?? __('locations.meta_description'),
                'keywords_'.$lang->local => $field[$lang->local]['keywords'] ?? __('locations.keywords'),
                'description_'.$lang->local => $field[$lang->local]['description'] ?? __('locations.description'),
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }
        return $attributes;
    }


    /**
     * Handle a failed validation attempt.
     *
     * Override the parent method action if the request is for AJAX
     *
     * @param Validator $validator
     * @return void
     *
     * @throws ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        // Change response attitude if the request done via Ajax requests like API requests
        if(Request::wantsJson()){
            $errors = (new ValidationException($validator))->errors();
            throw new HttpResponseException(response()->json(['errors' => $errors], 422));
        } else {
            parent::failedValidation($validator);
        }
    }
}
