prepare("SELECT * FROM products WHERE id IN ($placeholders)"); $stmt->execute($product_ids); $products = $stmt->fetchAll(); foreach ($products as $product) { $product_id = $product['id']; $quantity = $_SESSION['cart'][$product_id]; $subtotal = $product['price'] * $quantity; $total += $subtotal; $cart_items[] = [ 'id' => $product_id, 'name' => $product['name'], 'price' => $product['price'], 'quantity' => $quantity, 'subtotal' => $subtotal ]; } } if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_cart'])) { foreach ($_POST['quantities'] as $product_id => $quantity) { if ($quantity > 0) { $_SESSION['cart'][$product_id] = (int)$quantity; } else { unset($_SESSION['cart'][$product_id]); } } header("Location: cart.php"); exit; } if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['checkout'])) { if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; } if (empty($cart_items)) { header("Location: shop.php"); exit; } $pdo = db(); try { $pdo->beginTransaction(); // Check if user has enough balance $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?"); $stmt->execute([$_SESSION['user_id']]); $user = $stmt->fetch(); if ($user['balance'] < $total) { // Not enough balance $pdo->rollBack(); // Redirect to cart with an error message header("Location: cart.php?error=balance"); exit; } // Create order $stmt = $pdo->prepare("INSERT INTO orders (user_id, total) VALUES (?, ?)"); $stmt->execute([$_SESSION['user_id'], $total]); $order_id = $pdo->lastInsertId(); // Create order items $stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)"); foreach ($cart_items as $item) { $stmt->execute([$order_id, $item['id'], $item['quantity'], $item['price']]); } // Deduct balance from user $new_balance = $user['balance'] - $total; $stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?"); $stmt->execute([$new_balance, $_SESSION['user_id']]); $pdo->commit(); // Clear cart unset($_SESSION['cart']); // Redirect to a success page header("Location: order_success.php?order_id=" . $order_id); exit; } catch (Exception $e) { $pdo->rollBack(); // Log the error error_log($e->getMessage()); // Redirect to cart with a generic error header("Location: cart.php?error=checkout"); exit; } } ?> Shopping Cart You do not have enough balance to complete this purchase. An error occurred during checkout. Please try again. Your cart is empty. Continue Shopping Product Price Quantity Subtotal $ $ Update Cart Total: $ Checkout
Your cart is empty.
Total: $