<?php

namespace Modules\Company\Requests\Employee;

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\Company\Services\CompanyService;
use Modules\User\Enums\UserRoleEnum;

class CompanyRequest extends FormRequest
{
    public function __construct(
        private CompanyService $companyService,
    ){}
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $role = UserRoleEnum::employees();
        if (! Auth::check()) {
            return false;
        }
        if(!in_array(Auth::user()->role, $role))
        {
            return false;
        }
        if(Auth::user()->hasModule('companies'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $company = $this->companyService->checkItem($this->company ?? 0 );
        if($company)
        {
            if($company->lock)
            {
                return [
                    'locked'=>'required'
                ];
            }
        }
        $rules =
        [
            'domain'=>
            [
                'nullable',
                'url'
            ],
            'image'=>
            [
                $this->company ? 'nullable' : 'required',
                'image',
                'mimes:svg,png'
            ],
            'latitude'  =>
            [
                'nullable',
                'regex:/^-?([1-8]?[0-9](\.\d+)?|90(\.0+)?)$/'
            ],
            'longitude' =>
            [
                'nullable',
                'regex:/^-?((1[0-7][0-9]|[0-9]{1,2})(\.\d+)?|180(\.0+)?)$/'
            ],
            'sector_id'=>
            [
                'required',
                Rule::exists('sectors','id')->whereNull('deleted_at')
            ],
            'country_id'=>
            [
                'required',
                Rule::exists('countries','id')->whereNull('deleted_at')
            ],
            'region_id'=>
            [
                'required',
                Rule::exists('regions','id')->whereNull('deleted_at')
            ],
        ];

        if (!request('latitude') || !request('longitude'))
        {
            $rules['map'] = 'required';
        }

        foreach (languages() as $lang)
        {
            $lang_rules=[
                'title_'.$lang->local=> [
                    'required',
                    'string',
                    'max:50',
                    function($attribute, $value, $fail) use ($lang) {
                        $region_id = $this->input('region_id');
                        $exists = $this->companyService->getCompanyDescription(
                            [
                                'title'=>$value,
                                'region_id'=>$region_id,
                                'not_company_id'=>$this->company ?? null,
                            ]);

                        if ($exists)
                        {
                            $fail(__('companies.title_exist_in_region'));
                        }
                    }
                ],
                'description_'.$lang->local=> 'nullable|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= [
            'domain'=>__('companies.domain'),
            'image'=>__('companies.image'),
            'map'=>__('companies.map'),
            'sector_id'=>__('companies.sector_id'),
            'country_id'=>__('companies.country_id'),
            'region_id'=>__('companies.region_id'),
        ];
        $languages = languages();
        foreach ($languages as $lang) {
            $lang_attributes=[
                'title_'.$lang->local => __('companies.title') . (count($languages) > 1 ? ' '.$lang->local : '' ),
                'description_'.$lang->local => __('companies.description') . (count($languages) > 1 ? ' '.$lang->local : '' ),
                'address_'.$lang->local => __('companies.address') . (count($languages) > 1 ? ' '.$lang->local : '' ),
            ];
            $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 {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
