<?php

namespace App\Http\Requests;

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;

/**
 * @property mixed product_id
 * @property mixed type
 */
class CouponRequest 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('coupons' ))
        {
            return true;
        }
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        $discountAmountRule = 'required|numeric|gt:0';
        $userIdRule = 'nullable';
        $marketerPercentageRules = 'nullable';

        if (request('discount_type') == 'percentage'){
            $discountAmountRule = 'required|numeric|between:1,100|gt:0';
        }
        if (request('marketer_coupons')){
            $userIdRule = [
                'required',
                'exists:users,id',
                Rule::unique('coupons')->ignore($this->marketerCoupon ? $this->marketerCoupon->id : 0, 'id')
            ];
            $marketerPercentageRules = 'required|numeric|between:1,100|gt:0';
        }
        $rules = [
            'user_id' => $userIdRule,
            'status' => 'required|in:1,0',
            'service_type' => 'required|in:all,consulting,documentation',
            'discount_type' => 'required|in:percentage,value',
            'discount_amount' => $discountAmountRule,
            'start_date' => 'required|date|after_or_equal:'.date('Y-m-d'),
            'end_date' => 'required|date|after_or_equal:start_date',
            'available_users' => 'required|numeric|gt:0',
            'code' => [
                'required',
                'max:50',
                Rule::unique('coupons')->ignore(($this->coupon ?? $this->marketerCoupon)? ($this->coupon->id ?? $this->marketerCoupon->id) : 0, 'id')
            ],
            'marketer_percentage' => $marketerPercentageRules,

        ];

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $field = metaFields('coupons');
        $local = getCurrentLocale();
        $attributes=[
            'user_id' => $field[$local]['user_id'] ?? __('coupons.user_id'),
            'discount_type' => $field[$local]['discount_type'] ?? __('coupons.discount_type'),
            'service_type' => $field[$local]['service_type'] ?? __('coupons.service_type'),
            'status' => $field[$local]['status'] ?? __('coupons.status'),
            'discount_amount' => $field[$local]['discount_amount'] ?? __('coupons.discount_amount'),
            'start_date' => $field[$local]['start_date'] ?? __('coupons.start_date'),
            'end_date' => $field[$local]['end_date'] ?? __('coupons.end_date'),
            'available_users' => $field[$local]['available_users'] ?? __('coupons.available_users'),
            'code' => $field[$local]['code'] ?? __('coupons.code'),
            'marketer_percentage' => $field[$local]['marketer_percentage'] ?? __('coupons.marketer_percentage'),
        ];

        if (request('discount_type') == 'percentage'){
            $attributes['discount_amount'] = __('coupons.discount_percentage');
        }

        return $attributes;
    }


    public function messages()
    {
        return [
            'discount_amount.between' => __('coupons.discount_amount_between'),
            'discount_amount.gt' => __('coupons.discount_amount_gt_zero'),
            'available_users.gt' => __('coupons.available_users_gt_zero'),
            'marketer_percentage.gt' => __('coupons.marketer_percentage_gt_zero'),
            'start_date.after_or_equal' => __('coupons.start_date_gt_today'),
            'end_date.after_or_equal' => __('coupons.end_date_gt_today'),
        ];
    }

    /**
     * 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::ajax()){
            if ($validator->fails()){
                $errors = $validator->errors();
                throw new HttpResponseException(response()->json(['errors' => $errors->first()]));
            }

        } else {
            // Do the original action of the Form request class
            parent::failedValidation($validator);
        }
    }
}
