-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_order.php
More file actions
84 lines (67 loc) · 2.24 KB
/
Copy pathprocess_order.php
File metadata and controls
84 lines (67 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/cart.php';
verify_csrf_or_fail();
$cart_items = get_cart_items();
$cart_total = get_cart_total();
if (empty($cart_items)) {
set_flash('error', 'Your cart is empty.');
redirect('/cart.php');
}
$customer_name = trim((string) ($_POST['customer_name'] ?? ''));
$customer_email = trim((string) ($_POST['customer_email'] ?? ''));
$customer_phone = trim((string) ($_POST['customer_phone'] ?? ''));
$customer_address = trim((string) ($_POST['customer_address'] ?? ''));
// Validation
if (empty($customer_name) || empty($customer_email) || empty($customer_address)) {
set_flash('error', 'Please fill in all required fields.');
redirect('/checkout.php');
}
if (!filter_var($customer_email, FILTER_VALIDATE_EMAIL)) {
set_flash('error', 'Please enter a valid email address.');
redirect('/checkout.php');
}
try {
$pdo = get_pdo();
$pdo->beginTransaction();
require_once __DIR__ . '/includes/auth.php';
$user_id = is_logged_in() ? current_user()['id'] : null;
// Create order
$stmt = $pdo->prepare('
INSERT INTO orders (user_id, customer_name, customer_email, customer_phone, customer_address, total_amount, status)
VALUES (?, ?, ?, ?, ?, ?, ?)
');
$stmt->execute([
$user_id,
$customer_name,
$customer_email,
$customer_phone ?: null,
$customer_address,
$cart_total,
'pending'
]);
$order_id = (int) $pdo->lastInsertId();
// Add order items
$stmt = $pdo->prepare('
INSERT INTO order_items (order_id, car_id, price_at_purchase)
VALUES (?, ?, ?)
');
foreach ($cart_items as $item) {
$stmt->execute([
$order_id,
$item['id'],
$item['price']
]);
}
$pdo->commit();
// Clear cart
clear_cart();
set_flash('success', 'Order placed successfully! Order ID: ' . $order_id);
redirect('/order_confirmation.php?order_id=' . $order_id);
} catch (Exception $e) {
$pdo->rollBack();
set_flash('error', 'An error occurred while placing your order. Please try again.');
redirect('/checkout.php');
}