namespace App\Http\Controllers; use App\Models\CartItem; use App\Models\Order; use App\Models\OrderItem; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\DB; class CheckoutController extends Controller { public function index() { $cartItems = CartItem::with(['product', 'inventoryItem'])->where('user_id', Auth::id())->get(); $subtotal = $cartItems->sum(function ($item) { return $item->quantity * $item->price_at_add; }); $user = Auth::user(); $shippingAddress = $user->profile->shipping_address ?? ''; $billingAddress = $user->profile->billing_address ?? ''; return view('checkout.index', compact('cartItems', 'subtotal', 'shippingAddress', 'billingAddress')); } public function store(Request $request) { $request->validate([ 'shipping_address' => 'required|string|max:255', 'billing_address' => 'required|string|max:255', ]); $cartItems = CartItem::with('inventoryItem')->where('user_id', Auth::id())->get(); if ($cartItems->isEmpty()) { return redirect()->route('cart.index')->with('error', 'Your cart is empty.'); } DB::transaction(function () use ($request, $cartItems) { $subtotal = 0; foreach ($cartItems as $item) { $inventory = $item->inventoryItem; if (!$inventory || $inventory->available_quantity < $item->quantity) { throw new \Exception('Insufficient stock for ' . $item->product->name); } $subtotal += $item->quantity * $inventory->current_price; } $taxRate = config('app.sales_tax_rate', 0.07); $taxAmount = $subtotal * $taxRate; $totalAmount = $subtotal + $taxAmount; $order = Order::create([ 'user_id' => Auth::id(), 'order_number' => uniqid('ORD-'), 'status' => 'pending_payment', 'sub_total' => $subtotal, 'tax_amount' => $taxAmount, 'total_amount' => $totalAmount, 'shipping_address' => $request->shipping_address, 'billing_address' => $request->billing_address, 'placed_at' => now(), ]); foreach ($cartItems as $item) { $inventory = $item->inventoryItem; OrderItem::create([ 'order_id' => $order->id, 'inventory_item_id' => $inventory->id, 'seller_user_id' => $inventory->product->seller_id, 'product_name' => $inventory->product->name, 'quantity' => $item->quantity, 'price' => $inventory->current_price, 'use_by_date' => $inventory->use_by_date, ]); $inventory->decrement('available_quantity', $item->quantity); } CartItem::where('user_id', Auth::id())->delete(); }); return redirect()->route('orders.thank_you', ['order_number' => $order->order_number])->with('success', 'Order placed successfully.'); } }