<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\CartItem;
use App\Models\Product;
use Illuminate\Http\Request;

class CartController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $cartItems = CartItem::with('product.supplier')
            ->where('user_id', auth()->id())
            ->get();

        $subtotal = $cartItems->sum(fn($item) => $item->quantity * $item->product->price);
        $tax = $subtotal * 0.15;
        $total = $subtotal + $tax;

        return view('cart.index', compact('cartItems', 'subtotal', 'tax', 'total'));
    }

    public function add(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'integer|min:1',
        ]);

        $product = Product::findOrFail($request->product_id);
        $quantity = $request->get('quantity', 1);

        // Check if already in cart
        $cartItem = CartItem::where('user_id', auth()->id())
            ->where('product_id', $product->id)
            ->first();

        if ($cartItem) {
            $cartItem->quantity += $quantity;
            $cartItem->save();
        } else {
            CartItem::create([
                'user_id' => auth()->id(),
                'product_id' => $product->id,
                'quantity' => $quantity,
            ]);
        }

        return back()->with('success', 'Product added to cart!');
    }

    public function update(Request $request, $id)
    {
        $cartItem = CartItem::where('user_id', auth()->id())
            ->findOrFail($id);

        if ($request->action === 'increase') {
            $cartItem->quantity++;
        } elseif ($request->action === 'decrease') {
            $cartItem->quantity--;
            if ($cartItem->quantity <= 0) {
                $cartItem->delete();
                return back()->with('success', 'Item removed from cart');
            }
        } elseif ($request->has('quantity')) {
            $cartItem->quantity = max(1, (int) $request->quantity);
        }

        $cartItem->save();

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

    public function remove($id)
    {
        CartItem::where('user_id', auth()->id())
            ->where('id', $id)
            ->delete();

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

    public function clear()
    {
        CartItem::where('user_id', auth()->id())->delete();

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