<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Cart;
use App\Models\Product; // Pastikan Model Product dipanggil

class CartController extends Controller
{
    public function index()
    {
        $carts = Cart::with('product')->where('user_id', Auth::id())->get();
        
        $total = $carts->sum(function($cart) {
            return $cart->product->price * $cart->qty;
        });

        return view('cart', compact('carts', 'total'));
    }

    // --- LOGIKA BARU ANTI STOK MINUS ---
    public function addToCart(Request $request, $productId)
    {
        $user = Auth::user();
        $product = Product::findOrFail($productId); // Ambil data produk

        // 1. Cek apakah Stok Habis Total (0)
        if ($product->stock <= 0) {
            return redirect()->back()->with('error', 'Maaf, stok produk ini sudah habis!');
        }

        $existingCart = Cart::where('user_id', $user->id)
                            ->where('product_id', $productId)
                            ->first();

        if ($existingCart) {
            // 2. Cek jika ditambah 1, apakah melebihi stok yang ada?
            if (($existingCart->qty + 1) > $product->stock) {
                return redirect()->back()->with('error', 'Stok tidak cukup! Sisa stok hanya: ' . $product->stock);
            }
            
            $existingCart->increment('qty');
        } else {
            // Kalau baru pertama kali masuk keranjang, pasti aman (karena stok > 0)
            Cart::create([
                'user_id' => $user->id,
                'product_id' => $productId,
                'qty' => 1
            ]);
        }

        return redirect()->back()->with('success', 'Produk berhasil masuk keranjang!');
    }
    // -----------------------------------

    public function destroy($id)
    {
        Cart::destroy($id);
        return redirect()->back()->with('success', 'Item dihapus dari keranjang.');
    }
}