<?php

namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Wishlist;
use App\Models\Cart;
use App\Models\NFT;
use App\Models\Order;
use Illuminate\Support\Str;
use Helper;
use Inertia\Inertia;


class CartController extends Controller
{
    protected $product=null;
    public function __construct(Product $product){
        $this->product=$product;
    }

    public function addToCart(Request $request){
        
        $request->validate([
            'slug'      =>  'required',
            'color'      =>  'required',
            'size'      =>  'required',
            'selected' => 'required',
        ]);

        $product = Product::where('slug', $request->slug)->first();

        if($product->stock < 1){
            return back()->with('error','Out of stock, You can add other products.');
        }
        if ( (1 < 1) || empty($product) ) {
            request()->session()->flash('error','Invalid Products');
            return back();
        }    
        $already_cart = Cart::where('user_id', auth()->user()->id)->where('order_id',null)->where('product_id', $product->id)->first();
        
        if($already_cart) {
            return back()->with('error','Product already in the cart!.');
        }else{
            $cart = new Cart;
            $cart->user_id = auth()->user()->id;
            $cart->product_id = $product->id;
            $cart->color = $request->color;
            $cart->size = $request->size;
            $cart->quantity = 1;
            if ($cart->product->stock < $cart->quantity || $cart->product->stock <= 0) return back()->with('error','Stock not sufficient!.');
            $cart->save();
        }
        request()->session()->flash('success','Product successfully added to cart.');
        return back();       
    } 
    
    public function cartDelete(Request $request){
        $cart = Cart::find($request->id);
        if ($cart) {
            $cart->delete();
            return back()->with('success', 'Cart successfully removed');  
        }
        return back()->with('error', 'Error please try again');   
    }     

    public function cartClear(Request $request){
        $data = $request->all();
        $user = Auth::id();
        $clearCart = $user && Cart::where('user_id', $user)->delete();
        if($clearCart){
            return back()->with('warning', 'Cart Items Cleared');  
        }
    }

    public function checkout(Request $request){
        return Inertia::render('Checkout',[
           'cart' => Helper::cartItems()
        ]);
    }
}
