<?php

namespace Modules\Category\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\Category\Models\Category;
use Modules\Category\Services\CategoryService;
use Modules\User\Enums\UserRoleEnum;

class CategoryRequest extends FormRequest
{
    public function __construct(
        private CategoryService $categoryService,
    ){}
    /**
     * 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('categories'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $category = $this->categoryService->checkItem($this->route('category') ?? 0 );
        if($category)
        {
            if($category->lock)
            {
                return [
                    'locked'=>'required'
                ];
            }
        }
        $rules =
            [
                'start_price'=>
                    [
                        'required',
                        'numeric'
                    ],
                'end_price' => [
                    'required',
                    'numeric',
                    'gt:start_price',
                    function ($attribute, $value, $fail) {
                        $start = $this->input('start_price');
                        $end   = $this->input('end_price');

                        $exists = Category::where(function ($query) use ($start, $end) {
                            $query->whereBetween('start_price', [$start, $end])
                                ->orWhereBetween('end_price', [$start, $end])
                                ->orWhere(function ($q) use ($start, $end) {
                                    $q->where('start_price', '<', $start)
                                        ->where('end_price', '>', $end);
                                });
                        })
                            ->when($this->route('budget_range'), function($query) {
                                $query->where('id', '!=', $this->route('budget_range')->id);
                            })
                            ->exists();

                        if ($exists) {

                            $attributes = $this->attributes();
                            $failMessage = str_replace(
                                [':start', ':end'],
                                [$attributes['start_price'], $attributes['end_price']],
                                'The given :start and :end range overlaps with an existing one.'
                            );
                            $fail($failMessage);
                        }
                    },
                ],
            ];


        foreach (languages() as $lang)
        {
            $lang_rules=[
                'title_'.$lang->local=> 'required|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= [
            'start_price'=>__('categories.start_price'),
            'end_price'=>__('categories.end_price'),
        ];
        $languages = languages();
        foreach ($languages as $lang) {
            $lang_attributes=[
                'title_'.$lang->local => __('categories.title') . (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);
        }
    }
}
