<?php

namespace App\Http\Requests\Web;

use App\Models\Cart;
use App\Services\Repositories\CartRepository;
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 video_type
 * @property mixed video_url
 * @property mixed images
 */
class OrderRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules =
            [
                'status' => 'required|in:room,table,pickup',
                'time' => 'sometimes|nullable|required_if:status,pickup',
                'table_id' => 'sometimes|nullable|required_if:status,table|exists:table_numbers,id',
                'room_id' => 'sometimes|nullable|required_if:status,room|exists:rooms,id',
            ];
        $carts = Cart::where('user_id',Auth::user()->id)->count();
        if ($carts == 0)
        {
            return ['min_1' => 'required'];
        }

        return $rules;
    }

    public function messages()
    {
        return [
            'min_1.required'=>__('web.min_1')
        ];
    }
    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $attributes=
            [
                'status' => __('orders.status'),
                'time' => __('orders.time'),
                'table_id' => __('orders.table_id'),
                'room_id' => __('orders.room_id'),
            ];

        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 {
            parent::failedValidation($validator);
        }
    }
}
