<?php


namespace Modules\Order\Requests\Api;



use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class OrderRequest extends FormRequest
{
    public function authorize()
    {
        return auth()->check() && auth()->user()->role == 6;
    }

    public function rules()
    {
        return [
            'child_id' => 'required|exists:users,id',
            // 'canteen_id' => 'required|exists:canteens,id',
            'products' => 'required|array|min:1',
            'products.*.product_id' => 'required|exists:products,id',
            'products.*.count' => 'required|integer|min:1',
        ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes(): array
    {
        return [
            'child_id' => __('orders.child_id'),
            // 'canteen_id' => __('orders.canteen_id'),
            'products' => __('orders.products'),
            'products.*.product_id' => __('orders.product_id'),
            'products.*.count' => __('orders.count')
        ];
    }

    /**
     * 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)
    {
        $errors = (new ValidationException($validator))->errors();
        $message = $validator->errors()->first();
        throw new HttpResponseException(response()->json(['message' => $message, 'errors' => $errors], 400));
    }
}
