34968-vm/checkout.php
Flatlogic Bot ab1ae8b39b V2
2025-10-14 23:38:25 +00:00

101 lines
3.1 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
// If user is not logged in, redirect to login page
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
// If cart is empty, redirect to cart page
if (empty($_SESSION['cart'])) {
header('Location: cart.php');
exit;
}
$cart_items = [];
$total_price = 0;
$restaurant_id = $_SESSION['cart_restaurant'];
$menu_item_ids = array_keys($_SESSION['cart']);
$placeholders = implode(',', array_fill(0, count($menu_item_ids), '?'));
$stmt = db()->prepare("SELECT * FROM menu_items WHERE id IN ($placeholders)");
$stmt->execute($menu_item_ids);
$db_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($db_items as $item) {
$quantity = $_SESSION['cart'][$item['id']];
$item_total = $item['price'] * $quantity;
$total_price += $item_total;
$cart_items[] = [
'id' => $item['id'],
'name' => $item['name'],
'price' => $item['price'],
'quantity' => $quantity,
'total' => $item_total
];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user_id = $_SESSION['user_id'];
// Insert into orders table
$stmt = db()->prepare("INSERT INTO orders (user_id, restaurant_id, total_price, status) VALUES (?, ?, ?, ?)");
$stmt->execute([$user_id, $restaurant_id, $total_price, 'pending']);
$order_id = db()->lastInsertId();
// Insert into order_items table
$stmt = db()->prepare("INSERT INTO order_items (order_id, menu_item_id, quantity, price) VALUES (?, ?, ?, ?)");
foreach ($cart_items as $item) {
$stmt->execute([$order_id, $item['id'], $item['quantity'], $item['price']]);
}
// Clear the cart
$_SESSION['cart'] = [];
$_SESSION['cart_restaurant'] = null;
// Redirect to a confirmation page
header('Location: order_confirmation.php?id=' . $order_id);
exit;
}
include 'header.php';
?>
<main>
<div class="container">
<h1>Checkout</h1>
<div class="checkout-summary">
<h2>Order Summary</h2>
<table class="cart-table">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<?php foreach ($cart_items as $item): ?>
<tr>
<td><?= htmlspecialchars($item['name']) ?></td>
<td><?= $item['quantity'] ?></td>
<td>$<?= htmlspecialchars(number_format($item['total'], 2)) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="cart-total">
<h3>Total: $<?= htmlspecialchars(number_format($total_price, 2)) ?></h3>
</div>
<form action="checkout.php" method="POST" class="checkout-form">
<button type="submit" class="checkout-btn">Place Order</button>
</form>
</div>
</div>
</main>
<?php include 'footer.php'; ?>