<?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 video_type
 * @property mixed video_url
 * @property mixed images
 */
class DoctorRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (! Auth::check()) {
            return false;
        }
        if(in_array(Auth::user()->role, ['super_admin', 'admin', 'sub_admin']))
        {
            return true;
        }

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $percentagePattern = "/[+-]?([0-9]*[.])?[0-9]+/";
        $rules = [
            'show_in_chairman' => 'required|in:1,0',
            'show_in_home' => 'required|in:1,0',
            'show_in_offers' => 'required|in:1,0',
            'category_id' => 'required_if:show_in_offers,1|nullable|in:1,2,3',
            'discount_percentage' => ['required_if:show_in_offers,1', 'regex:'.$percentagePattern, 'nullable'],
            'facebook' => 'nullable|url|max:300',
            'twitter' => 'nullable|url|max:300',
            'instagram' => 'nullable|url|max:300',
            'linkedin' => 'nullable|url|max:300',
            'okadoc_url' => 'nullable|url|max:300',
        ];

        foreach (languages() as $lang) {
            $lang_rules=[
                'name_'.$lang->local=> 'required|min:3|max:100',
//                'specialist_'.$lang->local=> 'nullable|min:3',
//                'certifications_'.$lang->local=> 'nullable|min:3',
//                'trainings_'.$lang->local=> 'nullable|min:3',
//                'experiences_'.$lang->local=> 'nullable|min:3',
//                'researches_'.$lang->local=> 'nullable|min:3',
//                'professional_memberships_'.$lang->local=> 'nullable|min:3',
                'details_'.$lang->local=> 'required|min:3',
            ];
            $rules= array_merge($rules, $lang_rules);
        }

        $rules['image'] = 'required';
        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $field = metaFields('doctors');
        $local = getCurrentLocale();
        $attributes=[
            'show_in_chairman' =>  $field[$local]['show_in_chairman'] ?? __('doctors.show_in_chairman'),
            'show_in_home' =>  $field[$local]['show_in_home'] ?? __('doctors.show_in_home'),
            'show_in_offers' =>  $field[$local]['show_in_offers'] ?? __('doctors.show_in_offers'),
            'category_id' =>  $field[$local]['category_id'] ?? __('doctors.category_id'),
            'discount_percentage' =>  $field[$local]['discount_percentage'] ?? __('doctors.discount_percentage'),
            'image' =>  $field[$local]['image'] ?? __('doctors.image'),
            'facebook' =>  $field[$local]['facebook'] ?? __('doctors.facebook'),
            'twitter' =>  $field[$local]['twitter'] ?? __('doctors.twitter'),
            'instagram' =>  $field[$local]['instagram'] ?? __('doctors.instagram'),
            'linkedin' =>  $field[$local]['linkedin'] ?? __('doctors.linkedin'),
            'okadoc_url' =>  $field[$local]['okadoc_url'] ?? __('doctors.okadoc_url'),
        ];


        foreach (languages() as $lang) {
            $local = $lang->local == 'ar' ? ' (عربي) ' : ' (English) ';
            $lang_attributes=[
                'name_'.$lang->local => ($field[$lang->local]['name'] ?? __('doctors.name')) . $local,
//                'specialist_'.$lang->local => ($field[$lang->local]['specialist'] ?? __('doctors.specialist')) . $local,
//                'certifications_'.$lang->local => ($field[$lang->local]['certifications'] ?? __('doctors.certifications')) . $local,
//                'trainings_'.$lang->local => ($field[$lang->local]['trainings'] ?? __('doctors.trainings')) . $local,
//                'experiences_'.$lang->local => ($field[$lang->local]['experiences'] ?? __('doctors.experiences')) . $local,
//                'researches_'.$lang->local => ($field[$lang->local]['researches'] ?? __('doctors.researches')) . $local,
//                'professional_memberships_'.$lang->local => ($field[$lang->local]['professional_memberships'] ?? __('doctors.professional_memberships')) . $local,
                'details_'.$lang->local => ($field[$lang->local]['details'] ?? __('doctors.details')) . $local,
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }
        return $attributes;
    }

    public function messages()
    {
        return [
            'category_id.required_if' => __('doctors.category_id_validation'),
            'discount_percentage.required_if' => __('doctors.discount_percentage_validation'),
        ];
    }

    /**
     * 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));
        } elseif (Request::ajax()){
            $errors = $validator->errors()->first();
            throw new HttpResponseException(response()->json(['errors' => $errors]));
        } else {
            parent::failedValidation($validator);
        }
    }
}
