<?php

namespace Modules\Store\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\Coupon\Enums\CouponDiscountStatusEnum;
use Modules\Coupon\Enums\CouponStatusEnum;
use Modules\Store\Enums\StoreDayEnum;
use Modules\Store\Enums\StoreStatusAccountEnum;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $statuses_account = StoreStatusAccountEnum::values();
        $rules=[
            'name'=> 'required|min:3|max:100',
            'phone'=> [
                "required",
                "numeric",
                "digits:9",
                Rule::unique('users')->ignore($this->user? $this->user->id : 0, 'id')
            ],
            'email'=> [
                'required',
                'email',
                Rule::unique('users')->ignore($this->user? $this->user->id : 0, 'id')
            ],
            'category_id'=>[
                'required',
                'exists:categories,id'
            ],
            'sub_category_id'=>[
                'required',
                'exists:categories,id'
            ],
            'min_order'=>[
                'required',
                'numeric',
                'min:1'
            ],
            'logo'=>[
                'required',
            ],
            'header'=>[
                'required',
            ],
            'bank_account'=>[
                'required',
                'min:3'
            ],
            'bank_num'=>[
                'required',
                'min:3'
            ],
            'iban'=>[
                'required',
                'min:3'
            ],
            'bank'=>[
                'required',
                'min:3',
                'max:100'
            ],
            'status_account'=>[
                'required',
                'in:'.implode(',',$statuses_account)
            ],
        ];
        $days = StoreDayEnum::values();
        foreach ($days as $row)
        {
            $rules['days.'.$row.'.start_time'] = 'required';
            $rules['days.'.$row.'.end_time'] = 'required';
        }

        if (request('status_account') == StoreStatusAccountEnum::MEMBER->value)
        {
            $rules['user_id_front_image'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['user_id_back_image'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['iban_card'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['license_work'] = [
                $this->store ? 'sometimes':'required',
                'mimes:pdf'
            ];
        }

        if (request('status_account') == StoreStatusAccountEnum::FOUNDATION->value)
        {
            $rules['user_id_front_image'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['user_id_back_image'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['iban_card'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['commercial_log'] = [
                $this->store ? 'sometimes':'required',
                'mimes:pdf'
            ];
            $rules['manager_id'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
        }

        if (request('status_account') == StoreStatusAccountEnum::COMPANY->value)
        {
            $rules['user_id_front_image'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['user_id_back_image'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['iban_card'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['commercial_log'] = [
                $this->store ? 'sometimes':'required',
                'mimes:pdf'
            ];
            $rules['manager_id'] = [
                $this->store ? 'sometimes':'required',
                'mimes:jpg,png,jpeg'
            ];
            $rules['contract_establish'] = [
                $this->store ? 'sometimes':'required',
                'mimes:pdf'
            ];
            $rules['owner_id'] = [
                $this->store ? 'sometimes':'required',
                'mimes:pdf'
            ];
        }

        return $rules;
    }

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

        $attributes =
        [
            'name' => __('stores.name'),
            'phone' => __('stores.phone'),
            'email' => __('stores.email'),
            'category_id' => __('stores.category_id'),
            'sub_category_id' => __('stores.sub_category_id'),
            'min_order' => __('stores.min_order'),
            'logo' => __('stores.logo'),
            'header' => __('stores.header'),
            'bank_account' => __('stores.bank_account'),
            'bank_num' => __('stores.bank_num'),
            'iban' => __('stores.iban'),
            'bank' => __('stores.bank'),
            'status_account' => __('stores.status_account'),
            'license_work' => __('stores.license_work'),
            'manager_id' => __('stores.manager_id'),
            'user_id_front_image' => __('stores.user_id_front_image'),
            'user_id_back_image' => __('stores.user_id_back_image'),
            'iban_card' => __('stores.iban_card'),
            'commercial_log' => __('stores.commercial_log'),
            'contract_establish' => __('stores.contract_establish'),
            'owner_id'=>__('stores.owner_id')
        ];
        $days = StoreDayEnum::values();
        foreach ($days as $row)
        {
            $attributes['days.'.$row.'.start_time'] = __('stores.days.'.$row).' '.__('stores.start_time');
            $attributes['days.'.$row.'.end_time'] = __('stores.days.'.$row).' '.__('stores.end_time');
        }
        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);
        }
    }
}
