-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcart.php
More file actions
317 lines (288 loc) · 14.4 KB
/
Copy pathcart.php
File metadata and controls
317 lines (288 loc) · 14.4 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
<?php
/**
* Shopping Cart Details Page
*/
require_once __DIR__ . '/includes/helpers.php';
$sessionId = session_id();
$userId = $_SESSION['user_id'] ?? null;
// Fetch cart items
try {
if ($userId) {
$stmt = db()->prepare("
SELECT c.*, p.name as p_name, p.slug as p_slug, p.image as p_image, p.price as p_price,
p.discount_price as p_disc_price, p.tax as p_tax, p.shipping_cost as p_ship,
v.color, v.size, v.ram, v.storage, v.price_modifier
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]);
} else {
$stmt = db()->prepare("
SELECT c.*, p.name as p_name, p.slug as p_slug, p.image as p_image, p.price as p_price,
p.discount_price as p_disc_price, p.tax as p_tax, p.shipping_cost as p_ship,
v.color, v.size, v.ram, v.storage, v.price_modifier
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.session_id = ?
");
$stmt->execute([$sessionId]);
}
$cartItems = $stmt->fetchAll();
} catch (Exception $e) {
$cartItems = [];
}
// 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;
// Tax contribution
$totalTax += ($itemTotal * $item['p_tax']) / 100;
// Shipping contribution
$totalShipping += $item['p_ship'];
}
// Check coupon session
$discount = 0.00;
$couponCode = '';
if (isset($_SESSION['coupon'])) {
$cSession = $_SESSION['coupon'];
$couponCode = $cSession['code'];
if ($cSession['type'] === 'percent') {
$discount = ($subtotal * $cSession['value']) / 100;
} else {
$discount = $cSession['value'];
}
// Update stored session discount value
$_SESSION['coupon']['discount'] = $discount;
}
$grandTotal = ($subtotal + $totalTax + $totalShipping) - $discount;
if ($grandTotal < 0) $grandTotal = 0;
$pageTitle = "My Shopping Cart";
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/navbar.php';
?>
<div class="container my-5">
<h3 class="fw-bold mb-4"><i class="bi bi-cart3 text-primary me-2"></i> Shopping Cart</h3>
<?php if (empty($cartItems)): ?>
<div class="card border-0 shadow-sm p-5 text-center rounded-4">
<div class="fs-1 text-muted mb-3"><i class="bi bi-cart-x"></i></div>
<h5>Your shopping cart is empty.</h5>
<p class="text-secondary small">Looks like you haven't added any products to your cart yet.</p>
<a href="index.php" class="btn btn-primary btn-sm px-4 fw-bold">Shop Now</a>
</div>
<?php else: ?>
<div class="row g-4">
<!-- Left: Cart Items list -->
<div class="col-lg-8">
<div class="card border-0 shadow-sm p-4 rounded-4">
<div class="table-responsive">
<table class="table align-middle">
<thead class="bg-light">
<tr>
<th>Product</th>
<th>Price</th>
<th width="15%">Qty</th>
<th>Total</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
<?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'];
}
$rowTotal = $unitPrice * $item['quantity'];
// Variant description
$varDesc = [];
if ($item['color']) $varDesc[] = $item['color'];
if ($item['size']) $varDesc[] = $item['size'];
if ($item['ram']) $varDesc[] = $item['ram'];
if ($item['storage']) $varDesc[] = $item['storage'];
$varString = implode(', ', $varDesc);
?>
<tr id="cart-row-<?php echo $item['id']; ?>">
<td>
<div class="d-flex align-items-center gap-3">
<img src="<?php echo BASE_URL; ?>uploads/products/<?php echo htmlspecialchars($item['p_image']); ?>" onerror="this.src='https://placehold.co/50x50?text=Product';" class="rounded" width="50" height="50">
<div>
<a href="product.php?slug=<?php echo $item['p_slug']; ?>" class="fw-bold text-dark text-decoration-none small small-hover d-block"><?php echo htmlspecialchars($item['p_name']); ?></a>
<?php if ($varString): ?>
<span class="badge bg-secondary-subtle text-dark small-text" style="font-size: 11px;"><?php echo htmlspecialchars($varString); ?></span>
<?php endif; ?>
</div>
</div>
</td>
<td><?php echo format_price($unitPrice); ?></td>
<td>
<input type="number" class="form-control form-control-sm text-center cart-qty-input" data-cart-id="<?php echo $item['id']; ?>" value="<?php echo $item['quantity']; ?>" min="1">
</td>
<td class="fw-bold text-dark cart-row-total"><?php echo format_price($rowTotal); ?></td>
<td class="text-end">
<button type="button" class="btn btn-sm text-danger remove-cart-btn" data-cart-id="<?php echo $item['id']; ?>" title="Remove item">
<i class="bi bi-trash fs-5"></i>
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- Right: Order Summary -->
<div class="col-lg-4">
<!-- Promo Coupon Box -->
<div class="card border-0 shadow-sm p-4 rounded-4 mb-4">
<h5 class="fw-bold mb-3">Apply Promo Voucher</h5>
<form id="cart-coupon-form">
<input type="hidden" id="coupon-subtotal" value="<?php echo $subtotal; ?>">
<div class="input-group">
<input type="text" id="coupon-code-input" class="form-control" placeholder="Coupon Code (e.g. SAVE10)" value="<?php echo htmlspecialchars($couponCode); ?>">
<button class="btn btn-dark" type="submit">Apply</button>
</div>
</form>
<div id="coupon-status-msg" class="small mt-2"></div>
</div>
<!-- Summary totals -->
<div class="card border-0 shadow-sm p-4 rounded-4">
<h5 class="fw-bold mb-4">Order Summary</h5>
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="text-secondary small">Subtotal</span>
<span class="fw-semibold" id="cart-summary-subtotal"><?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" id="cart-summary-tax"><?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 Costs</span>
<span class="fw-semibold" id="cart-summary-shipping"><?php echo format_price($totalShipping); ?></span>
</div>
<div class="d-flex justify-content-between align-items-center mb-3 border-bottom pb-2 <?php echo $discount === 0.00 ? 'd-none' : ''; ?>" id="summary-discount-row">
<span class="text-success small fw-bold">Discount</span>
<span class="fw-bold text-success" id="cart-summary-discount">-<?php echo format_price($discount); ?></span>
</div>
<div class="d-flex justify-content-between align-items-center mb-4">
<span class="fw-bold text-dark fs-5">Grand Total</span>
<span class="fw-bold text-primary fs-4" id="cart-summary-grand"><?php echo format_price($grandTotal); ?></span>
</div>
<a href="checkout.php" class="btn btn-primary btn-lg w-100 fw-bold rounded-3">Proceed To Checkout <i class="bi bi-arrow-right ms-2"></i></a>
<a href="index.php" class="btn btn-outline-secondary w-100 fw-bold mt-2 rounded-3">Continue Shopping</a>
</div>
</div>
</div>
<?php endif; ?>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
// AJax Quantity Update
const qtyInputs = document.querySelectorAll('.cart-qty-input');
qtyInputs.forEach(input => {
input.addEventListener('change', function() {
const cartId = this.getAttribute('data-cart-id');
const qty = parseInt(this.value);
if (qty <= 0) {
this.value = 1;
return;
}
$.ajax({
url: BASE_URL + 'ajax/cart-handler.php',
method: 'POST',
data: {
action: 'update',
cart_id: cartId,
quantity: qty
},
dataType: 'json',
success: function(res) {
if (res.success) {
showToast('Success', 'Cart updated successfully!', 'success');
setTimeout(() => location.reload(), 800);
} else {
showToast('Warning', res.message, 'warning');
if (res.rollback_qty) {
input.value = res.rollback_qty;
}
}
},
error: function() {
showToast('Error', 'Failed to update item quantity.', 'danger');
}
});
});
});
// Remove Cart Item
const removeBtns = document.querySelectorAll('.remove-cart-btn');
removeBtns.forEach(btn => {
btn.addEventListener('click', function() {
const cartId = this.getAttribute('data-cart-id');
if(!confirm("Are you sure you want to remove this item from your cart?")) return;
$.ajax({
url: BASE_URL + 'ajax/cart-handler.php',
method: 'POST',
data: {
action: 'remove',
cart_id: cartId
},
dataType: 'json',
success: function(res) {
if (res.success) {
showToast('Success', res.message, 'success');
setTimeout(() => location.reload(), 800);
} else {
showToast('Error', res.message, 'danger');
}
},
error: function() {
showToast('Error', 'Failed to remove item.', 'danger');
}
});
});
});
// Apply Coupon
const couponForm = document.getElementById('cart-coupon-form');
if (couponForm) {
couponForm.addEventListener('submit', function(e) {
e.preventDefault();
const code = document.getElementById('coupon-code-input').value.trim();
const subtotal = parseFloat(document.getElementById('coupon-subtotal').value);
if (!code) return;
$.ajax({
url: BASE_URL + 'ajax/cart-handler.php',
method: 'POST',
data: {
action: 'apply_coupon',
coupon_code: code,
subtotal: subtotal
},
dataType: 'json',
success: function(res) {
const statusMsg = document.getElementById('coupon-status-msg');
if (res.success) {
statusMsg.innerHTML = `<span class="text-success fw-semibold">${res.message}</span>`;
showToast('Coupon Applied', res.message, 'success');
setTimeout(() => location.reload(), 1000);
} else {
statusMsg.innerHTML = `<span class="text-danger fw-semibold">${res.message}</span>`;
showToast('Error', res.message, 'danger');
}
},
error: function() {
showToast('Error', 'Coupon application error occurred.', 'danger');
}
});
});
}
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>