56 lines
2.0 KiB
PHP
56 lines
2.0 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header("Location: login.php");
|
|
exit();
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$userId = $_SESSION['user_id'];
|
|
$pdoconnection = db();
|
|
|
|
// Create a new order
|
|
$stmt = $pdoconnection->prepare("INSERT INTO orders (user_id, restaurant_id, total_price, status) VALUES (:user_id, :restaurant_id, :total_price, 'pending')");
|
|
$stmt->bindParam(':user_id', $userId);
|
|
$stmt->bindParam(':restaurant_id', $_POST['restaurant_id']);
|
|
$stmt->bindParam(':total_price', $_POST['total_price']);
|
|
$stmt->execute();
|
|
$orderId = $pdoconnection->lastInsertId();
|
|
|
|
// Get cart items
|
|
$stmt = $pdoconnection->prepare("SELECT * FROM cart WHERE user_id = :user_id");
|
|
$stmt->bindParam(':user_id', $userId);
|
|
$stmt->execute();
|
|
$cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
|
|
// Move cart items to order_items
|
|
$stmt = $pdoconnection->prepare("INSERT INTO order_items (order_id, menu_item_id, quantity, price) VALUES (:order_id, :menu_item_id, :quantity, :price)");
|
|
foreach ($cartItems as $item) {
|
|
// Get menu item price
|
|
$priceStmt = $pdoconnection->prepare("SELECT price FROM menu_items WHERE id = :menu_item_id");
|
|
$priceStmt->bindParam(':menu_item_id', $item['menu_item_id']);
|
|
$priceStmt->execute();
|
|
$menuItem = $priceStmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
$stmt->bindParam(':order_id', $orderId);
|
|
$stmt->bindParam(':menu_item_id', $item['menu_item_id']);
|
|
$stmt->bindParam(':quantity', $item['quantity']);
|
|
$stmt->bindParam(':price', $menuItem['price']);
|
|
$stmt->execute();
|
|
}
|
|
|
|
// Clear the cart
|
|
$stmt = $pdoconnection->prepare("DELETE FROM cart WHERE user_id = :user_id");
|
|
$stmt->bindParam(':user_id', $userId);
|
|
$stmt->execute();
|
|
|
|
// Redirect to order confirmation
|
|
header("Location: order_confirmation.php?id=" . $orderId);
|
|
exit();
|
|
} else {
|
|
header("Location: checkout.php");
|
|
exit();
|
|
}
|
|
?>
|