[Back]
<?php

namespace App\Http\Controllers;

use App\Models\{Cart, CartItem, Product};
use Illuminate\Http\Request;

class CartController extends Controller
{
    private function userCart(): Cart
    {
        return Cart::firstOrCreate(['user_id' => auth()->id()]);
    }

    public function index()
    {
        $cart = $this->userCart()->load('items.product');
        $subtotalCents = $cart->items->sum(fn($i) => $i->quantity * $i->unit_price_cents);

        return view('cart.index', compact('cart', 'subtotalCents'));
    }

    public function add(Request $request, Product $product)
    {
        $cart = $this->userCart();

        $qty = max(1, (int) $request->input('quantity', 1));

        $item = CartItem::firstOrNew([
            'cart_id' => $cart->id,
            'product_id' => $product->id,
        ]);

        $item->unit_price_cents = $product->price_cents;
        $item->quantity = ($item->exists ? $item->quantity : 0) + $qty;
        $item->save();

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

    public function update(Request $request, Product $product)
    {
        $cart = $this->userCart();

        $qty = max(1, (int) $request->input('quantity', 1));

        CartItem::where('cart_id', $cart->id)
            ->where('product_id', $product->id)
            ->update(['quantity' => $qty]);

        return back()->with('success', 'Cart updated.');
    }

    public function remove(Product $product)
    {
        $cart = $this->userCart();

        CartItem::where('cart_id', $cart->id)
            ->where('product_id', $product->id)
            ->delete();

        return back()->with('success', 'Item removed.');
    }
}