prepare("SELECT id, price FROM menu_items WHERE id IN ($placeholders)"); $stmt->execute($item_ids); $db_items = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); foreach ($cart['items'] as &$item) { if (!isset($db_items[$item['id']])) { die("Invalid item in cart."); // Or handle more gracefully } $item['price'] = $db_items[$item['id']]; // Use price from DB for security $total_price += $item['price'] * $item['quantity']; } unset($item); // --- Database Transaction --- try { $pdo->beginTransaction(); $user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null; // 1. Insert into orders table $stmt = $pdo->prepare( 'INSERT INTO orders (user_id, restaurant_id, customer_name, customer_email, customer_phone, delivery_address, total_price) VALUES (?, ?, ?, ?, ?, ?, ?)' ); $stmt->execute([ $user_id, $cart['restaurantId'], $customer_name, $customer_email, $customer_phone, $delivery_address, $total_price ]); $order_id = $pdo->lastInsertId(); // 2. Insert into order_items table $stmt = $pdo->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'] ]); } $pdo->commit(); $_SESSION['last_order_id'] = $order_id; // --- Send Emails --- // To Customer $customer_subject = "Your MajuroEats Order #{$order_id} is Confirmed"; $customer_html = "
Your order with ID #{$order_id} has been placed.
We will notify you once the restaurant confirms it.
"; MailService::sendMail($customer_email, $customer_subject, $customer_html, strip_tags($customer_html)); // To Restaurant $stmt_restaurant = $pdo->prepare('SELECT u.email FROM users u JOIN restaurants r ON u.id = r.user_id WHERE r.id = ?'); $stmt_restaurant->execute([$cart['restaurantId']]); $restaurant_email = $stmt_restaurant->fetchColumn(); if ($restaurant_email) { $restaurant_subject = "New Order Received (#{$order_id})"; $restaurant_html = "Order ID: #{$order_id}
Please log in to your dashboard to view the details and confirm the order.
"; MailService::sendMail($restaurant_email, $restaurant_subject, $restaurant_html, strip_tags($restaurant_html)); } header('Location: order_confirmation.php'); exit; } catch (Exception $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } // In a real app, log this error $_SESSION['error_message'] = 'There was a problem placing your order. Please try again.'; header('Location: checkout.php'); exit; }