<?php

namespace App\Http\Middleware;

use App\Services\InteractWithCart;
use App\Services\OrderService;
use Closure;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class CheckStock{

    use InteractWithCart;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next){

        $checkStock = (new OrderService)->productsIsAvailable();
        if (auth()->check() && Cart::instance('default')->count() > 0) {
            return $next($request);
        }
        return redirect()
            ->route('shop.index')->with([
                "message" => __("Your cart is empty. Please add products and continue."),
                "alert-type" => "danger",
            ]);
    }
}
