<?php

namespace Modules\Warehouse\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\Warehouse\Enums\UpgradeWarehouseEnum;

class WarehouseRequest extends FormRequest
{
    /**
     * 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('warehouses'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules =
        [
            'latitude'=>
            [
                'nullable',
            ],
            'longitude'=>
            [
                'nullable',
            ],
            'phone'=>
            [
                'required',
                'numeric'
            ],
            'postal_number'=>
            [
                'required',
                'numeric'
            ],
            'upgrade_warehouse'=>
            [
                'required',
                'in:'.implode(',',UpgradeWarehouseEnum::values())
            ],
            'store_id'=>
            [
                'required',
                Rule::exists('stores','id')->whereNull('deleted_at')
            ],
            'country_id'=>
            [
                'required',
                Rule::exists('countries','id')->whereNull('deleted_at')
            ],
            'region_id'=>
            [
                'required',
                Rule::exists('regions','id')->whereNull('deleted_at')
            ],
            'city_id'=>
            [
                'required',
                Rule::exists('cities','id')->whereNull('deleted_at')
            ],
            'area_id'=>
            [
                'required',
                Rule::exists('areas','id')->whereNull('deleted_at')
            ],
            'warehouse_id'=>
            [
                'nullable',
                Rule::exists('warehouses','id')->whereNull('deleted_at')
            ],
            'warehouse_category_id'=>
            [
                'required',
                Rule::exists('warehouse_categories','id')->whereNull('deleted_at')
            ],

        ];
        if (!request('latitude') || !request('longitude'))
        {
            $rules['map'] = 'required';
        }
        foreach (languages() as $lang)
        {
            $lang_rules=[
                'title_'.$lang->local=> 'required|max:100',
                'address_'.$lang->local=> 'required|max:500',
                'work_hours_'.$lang->local=> 'required|max:500',
                'description_'.$lang->local=> 'required',
            ];
            $rules= array_merge($rules, $lang_rules);
        }


        return $rules;
    }

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

        $attributes= [
            'phone'=>__('warehouses.phone'),
            'postal_number'=>__('warehouses.postal_number'),
            'upgrade_warehouse'=>__('warehouses.upgrade_warehouse'),
            'store_id'=>__('warehouses.store_id'),
            'country_id'=>__('warehouses.country_id'),
            'region_id'=>__('warehouses.region_id'),
            'city_id'=>__('warehouses.city_id'),
            'area_id'=>__('warehouses.area_id'),
            'warehouse_id'=>__('warehouses.warehouse_id'),
            'map'=>__('warehouses.map'),
            'warehouse_category_id'=>__('warehouses.warehouse_category_id'),

        ];
        foreach (languages() as $lang) {
            $lang_attributes=[
                'title_'.$lang->local => __('warehouses.title').' '.$lang->local,
                'address_'.$lang->local => __('warehouses.address').' '.$lang->local,
                'work_hours_'.$lang->local => __('warehouses.work_hours').' '.$lang->local,
                'description_'.$lang->local => __('warehouses.description').' '.$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);
        }
    }
}
