<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class CartController extends Controller
{

    public function add(Request $request, Product $product)
    {
        $cart = session()->get('cart', []);
        if (isset($cart[$product->id])) {
            $cart[$product->id]['quantity']++;
        } else {
            $cart[$product->id] = [
                'name' => $product->name,
                'quantity' => 1,
                'price' => $product->price,
                'image' => $product->image
            ];
        }
        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'product added to cart');
    }

    public function index()
    {
        return view('cart.index');
    }
    public function update(Request $request)
    {
        $request->validate([
            'id' =>'required',
            'quantity' =>'required',    
        ]);
        $cart=session()->get('cart',[]);
        if ($request->id && $request->quantity && isset($cart[$request->id])) {
            $cart[$request->id]['quantity']=$request->quantity;
            session()->put('cart', $cart);
            return redirect()->back()->with('success','cart Updated');
        }
        return redirect()->back()->with('error', 'unble to updte cart');
    }
    public function remove($id){
        $cart=session()->get('cart');
        if(isset($cart[$id])){
            unset($cart[$id]);
            session()->put('cart',$cart);
        }
        return redirect()->back()->with('success','Item removed');
    }
}
