<?php

namespace Modules\Offer\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\Offer\Enums\OfferStatusEnum;
use Modules\User\Enums\UserRoleEnum;

class OfferRequest 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('offers'))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $statuses = OfferStatusEnum::values();
        $rules =
        [
            'status'=>
            [
                'required',
                'in:'.implode(',',$statuses)
            ],
            'start_date'=>
            [
                'required',
                'date'
            ],
            'store_id'=>
            [
                'required',
                Rule::exists('stores','id')->whereNull('deleted_at')
            ],
            'category_id'=>
            [
                'required',
                Rule::exists('categories','id')->whereNull('deleted_at')
            ],
            'sub_category_id'=>
            [
                'required',
                Rule::exists('categories','id')->whereNotNull('category_id')->whereNull('deleted_at')
            ],
            'product_ids'=>
            [
                'required',
                'array'
            ],
            'product_ids.*'=>
            [
                'required',
                Rule::exists('products','id')->whereNull('deleted_at')
            ]
        ];
        if (request('status') == OfferStatusEnum::SEASON->value)
        {
            $rules['end_date'] =
            [
                'required',
                'date',
                'after:start_date'
            ];
        }

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


        return $rules;
    }

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

        $attributes= [
            'logo'=>__('offers.logo'),
            'show_models'=>__('offers.show_models'),
            'show_home'=>__('offers.show_home'),
            'store_id'=>__('offers.store_id'),
            'category_id'=>__('offers.category_id'),
            'sub_category_id'=>__('offers.sub_category_id'),
            'start_date'=>__('offers.start_date'),
            'end_date'=>__('offers.end_date'),
            'product_ids'=>__('offers.product'),
        ];
        foreach (languages() as $lang) {
            $lang_attributes=[
                'title_'.$lang->local => __('offers.title').' '.$lang->local,
                'description_'.$lang->local => __('offers.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);
        }
    }
}
