<?php

namespace App\Http\Requests\Admin;

use App\Models\Attribute;
use App\Models\Category;
use App\Enums\ProductCostStatusEnum;
use App\Models\CategoryAttribute;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class ProductRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (! Auth::check()) {
            return false;
        }
        if(in_array(Auth::user()->role, ['super_admin', 'admin', 'sub_admin']))
        {
            return true;
        }

        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=[
            'image'=>'required',
            // 'code'=> [
            //     "sometimes",
            //     Rule::unique('products')->ignore($this->product? $this->product->id : 0, 'id')
            // ],
            'status' => 'required|in:all,users',
            'count'=>'sometimes|nullable|numeric|min:0',
            'most_sale'=>'required|in:true,false',
            'category_id'=>'required|exists:categories,id',
            'min_order'=>'required|numeric|min:1',
            'num_buy'=>'sometimes|numeric|nullable|min:1',
            'video'=>'sometimes|url|nullable',
            'images.*'=>'required',
            'rates.*.rate'=>'required|in:1,2,3,4,5',
            'rates.*.name'=>'required',
            'rates.*.comment' => 'required',
            'rates.*.image'=>'sometimes',
        ];
        if(request('code'))
        {
            $rules['code'] = [
                "required",
                Rule::unique('products')->ignore($this->product? $this->product->id : 0, 'id')
            ];
        }
        
        if(request('category_id') )
        {
            $category = Category::find( request('category_id') );
            
            if($category->main_id)
            {
                $rules['count'] = 'sometimes|nullable|numeric';
            }
            else
            {
                $rules['count'] = 'required|numeric';
            }
            $ones = CategoryAttribute::where('category_id',request('category_id'))->pluck('attribute_id')->toArray();
            foreach($ones as $one)
            {
                $rules['one.'.$one.'.choice_id'] = 'sometimes|nullable|exists:choices,id';
            }
            if($category->brand_status == 'true')
            {
                $rules['brand_id'] = 'required|exists:brands,id';
            }
            if($category->gender_status == 'true')
            {
                $rules['gender'] = 'required|in:male,female';
            }
        }
//        if( !is_null( request('category_id') ) )
//        {
//            $category = Category::find( request('category_id') );
//            $main_ids = CategoryAttribute::where('category_id',request('category_id'))->pluck('attribute_id')->toArray();
//            $sub_ids = Attribute::whereIn('attribute_id',$main_ids)->pluck('id')->toArray();
//            $ids= array_merge($sub_ids, $main_ids);
//            $attributes = Attribute::find($ids);
//            if($category->brand_status)
//            {
//                $rules['brand_id'] = 'required|exists:brands,id';
//            }
//            $categories_count = Category::where('category_id',$category->id)->count();
//            if($categories_count > 0)
//            {
//                $rules['model_id'] = 'required|exists:categories,id';
//            }
//            foreach ($attributes as $row)
//            {
//                $rules['attributes.'.$row->id.'.choice_id'] = 'required|exists:choices,id';
//                if($row->count_status == 'true')
//                {
//                    $rules['attributes.'.$row->id.'.count'] = 'required|numeric';
//                }
//                if($row->image_status == 'true')
//                {
//                    $rules['attributes.'.$row->id.'.image'] = 'required';
//                }
//            }
//        }
        $cost_status = ProductCostStatusEnum::status();
        foreach ($cost_status as $status)
        {
            $rules['costs.'.$status.'.cost'] = 'required|numeric';
            $rules['costs.'.$status.'.cost_discount'] = 'sometimes|nullable|numeric|lt:'.request('costs.'.$status.'.cost');
        }
        foreach (languages() as $lang) {
            $lang_rules=[
                'name_'.$lang->local=> 'required',
                'description_'.$lang->local=> 'required',
            ];
            $rules= array_merge($rules, $lang_rules);
        }
        return $rules;
    }

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

        $field = metaFields('products');
        $attributes=[
            'video' => __('products.video'),
            'image' => __('products.image'),
            'status' => __('products.status'),
            'category_id' => __('products.category_id'),
            'code' => __('products.code'),
            'city_id' => __('products.city_id'),
            'count' => __('products.count'),
            'cost_discount' => __('products.cost_discount'),
            'cost' => __('products.cost'),
            'most_sale' => __('products.most_sale'),
            'brand_id' => __('products.brand_id'),
            'gender' => __('products.gender'),
            'num_buy' => __('products.num_buy'),
            'model_id' => __('products.model_id'),
            'min_order'=>__('products.min_order'),

        ];

        $cost_status = ProductCostStatusEnum::status();
        foreach ($cost_status as $status)
        {
            $lang_attributes=[
                'costs.'.$status.'.cost'=>  __('products.cost') .' '.__('web.'.$status),
                'costs.'.$status.'.cost_discount'=>  __('products.cost_discount') .' '.__('web.'.$status),
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }
        foreach (languages() as $lang) {
            $lang_attributes=[
                'name_'.$lang->local=>  __('products.name') .' '.$lang->local,
                'description_'.$lang->local=>  __('products.description') .' '.$lang->local,
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }
        if( !is_null( request('category_id') ) )
        {
            $ones = CategoryAttribute::where('category_id',request('category_id'))->pluck('attribute_id')->toArray();
            foreach($ones as $one)
            {
                $attribute = Attribute::withDescription()->find($one);
                $attributes['one.'.$one.'.choice_id'] = $attribute->name;
            }
        }
        if( !is_null( request('attributes') ) )
        {
            foreach(request('attributes') as $key=>$row)
            {
                $attribute = Attribute::withDescription()->find($key);
                $choiceTitle =
                    [
                        'attributes.'.$key.'.count' =>  __('products.count') .' : '.$attribute->name,
                        'attributes.'.$key.'.image' =>  __('products.image') .' : '.$attribute->name,
                        'attributes.'.$key.'.choice_id' =>  __('products.choice') .' : '.$attribute->name,
                    ];
                $attributes = array_merge($attributes, $choiceTitle);
            }
        }
        if( !is_null( request('rates') ) )
        {
            $i = 1;
            foreach(request('rates') as $key=>$row)
            {
                $choiceTitle =
                    [
                        'rates.'.$key.'.rate' =>  __('rates.rate') . ' '. $i,
                        'rates.'.$key.'.name' =>  __('rates.name'). ' '. $i,
                        'rates.'.$key.'.comment' =>  __('rates.comment'). ' '. $i,
                        'rates.'.$key.'.image' =>  __('products.image') . ' '. $i,
                    ];
                $attributes = array_merge($attributes, $choiceTitle);
                ++$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);
        }
    }
}
