79 lines
2.7 KiB
PHP
79 lines
2.7 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
require_once 'vendor/autoload.php';
|
|
require_once 'includes/api_keys.php';
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header("Location: login.php");
|
|
exit();
|
|
}
|
|
|
|
if (!isset($_GET['session_id'])) {
|
|
header("Location: index.php");
|
|
exit();
|
|
}
|
|
|
|
$stripe_session_id = $_GET['session_id'];
|
|
$user_id = $_SESSION['user_id'];
|
|
$pdo = db();
|
|
|
|
\Stripe\Stripe::setApiKey($stripeSecretKey);
|
|
|
|
try {
|
|
$checkout_session = \Stripe\Checkout\Session::retrieve($stripe_session_id);
|
|
|
|
if ($checkout_session->payment_status == 'paid') {
|
|
// Fetch cart items and delivery details
|
|
$stmt = $pdo->prepare("SELECT c.*, mi.price, mi.restaurant_id FROM cart c JOIN menu_items mi ON c.menu_item_id = mi.id WHERE c.user_id = ?");
|
|
$stmt->execute([$user_id]);
|
|
$cart_items = $stmt->fetchAll();
|
|
|
|
if (empty($cart_items)) {
|
|
header("Location: index.php");
|
|
exit();
|
|
}
|
|
|
|
$total_price = 0;
|
|
$restaurant_id = null;
|
|
foreach ($cart_items as $item) {
|
|
$total_price += $item['price'] * $item['quantity'];
|
|
$restaurant_id = $item['restaurant_id']; // Assuming all items in cart are from the same restaurant
|
|
}
|
|
$delivery_fee = 5.00;
|
|
$total_price += $delivery_fee;
|
|
|
|
// Get delivery details stored in cart
|
|
$delivery_name = $cart_items[0]['delivery_name'];
|
|
$delivery_address = $cart_items[0]['delivery_address'];
|
|
$delivery_phone = $cart_items[0]['delivery_phone'];
|
|
|
|
// Create order
|
|
$stmt = $pdo->prepare("INSERT INTO orders (user_id, restaurant_id, total_price, status, stripe_session_id, delivery_name, delivery_address, delivery_phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
|
|
$stmt->execute([$user_id, $restaurant_id, $total_price, 'paid', $stripe_session_id, $delivery_name, $delivery_address, $delivery_phone]);
|
|
$order_id = $pdo->lastInsertId();
|
|
|
|
// Insert order items
|
|
$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['menu_item_id'], $item['quantity'], $item['price']]);
|
|
}
|
|
|
|
// Clear cart
|
|
$stmt = $pdo->prepare("DELETE FROM cart WHERE user_id = ?");
|
|
$stmt->execute([$user_id]);
|
|
|
|
$_SESSION['order_id'] = $order_id;
|
|
header("Location: order_confirmation.php");
|
|
exit();
|
|
|
|
} else {
|
|
header("Location: payment-cancel.php");
|
|
exit();
|
|
}
|
|
} catch (\Stripe\Exception\ApiErrorException $e) {
|
|
// Handle Stripe API errors
|
|
error_log($e->getMessage());
|
|
header("Location: payment-cancel.php");
|
|
exit();
|
|
} |