36766-vm/cart.php
Flatlogic Bot 6c14b2436f 2.0
2025-12-18 09:40:37 +00:00

180 lines
6.5 KiB
PHP

<?php
require_once 'includes/header.php';
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
// Initialize cart if it doesn't exist
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
$pdo = db();
$action = $_GET['action'] ?? '';
switch ($action) {
case 'add':
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['product_id'])) {
$product_id = $_POST['product_id'];
$quantity = (int)($_POST['quantity'] ?? 1);
if ($quantity > 0) {
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id] += $quantity;
} else {
$_SESSION['cart'][$product_id] = $quantity;
}
}
}
header('Location: products.php');
exit;
case 'update':
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['quantities'])) {
foreach ($_POST['quantities'] as $product_id => $quantity) {
$quantity = (int)$quantity;
if ($quantity > 0) {
$_SESSION['cart'][$product_id] = $quantity;
} else {
unset($_SESSION['cart'][$product_id]);
}
}
}
header('Location: cart.php');
exit;
case 'place_order':
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_SESSION['cart'])) {
$total_amount = 0;
$cart_products = [];
$product_ids = array_keys($_SESSION['cart']);
if (empty($product_ids)) {
header('Location: cart.php');
exit;
}
$sql = "SELECT * FROM products WHERE id IN (" . implode(',', array_fill(0, count($product_ids), '?')) . ")";
$stmt = $pdo->prepare($sql);
$stmt->execute($product_ids);
$products_array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$products = [];
foreach ($products_array as $product) {
$products[$product['id']] = $product;
}
// Debug: Dump products array
// var_dump($products);
foreach ($_SESSION['cart'] as $product_id => $quantity) {
if (isset($products[$product_id])) {
$product = $products[$product_id];
$price = $product['price'] ?? 0;
$total_amount += $price * $quantity;
$cart_products[] = ['product' => $product, 'quantity' => $quantity];
}
}
// Debug: Dump total amount
// var_dump($total_amount);
if ($total_amount > 0) {
$pdo->beginTransaction();
try {
$sql = 'INSERT INTO orders (user_id, total_amount, status) VALUES (?, ?, ?)';
$stmt = $pdo->prepare($sql);
$stmt->execute([$_SESSION['user_id'], $total_amount, 'Pending']);
$order_id = $pdo->lastInsertId();
$sql = 'INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)';
$stmt = $pdo->prepare($sql);
foreach ($cart_products as $item) {
// Use the price from the database, not the one from the session/cart loop
$product_price = $products[$item['product']['id']]['price'] ?? 0;
$stmt->execute([$order_id, $item['product']['id'], $item['quantity'], $product_price]);
}
$pdo->commit();
$_SESSION['cart'] = [];
header('Location: order_details.php?id=' . $order_id);
exit;
} catch (Exception $e) {
$pdo->rollBack();
// Debug: Log exception
error_log($e->getMessage());
header('Location: cart.php?error=place_order_failed');
exit;
}
} else {
header('Location: cart.php?error=zero_total');
exit;
}
}
header('Location: cart.php');
exit;
}
// Display Cart
$cart_items = [];
$total_price = 0;
if (!empty($_SESSION['cart'])) {
$product_ids = array_keys($_SESSION['cart']);
$sql = "SELECT * FROM products WHERE id IN (" . implode(',', array_fill(0, count($product_ids), '?')) . ")";
$stmt = $pdo->prepare($sql);
$stmt->execute($product_ids);
$products = $stmt->fetchAll();
foreach ($products as $product) {
$product_id = $product['id'];
$quantity = $_SESSION['cart'][$product_id];
$price = $product['price'] ?? 0;
$cart_items[] = ['product' => $product, 'quantity' => $quantity, 'price' => $price];
$total_price += $price * $quantity;
}
}
?>
<h1 class="mb-4">Shopping Cart</h1>
<?php if (empty($cart_items)) : ?>
<div class="alert alert-info">Your cart is empty.</div>
<?php else : ?>
<form action="cart.php?action=update" method="post">
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php foreach ($cart_items as $item) : ?>
<tr>
<td><?php echo htmlspecialchars($item['product']['name']); ?></td>
<td>$<?php echo number_format($item['price'], 2); ?></td>
<td>
<input type="number" name="quantities[<?php echo $item['product']['id']; ?>]" value="<?php echo $item['quantity']; ?>" min="1" class="form-control" style="width: 80px;">
</td>
<td>$<?php echo number_format($item['price'] * $item['quantity'], 2); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="d-flex justify-content-between align-items-center mb-3">
<button type="submit" class="btn btn-secondary">Update Cart</button>
<h4>Total: $<?php echo number_format($total_price, 2); ?></h4>
</div>
</form>
<form action="cart.php?action=place_order" method="post" class="text-end">
<button type="submit" class="btn btn-primary">Place Order</button>
</form>
<?php endif; ?>
<?php require_once 'includes/footer.php'; ?>