<?php

namespace Modules\ContactList\Requests\Admin;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Modules\ContactList\Enums\ContactDecisionEnum;
use Modules\ContactList\Enums\ContactStatusEnum;
use Modules\ContactList\Services\ContactListService;
use Modules\User\Enums\UserRoleEnum;
use Modules\ContactList\Enums\GenderEnum;

class ContactListRequest extends FormRequest
{
    public function __construct(
        private ContactListService $contactListService,
    ){}

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $role = UserRoleEnum::admins();
        if (! Auth::check()) {
            return false;
        }
        if(!in_array(Auth::user()->role, $role))
        {
            return false;
        }
        if(Auth::user()->hasModule('contact_lists'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $contactList = $this->contactListService->checkItem($this->contact_list ?? 0 );
        if($contactList)
        {
            if($contactList->lock)
            {
                return [
                    'locked'=>'required'
                ];
            }
        }
        $genders = GenderEnum::values();
        $statuses = ContactStatusEnum::values();
        $decision_statuses = ContactDecisionEnum::values();
        $rules =
        [
            'role'=>
            [
                'required',
                'string',
                'max:35'
            ],
            'image'=>
            [
                // $this->contact_list ? 'nullable' : 'required',
                'nullable',
                'image',
                'mimes:jpg,png,jpeg'
            ],
            'email'  =>
            [
                'required',
                'email'
            ],
            'status'=>
            [
                'required',
                'in:'.implode(',',$statuses)
            ],
            'decision_maker_status'=>
            [
                'nullable',
                'in:'.implode(',',$decision_statuses)
            ],
            'budget'  =>
            [
                'nullable',
                'numeric'
            ],
            'avg_stand_annual'  =>
            [
                'nullable',
                'numeric'
            ],
            'avg_events_annual'  =>
            [
                'nullable',
                'numeric'
            ],
            'company_website'  =>
            [
                'nullable',
                'url'
            ],
            'phones.*.phone' =>
            [
                'required',
                'regex:/^[0-9+\-]+$/'
            ],
            // 'phones.*.country_id' =>
            // [
            //     'required',
            //     Rule::exists('countries','id')->whereNull('deleted_at')
            // ],
            'gender'=>
            [
                'required',
                'in:'.implode(',',$genders)
            ],
            'country_id'=>
            [
                'required',
                Rule::exists('countries','id')->whereNull('deleted_at')
            ],
            'company_id'=>
            [
                'required',
                Rule::exists('companies','id')->whereNull('deleted_at')
            ],
            'employee_id'=>
            [
                'required',
                Rule::exists('users','id')->whereIn('role',UserRoleEnum::employees())->whereNull('deleted_at')
            ],
            'is_top_customer'=>
            [
                'nullable',
                'boolean'
            ],
            'note'=>
            [
                'nullable',
                'string',
                'max:1000'
            ]
        ];


        foreach (languages() as $lang)
        {
            $lang_rules=[
                'title_'.$lang->local=> 'required|max:50',
                'address_'.$lang->local=> 'nullable|max:50',
            ];
            $rules= array_merge($rules, $lang_rules);
        }


        return $rules;
    }

    public function messages()
    {
        return [
            'locked.required'=>__('dashboard.locked'),
        ];
    }
    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {

        $attributes= [
            'role'=>__('contact_lists.role'),
            'image'=>__('contact_lists.image'),
            'email'=>__('contact_lists.email'),
            'phone'=>__('contact_lists.phone'),
            'country_id'=>__('contact_lists.country_id'),
            'company_id'=>__('contact_lists.company_id'),
            'employee_id'=>__('contact_lists.employee_id'),
            'gender'=>__('contact_lists.gender'),
            'status'=>__('contact_lists.status'),
            'decision_maker_status'=>__('contact_lists.decision_maker_status'),
            'budget'=>__('contact_lists.budget'),
            'avg_stand_annual'=>__('contact_lists.avg_stand_annual'),
            'avg_events_annual'=>__('contact_lists.avg_events_annual'),
            'company_website'=>__('contact_lists.company_website'),
            'note'=>__('contact_lists.note'),
        ];
        $languages = languages();
        foreach ($languages as $lang) {
            $lang_attributes=[
                'title_'.$lang->local => __('contact_lists.title') . (count($languages) > 1 ? ' '.$lang->local : '' ),
                'address_'.$lang->local => __('contact_lists.address') . (count($languages) > 1 ? ' '.$lang->local : '' ),
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }

        if (request('phones'))
        {
            $i = 1;
            foreach (request('phones') as $key=>$phone) {
                $attributes['phones.'.$key.'.phone']=__('contact_lists.phone') .' '. $i;
                $attributes['phones.'.$key.'.country_id']=__('contact_lists.country_id') .' '. $i;
                $i++;
            }
        }
        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 {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
