<?php

namespace App\Http\Controllers;

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

class CartController extends Controller
{
    public function index()
    {
        $cart = session('cart', []);
        $total = collect($cart)->sum(fn($item) => $item['price'] * $item['quantity']);
        return view('cart.index', compact('cart', 'total'));
    }

    public function add(Request $request, string $slug)
    {
        $package = Package::where('slug', $slug)->where('is_active', true)->where('is_custom', false)->firstOrFail();

        $cart = session('cart', []);

        if (isset($cart[$slug])) {
            $cart[$slug]['quantity']++;
        } else {
            $cart[$slug] = [
                'id'       => $package->id,
                'slug'     => $package->slug,
                'name'     => $package->name,
                'price'    => (float) $package->price,
                'quantity' => 1,
            ];
        }

        session(['cart' => $cart]);

        return redirect()->route('cart.index')->with('success', $package->name . ' added to cart!');
    }

    public function remove(string $slug)
    {
        $cart = session('cart', []);
        unset($cart[$slug]);
        session(['cart' => $cart]);

        return redirect()->route('cart.index')->with('success', 'Item removed from cart.');
    }

    public function clear()
    {
        session()->forget('cart');
        return redirect()->route('cart.index')->with('success', 'Cart cleared.');
    }
}
