<?php

namespace App\Http\Controllers;

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

class CartController extends Controller
{
    public function index(Request $request)
    {
        $cart = collect($request->session()->get('cart', []));
        $items = $cart->map(function ($quantity, $id) {
            return [
                'product' => Product::find($id),
                'quantity' => $quantity,
            ];
        })->filter(fn($item) => $item['product'] !== null);

        return view('cart.index', ['items' => $items]);
    }

    public function add(Request $request, $id)
    {
        $product = Product::findOrFail($id);

        $cart = $request->session()->get('cart', []);
        $cart[$product->id] = ($cart[$product->id] ?? 0) + 1;
        $request->session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Added to cart.');
    }

    public function remove(Request $request, $id)
    {
        $cart = $request->session()->get('cart', []);
        unset($cart[$id]);
        $request->session()->put('cart', $cart);

        return redirect()->route('cart.index');
    }
}
