<?php

namespace Modules\Unit\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\User\Enums\UserRoleEnum;
use Modules\User\Services\UserService;

class UnitRequest extends FormRequest
{
    public function __construct(
        private UserService $userService,
    )
    {}
    /**
     * 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('units'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules =
        [
            'user_code'=>
            [
                'required',
                Rule::exists('users','code')->where('role', UserRoleEnum::PROVIDER->value)->whereNull('deleted_at')
            ],
            'user_id'=>
            [
                'required'
            ],
            'type_id'=>
            [
                'required',
                Rule::exists('types','id')->whereNull('deleted_at')
            ],
            'area_id'=>
            [
                'required',
                Rule::exists('areas','id')->whereNull('deleted_at')
            ],
            'price'=> 'required|numeric|min:1|max:1000000000',
            'baths'=> 'required|numeric|min:1|max:100',
            'space'=> 'required|numeric|min:1|max:1000000000',
            'net_space'=> 'required|numeric|min:1|max:1000000000',
            'floor'=> 'nullable|numeric|min:1|max:20',
            'status'=> 'required|in:'.implode(',', config('globals.unit_statuses')),
            'sold_status'=> 'required|in:'.implode(',', config('globals.sold_statuses')),
            'image'=> 'sometimes|nullable|image|max:2048',
            'old_images'=> 'sometimes|nullable|array',
            'images'=> 'sometimes|nullable|array',
            'images.*'=> 'image|max:2048',
        ];

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


        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {

        $attributes= [
            'user_id'=>__('units.user_id'),
            'type_id'=>__('units.type_id'),
            'area_id'=>__('units.area_id'),
            'price'=>__('units.price'),
            'baths'=>__('units.baths'),
            'space'=>__('units.space'),
            'net_space'=>__('units.net_space'),
            'floor'=>__('units.floor'),
            'status'=>__('units.status'),
            'sold_status'=>__('units.sold_status'),
            'image'=>__('units.image'),

        ];
        foreach (languages() as $lang) {
            $lang_attributes=[
                'title_'.$lang->local => __('units.title').' '.$lang->local,
                'description_'.$lang->local => __('units.description').' '.$lang->local,
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }
        return $attributes;
    }

    /**
     * Add some data to be validated
     */
    public function validationData()
    {
        $data = parent::all();
        // dump($this->user);
        $user = $this->user_code ? $this->userService->getItemByCode($this->user_code) : null;
        if ($user) {
            $data['user_id'] = $user->id;
        }
        $this->replace($data); // < VIP line
        return parent::all();
    }

    /**
     * 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);
        }
    }
}
