<?php

namespace Modules\Deal\Requests\Employee;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Foundation\Http\FormRequest;
use Modules\Deal\Services\DealService;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Modules\Deal\Enums\DealPaymentStatusEnum;
use Modules\User\Enums\UserRoleEnum;
use Modules\Deal\Enums\DealStatusEnum;

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

    public function __construct(
        private DealService $dealService,
    ){}
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $deal = $this->dealService->checkItem($this->deal ?? 0 );
        if($deal)
        {
            if($deal->lock)
            {
                return [
                    'locked'=>'required'
                ];
            }
        }
        $rules = [];
        foreach (languages() as $lang)
        {
            $lang_rules=[
                'title_'.$lang->local=> 'required|max:50',
            ];
            $rules= array_merge($rules, $lang_rules);
        }


//            $rules['month'] =
//            [
//                'required',
//                'in:1,2,3,4,5,6,7,8,9,10,11,12',
//            ];
            $rules['end_date'] =
            [
                'required',
                'date',
                'after:start_date'
            ];
            $rules['start_date'] =
            [
                'required',
                'date'
            ];
            $rules['end_date'] =
            [
                'required',
                'date',
                'after:start_date'
            ];
            $rules['amount'] =
            [
                'required',
                'numeric',
                'min:0'
            ];

            $statuses = DealStatusEnum::values();
            $rules['status'] =
            [
                'required',
                'in:'.implode(',',$statuses)
            ];

            $statuses = DealPaymentStatusEnum::values();
            $rules['payment_status'] =
            [
                'required',
                'in:'.implode(',',$statuses)
            ];
            if(request('payment_status') == DealPaymentStatusEnum::MULTIPLE->value)
            {
                $rules['payments'] =
                [
                    'required',
                    'array',
                    'min:1',
                ];
                $rules['payments.*'] =
                [
                    'required',
                    'numeric',
                    'gte:0',
                ];
            }
            $rules['sector_id'] =
            [
                'required',
                Rule::exists('sectors','id')->whereNull('deleted_at')
            ];
            $rules['employee_id'] =
            [
                'required',
                Rule::exists('users','id')->whereNull('deleted_at')
            ];
            $rules['product_id'] =
            [
                'required',
                Rule::exists('products','id')->whereNull('deleted_at')
            ];
            // $rules['deal_id'] =
            // [
            //     'required',
            //     Rule::exists('deals','id')->whereNull('deal_id')->whereNull('deleted_at')
            // ];
            $rules['company_id'] =
            [
                'nullable',
                Rule::exists('companies','id')->whereNull('deleted_at')
            ];
            $rules['contact_list_id'] =
            [
                'nullable',
                Rule::exists('contact_lists','id')->whereNull('deleted_at')
            ];
            foreach (languages() as $lang)
            {
                $lang_rules=[
                    'description_'.$lang->local=> 'nullable',
                ];
                $rules= array_merge($rules, $lang_rules);
            }
            $rules['file'] =
                [
                    'nullable' ,
                    'file',
                    'mimes:pdf,docx,pptx'
                ];
            $rules['file_url'] =
                [
                    'nullable',
                    'url'
                ];


        if(!request('file') && !request('file_url'))
        {
            if($this->deal)
            {
                $deal = $this->dealService->checkItem($this->deal);
                if(is_null($deal->file))
                {
                    $rules['file_or_url'] =
                    [
                        'required'
                    ];
                }
            }
            else
            {
                $rules['file_or_url'] =
                [
                    'required'
                ];
            }
        }
        if(request('payment_status') == DealPaymentStatusEnum::MULTIPLE->value)
        {
            $total = 0;
            if(!is_null(request('payments')))
            {
                foreach(request('payments') as $payment)
                {
                    $total += $payment;
                }
            }
            if($total > request('amount'))
            {
                return [
                    'over_budget'=>'required'
                ];
            }
        }
        return $rules;
    }

    public function messages()
    {
        return
        [
            'locked.required'=>__('dashboard.locked'),
            'file_or_url.required'=>__('deals.file_or_url'),
            'over_budget.required'=>__('deals.over_budget')
        ];
    }

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

        $attributes= [
            'month'=>__('deals.month'),
            'sector_id'=>__('deals.sector_id'),
            'start_date'=>__('deals.start_date'),
            'end_date'=>__('deals.end_date'),
            'file'=>__('deals.file'),
            'deal_status_id'=>__('deals.deal_status_id'),
            'employee_id'=>__('deals.employee_id'),
            'deal_id'=>__('deals.deal_id'),
            'company_id'=>__('deals.company_id'),
            'contact_list_id'=>__('deals.contact_list_id'),
            'status'=>__('deals.status'),
            'payment_status'=>__('deals.payment_status'),
            'payments'=>__('deals.payments'),
        ];
        foreach (languages() as $lang) {
            $lang_attributes=[
                'title_'.$lang->local => __('deals.title').' '.$lang->local,
                'description_'.$lang->local => __('deals.description').' '.$lang->local,
            ];
            $attributes= array_merge($attributes, $lang_attributes);
        }
        if(request('payment_status') == DealPaymentStatusEnum::MULTIPLE->value)
        {
            $i = 1;
            if( !is_null( request('payments') ) )
            {
                foreach(request('payments') as $key => $row)
                {
                    $attributes['payments.'.$key] = $key == 0 ? __('deals.deposite') : __('deals.amount_card') . ($i);
                    ++$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);
        }
    }
}
