-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.php
More file actions
420 lines (371 loc) · 22 KB
/
Copy pathcheckout.php
File metadata and controls
420 lines (371 loc) · 22 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<?php
/**
* Checkout Page
*/
require_once __DIR__ . '/includes/helpers.php';
// Route Guard
auth_guard(['customer', 'vendor', 'admin']);
$userId = $_SESSION['user_id'];
$sessionId = session_id();
// Fetch Cart items
try {
$stmt = db()->prepare("
SELECT c.*, p.name as p_name, p.price as p_price, p.discount_price as p_disc_price,
p.tax as p_tax, p.shipping_cost as p_ship, p.vendor_id,
v.price_modifier, v.color, v.size, v.ram, v.storage
FROM `cart` c
JOIN `products` p ON c.product_id = p.id
LEFT JOIN `product_variants` v ON c.variant_id = v.id
WHERE c.user_id = ? OR c.session_id = ?
");
$stmt->execute([$userId, $sessionId]);
$cartItems = $stmt->fetchAll();
} catch (Exception $e) {
$cartItems = [];
}
if (empty($cartItems)) {
set_flash_message('warning', 'Your cart is empty. Add products before checkout.');
redirect('index.php');
}
// Calculate totals
$subtotal = 0.00;
$totalTax = 0.00;
$totalShipping = 0.00;
foreach ($cartItems as $item) {
$unitPrice = $item['p_disc_price'] !== null ? $item['p_disc_price'] : $item['p_price'];
if ($item['variant_id']) {
$unitPrice += $item['price_modifier'];
}
$itemTotal = $unitPrice * $item['quantity'];
$subtotal += $itemTotal;
$totalTax += ($itemTotal * $item['p_tax']) / 100;
$totalShipping += $item['p_ship'];
}
// Discount
$discount = 0.00;
$couponCode = null;
if (isset($_SESSION['coupon'])) {
$couponCode = $_SESSION['coupon']['code'];
$discount = $_SESSION['coupon']['discount'];
}
$grandTotal = ($subtotal + $totalTax + $totalShipping) - $discount;
if ($grandTotal < 0) $grandTotal = 0;
// Fetch User Addresses
$addrStmt = db()->prepare("SELECT * FROM `addresses` WHERE `user_id` = ? ORDER BY `is_default` DESC");
$addrStmt->execute([$userId]);
$addresses = $addrStmt->fetchAll();
// Handle Order Placement POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$addressId = (int)($_POST['address_id'] ?? 0);
$paymentMethod = clean($_POST['payment_method'] ?? 'COD');
// Inline new address values if selected
$fullName = clean($_POST['full_name'] ?? '');
$phone = clean($_POST['phone'] ?? '');
$addressLine1 = clean($_POST['address_line_1'] ?? '');
$city = clean($_POST['city'] ?? '');
$state = clean($_POST['state'] ?? '');
$postalCode = clean($_POST['postal_code'] ?? '');
$shippingAddressText = "";
try {
db()->beginTransaction();
// 1. Resolve Shipping Address
if ($addressId > 0) {
$selAddrStmt = db()->prepare("SELECT * FROM `addresses` WHERE `id` = ? AND `user_id` = ? LIMIT 1");
$selAddrStmt->execute([$addressId, $userId]);
$selAddr = $selAddrStmt->fetch();
if ($selAddr) {
$shippingAddressText = "{$selAddr['full_name']}, Phone: {$selAddr['phone']}, {$selAddr['address_line_1']}, {$selAddr['city']}, {$selAddr['state']}, {$selAddr['postal_code']}, {$selAddr['country']}";
}
} else {
// Validate inline address
if (empty($fullName) || empty($phone) || empty($addressLine1) || empty($city) || empty('postal_code')) {
throw new Exception("Please select a saved address or fill in all billing fields.");
}
// Save address to database
$insAddr = db()->prepare("INSERT INTO `addresses` (`user_id`, `label`, `full_name`, `phone`, `address_line_1`, `city`, `state`, `postal_code`, `country`, `is_default`) VALUES (?, 'Billing', ?, ?, ?, ?, ?, ?, 'Bangladesh', 0)");
$insAddr->execute([$userId, $fullName, $phone, $addressLine1, $city, $state, $postalCode]);
$shippingAddressText = "{$fullName}, Phone: {$phone}, {$addressLine1}, {$city}, {$state}, {$postalCode}, Bangladesh";
}
// 2. Generate Invoice and Order numbers
$orderNumber = "ORD-" . date('Ymd') . "-" . rand(1000, 9999);
$invoiceNo = "INV-" . date('Y') . "-" . rand(10000, 99999);
// 3. Insert Main Order record
$insOrder = db()->prepare("
INSERT INTO `orders` (`order_number`, `user_id`, `subtotal`, `discount`, `tax`, `shipping_cost`, `grand_total`, `payment_method`, `payment_status`, `shipping_status`, `shipping_address`, `invoice_no`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'pending', ?, ?)
");
$insOrder->execute([$orderNumber, $userId, $subtotal, $discount, $totalTax, $totalShipping, $grandTotal, $paymentMethod, $shippingAddressText, $invoiceNo]);
$orderId = db()->lastInsertId();
// 4. Save items, calculate commissions, and update vendor wallets
foreach ($cartItems as $item) {
$unitPrice = $item['p_disc_price'] !== null ? $item['p_disc_price'] : $item['p_price'];
if ($item['variant_id']) {
$unitPrice += $item['price_modifier'];
}
$rowTotal = $unitPrice * $item['quantity'];
// Fetch Vendor commission rate
$vProfileStmt = db()->prepare("SELECT `commission_rate` FROM `vendor_profiles` WHERE `user_id` = ? LIMIT 1");
$vProfileStmt->execute([$item['vendor_id']]);
$vProfile = $vProfileStmt->fetch();
$commRate = $vProfile ? (double)$vProfile['commission_rate'] : DEFAULT_COMMISSION;
$commissionAmount = ($rowTotal * $commRate) / 100;
$vendorEarnings = $rowTotal - $commissionAmount;
// Save order item
$insItem = db()->prepare("
INSERT INTO `order_items` (`order_id`, `product_id`, `vendor_id`, `variant_id`, `price`, `quantity`, `total_price`, `commission_amount`, `status`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
");
$insItem->execute([$orderId, $item['product_id'], $item['vendor_id'], $item['variant_id'], $unitPrice, $item['quantity'], $rowTotal, $commissionAmount]);
// Deduct product stock
if ($item['variant_id']) {
$updStock = db()->prepare("UPDATE `product_variants` SET `stock` = `stock` - ? WHERE `id` = ?");
$updStock->execute([$item['quantity'], $item['variant_id']]);
}
$updProductStock = db()->prepare("UPDATE `products` SET `stock` = `stock` - ? WHERE `id` = ?");
$updProductStock->execute([$item['quantity'], $item['product_id']]);
// Credit Vendor Wallet (Pending Balance until delivered)
$wallStmt = db()->prepare("INSERT INTO `wallet` (`user_id`, `balance`, `pending_balance`) VALUES (?, 0, ?) ON DUPLICATE KEY UPDATE `pending_balance` = `pending_balance` + ?");
$wallStmt->execute([$item['vendor_id'], $vendorEarnings, $vendorEarnings]);
}
// 5. Clear Cart
$clearCart = db()->prepare("DELETE FROM `cart` WHERE `user_id` = ? OR `session_id` = ?");
$clearCart->execute([$userId, $sessionId]);
// 6. Reset Coupon
unset($_SESSION['coupon']);
db()->commit();
// Redirect based on payment method
if ($paymentMethod === 'COD') {
redirect("success.php?order=" . $orderNumber);
} else {
redirect("pay.php?order=" . $orderNumber);
}
} catch (Exception $e) {
db()->rollBack();
set_flash_message('danger', 'Order Placement failed: ' . $e->getMessage());
redirect('checkout.php');
}
}
$pageTitle = "Order Checkout";
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/navbar.php';
?>
<div class="container my-5">
<h3 class="fw-bold mb-4">Secure Checkout</h3>
<?php
$flash = get_flash_message();
if ($flash):
?>
<div class="alert alert-<?php echo $flash['type']; ?> alert-dismissible fade show" role="alert">
<?php echo $flash['message']; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<form action="" method="POST" id="checkout-form">
<div class="row g-4">
<!-- Left Panel: Billing & Payments -->
<div class="col-lg-8">
<!-- Address Section -->
<div class="card border-0 shadow-sm p-4 rounded-4 mb-4">
<h5 class="fw-bold mb-3"><i class="bi bi-geo-alt text-primary me-2"></i> Shipping Address</h5>
<?php if (!empty($addresses)): ?>
<div class="row g-3 mb-3">
<?php foreach ($addresses as $addr): ?>
<div class="col-md-6">
<div class="card p-3 h-100 border">
<div class="form-check">
<input class="form-check-input" type="radio" name="address_id" id="addr-<?php echo $addr['id']; ?>" value="<?php echo $addr['id']; ?>" <?php echo $addr['is_default'] ? 'checked' : ''; ?> onclick="toggleAddressFields(false)">
<label class="form-check-label fw-bold text-dark" for="addr-<?php echo $addr['id']; ?>">
<?php echo htmlspecialchars($addr['label']); ?>
</label>
</div>
<p class="text-secondary small mt-2 mb-0">
<?php echo htmlspecialchars($addr['full_name']); ?><br>
Phone: <?php echo htmlspecialchars($addr['phone']); ?><br>
<?php echo htmlspecialchars($addr['address_line_1']); ?>, <?php echo htmlspecialchars($addr['city']); ?>
</p>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="radio" name="address_id" id="addr-new" value="0" onclick="toggleAddressFields(true)">
<label class="form-check-label fw-semibold" for="addr-new">
Ship to a new address
</label>
</div>
<?php else: ?>
<input type="hidden" name="address_id" value="0">
<p class="text-muted small">No saved addresses found. Please enter your address details below.</p>
<?php endif; ?>
<!-- Address Input Fields (Hidden if selecting saved address) -->
<div id="new-address-fields" class="<?php echo !empty($addresses) ? 'd-none' : ''; ?>">
<div class="row g-3">
<div class="col-md-6">
<label class="form-label small text-muted">Recipient Full Name</label>
<input type="text" name="full_name" class="form-control form-control-sm address-input" placeholder="e.g. John Doe">
</div>
<div class="col-md-6">
<label class="form-label small text-muted">Phone Number</label>
<input type="text" name="phone" class="form-control form-control-sm address-input" placeholder="e.g. +8801700000000">
</div>
<div class="col-12">
<label class="form-label small text-muted">Street Address</label>
<input type="text" name="address_line_1" class="form-control form-control-sm address-input" placeholder="House no, Street, Area">
</div>
<div class="col-md-4">
<label class="form-label small text-muted">City</label>
<input type="text" name="city" class="form-control form-control-sm address-input" placeholder="Dhaka">
</div>
<div class="col-md-4">
<label class="form-label small text-muted">State / Division</label>
<input type="text" name="state" class="form-control form-control-sm address-input" placeholder="Dhaka">
</div>
<div class="col-md-4">
<label class="form-label small text-muted">Postal Code</label>
<input type="text" name="postal_code" class="form-control form-control-sm address-input" placeholder="1230">
</div>
</div>
</div>
</div>
<!-- Payment Selection Section -->
<div class="card border-0 shadow-sm p-4 rounded-4">
<h5 class="fw-bold mb-4"><i class="bi bi-credit-card text-primary me-2"></i> Select Payment Method</h5>
<div class="row g-3">
<!-- COD (Always Enabled) -->
<div class="col-md-4 col-sm-6">
<div class="card p-3 text-center border cursor-pointer hover-up rounded-3 h-100" onclick="selectPayment('COD')">
<input class="form-check-input mx-auto mb-2" type="radio" name="payment_method" id="pay-cod" value="COD" checked>
<label class="form-check-label fw-bold text-dark" for="pay-cod">
<i class="bi bi-cash-stack text-success fs-3 d-block"></i> Cash on Delivery
</label>
</div>
</div>
<!-- Card System -->
<?php if (get_setting('payment_card_status') === 'active'): ?>
<div class="col-md-4 col-sm-6">
<div class="card p-3 text-center border cursor-pointer hover-up rounded-3 h-100" onclick="selectPayment('Card')">
<input class="form-check-input mx-auto mb-2" type="radio" name="payment_method" id="pay-card" value="Card">
<label class="form-check-label fw-bold text-dark" for="pay-card">
<i class="bi bi-credit-card-2-back text-info fs-3 d-block"></i> Card / Stripe
</label>
</div>
</div>
<?php endif; ?>
<!-- PayPal -->
<?php if (get_setting('payment_paypal_status') === 'active'): ?>
<div class="col-md-4 col-sm-6">
<div class="card p-3 text-center border cursor-pointer hover-up rounded-3 h-100" onclick="selectPayment('PayPal')">
<input class="form-check-input mx-auto mb-2" type="radio" name="payment_method" id="pay-paypal" value="PayPal">
<label class="form-check-label fw-bold text-dark" for="pay-paypal">
<i class="bi bi-paypal text-primary fs-3 d-block"></i> PayPal Gateway
</label>
</div>
</div>
<?php endif; ?>
<!-- RazorPay -->
<?php if (get_setting('payment_razorpay_status') === 'active'): ?>
<div class="col-md-4 col-sm-6">
<div class="card p-3 text-center border cursor-pointer hover-up rounded-3 h-100" onclick="selectPayment('RazorPay')">
<input class="form-check-input mx-auto mb-2" type="radio" name="payment_method" id="pay-razorpay" value="RazorPay">
<label class="form-check-label fw-bold text-dark" for="pay-razorpay">
<i class="bi bi-lightning-fill text-warning fs-3 d-block"></i> RazorPay System
</label>
</div>
</div>
<?php endif; ?>
<!-- UddoktoPay -->
<?php if (get_setting('payment_uddoktopay_status') === 'active'): ?>
<div class="col-md-4 col-sm-6">
<div class="card p-3 text-center border cursor-pointer hover-up rounded-3 h-100" onclick="selectPayment('UddoktoPay')">
<input class="form-check-input mx-auto mb-2" type="radio" name="payment_method" id="pay-uddokto" value="UddoktoPay">
<label class="form-check-label fw-bold text-dark" for="pay-uddokto">
<i class="bi bi-wallet2 text-danger fs-3 d-block"></i> UddoktoPay
</label>
</div>
</div>
<?php endif; ?>
<!-- AmarPay -->
<?php if (get_setting('payment_amarpay_status') === 'active'): ?>
<div class="col-md-4 col-sm-6">
<div class="card p-3 text-center border cursor-pointer hover-up rounded-3 h-100" onclick="selectPayment('AmarPay')">
<input class="form-check-input mx-auto mb-2" type="radio" name="payment_method" id="pay-amarpay" value="AmarPay">
<label class="form-check-label fw-bold text-dark" for="pay-amarpay">
<i class="bi bi-cash-coin text-success fs-3 d-block"></i> AmarPay Gateway
</label>
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<!-- Right Panel: Summary -->
<div class="col-lg-4">
<div class="card border-0 shadow-sm p-4 rounded-4 position-sticky" style="top: 100px;">
<h5 class="fw-bold mb-4">Review Order</h5>
<div class="list-group list-group-flush mb-4">
<?php foreach ($cartItems as $item):
$unitPrice = $item['p_disc_price'] !== null ? $item['p_disc_price'] : $item['p_price'];
if ($item['variant_id']) {
$unitPrice += $item['price_modifier'];
}
?>
<div class="list-group-item d-flex justify-content-between align-items-center py-2 px-0 bg-transparent">
<div>
<span class="small fw-semibold text-dark d-block text-truncate" style="max-width: 180px;"><?php echo htmlspecialchars($item['p_name']); ?></span>
<span class="text-muted small-text">Qty: <?php echo $item['quantity']; ?></span>
</div>
<span class="small fw-bold text-dark"><?php echo format_price($unitPrice * $item['quantity']); ?></span>
</div>
<?php endforeach; ?>
</div>
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="text-secondary small">Subtotal</span>
<span class="fw-semibold text-dark"><?php echo format_price($subtotal); ?></span>
</div>
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="text-secondary small">VAT / Tax</span>
<span class="fw-semibold text-dark"><?php echo format_price($totalTax); ?></span>
</div>
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="text-secondary small">Shipping</span>
<span class="fw-semibold text-dark"><?php echo format_price($totalShipping); ?></span>
</div>
<?php if ($discount > 0): ?>
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="text-success small fw-bold">Discount</span>
<span class="fw-bold text-success">-<?php echo format_price($discount); ?></span>
</div>
<?php endif; ?>
<hr class="my-3">
<div class="d-flex justify-content-between align-items-center mb-4">
<span class="fw-bold text-dark fs-5">Total Pay</span>
<span class="fw-bold text-primary fs-4"><?php echo format_price($grandTotal); ?></span>
</div>
<button type="submit" class="btn btn-primary btn-lg w-100 fw-bold rounded-3">Place Order <i class="bi bi-patch-check-fill ms-2"></i></button>
<p class="text-muted small text-center mt-3"><i class="bi bi-lock-fill"></i> Secure SSL Encrypted Connection</p>
</div>
</div>
</div>
</form>
</div>
<script>
function toggleAddressFields(show) {
const fields = document.getElementById('new-address-fields');
const inputs = fields.querySelectorAll('.address-input');
if (show) {
fields.classList.remove('d-none');
inputs.forEach(i => i.setAttribute('required', 'required'));
} else {
fields.classList.add('d-none');
inputs.forEach(i => i.removeAttribute('required'));
}
}
function selectPayment(method) {
const radio = document.querySelector(`input[name="payment_method"][value="${method}"]`);
if (radio) {
radio.checked = true;
}
}
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>