<?php

namespace Modules\Product\Requests\Store;

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\Product\Enums\ProductStatusEnum;
use Modules\User\Enums\UserRoleEnum;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules=[
            'category_id'=>[
                'required',
                'exists:categories,id'
            ],
            'sub_category_id'=>[
                'required',
                'exists:categories,id'
            ],
            'count'=>[
                'required',
                'numeric'
            ],
            'cost'=>[
              'required',
              'numeric'
            ],
            'cost_discount'=>[
                'nullable',
                'numeric'
            ],
            'items.*.cost'=>[
                'required',
                'numeric'
            ],
            'additions.*.cost'=>[
                'required',
                'numeric'
            ],
            'product_items.*.items.*.cost'=>[
                'required',
                'numeric'
            ],
        ];

        foreach (languages() as $lang) {
            $lang_rules=[
                'title_'.$lang->local=> 'required|max:35',
                'description_'.$lang->local=> 'required|max:35',
                'additions.*.title_'.$lang->local=>'required|max:100',
                'product_items.*.title_'.$lang->local=>'required|max:100',
                'product_items.*.items.*.title_'.$lang->local=>'required|max:100',
            ];
            $rules= array_merge($rules, $lang_rules);
        }
        if (!$this->product)
        {
            $rules['image'] = 'required';
        }
        else
        {
            $rules['image'] = 'sometimes';
        }
        return $rules;
    }

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

        $attributes= [
            'category_id'=>__('products.category_id'),
            'sub_category_id'=>__('products.sub_category_id'),
            'count'=>__('products.count'),
            'cost'=>__('products.cost'),
            'image'=>__('products.image'),
            'cost_discount'=>__('products.cost_discount'),
        ];
        foreach (languages() as $lang) {
            $lang_attributes=[
                'title_'.$lang->local => $service->{'title_'.$lang->local} ?? __('products.title').' '.$lang->local,
                'description_'.$lang->local => $service->{'description_'.$lang->local} ?? __('products.description').' '.$lang->local,
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }

        if( @request('additions') )
        {
            $i = 0;
            foreach(request('additions') as $key=>$row)
            {
                $lang_attribute=[
                    'additions.'.$key.'.cost' => __('products.cost').' '. __('products.addition') . ' ( '. ($i+1) . ' )',
                ];
                $attributes= array_merge($attributes, $lang_attribute);
                foreach (languages() as $lang)
                {
                    $lang_attribute=[
                        'additions.'.$key.'.title_'.$lang->local => __('products.title').' '. __('products.addition') .' ' .$lang->local. ' ( '. ($i+1) . ' )',
                    ];
                    $attributes= array_merge($attributes, $lang_attribute);
                }
                ++$i;
            }
        }
        if( @request('product_items') )
        {
            $i = 0;
            foreach(request('product_items') as $key=>$row)
            {
                foreach (languages() as $lang)
                {
                    $lang_attribute=[
                        'product_items.'.$key.'.title_'.$lang->local => __('products.title').' '. __('products.product_item') .' ' .$lang->local. ' ( '. ($i+1) . ' )',
                    ];
                    $attributes= array_merge($attributes, $lang_attribute);

                    if( isset( $row['items'] ) )
                    {
                        $j = 0;
                        foreach($row['items'] as $keyItem=>$item)
                        {
                            $attribute=[
                                'product_items.'.$key.'.items.'.$keyItem.'.cost' => __('products.item').' ' . ($i+1) .' - '. __('products.cost').' ' . ($j+1) ,
                            ];
                            foreach (languages() as $lang)
                            {
                                $lang_attribute=[
                                    'product_items.'.$key.'.items.'.$keyItem.'.title_'.$lang->local => __('products.item').' ' . ($i+1) .' - '. __('products.title').' ' .  $lang->local. ' ( '. ($i+1) . ' )',
                                ];
                                $attributes= array_merge($attributes, $lang_attribute);
                            }
                            $attributes= array_merge($attributes, $attribute);
                            ++$j;
                        }
                    }
                }
                ++$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);
        }
    }
}
