-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.php
More file actions
1002 lines (964 loc) · 53.3 KB
/
Copy pathadmin.php
File metadata and controls
1002 lines (964 loc) · 53.3 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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Admin Panel - Dashboard & Management
* ShopAlpha E-commerce Store
*/
require_once 'classes/User.php';
require_once 'classes/Product.php';
require_once 'classes/Order.php';
require_once 'classes/Review.php';
// Enforce admin privileges
if (!User::isAdmin()) {
header('Location: index.php');
exit;
}
$productModel = new Product();
$orderModel = new Order();
$reviewModel = new Review();
$db = getDB();
/**
* Handle product image upload. Returns stored path, or URL fallback, or empty.
*/
function handleImageUpload(): string {
$url = trim($_POST['image'] ?? '');
if (!empty($_FILES['image_file']['name']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$ext = strtolower(pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
throw new RuntimeException('Invalid file type. Allowed: ' . implode(', ', $allowed));
}
if ($_FILES['image_file']['size'] > 2 * 1024 * 1024) {
throw new RuntimeException('File too large. Max 2MB.');
}
$dir = __DIR__ . '/assets/images/products/';
$filename = uniqid('prod_') . '.' . $ext;
if (!move_uploaded_file($_FILES['image_file']['tmp_name'], $dir . $filename)) {
throw new RuntimeException('Failed to save file.');
}
return 'assets/images/products/' . $filename;
}
return $url;
}
/**
* Delete a local product image file.
*/
function deleteImageFile(string $path): void {
if (!empty($path) && !str_starts_with($path, 'http://') && !str_starts_with($path, 'https://')) {
$file = __DIR__ . '/' . $path;
if (file_exists($file)) {
unlink($file);
}
}
}
$message = '';
$error = '';
// Handle Admin Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!validateCsrfToken()) {
$error = 'Invalid session token. Please try again.';
} else {
$action = $_POST['action'] ?? '';
if ($action === 'create_product') {
$categoryId = (int)$_POST['category_id'];
$name = trim($_POST['name']);
$slug = trim($_POST['slug']);
$description = trim($_POST['description']);
$price = (float)$_POST['price'];
$stock = (int)$_POST['stock'];
$featured = isset($_POST['featured']) ? 1 : 0;
if (empty($name) || empty($slug) || $price < 0 || $stock < 0) {
$error = 'Invalid product data. Please check all fields.';
} else {
try {
$image = handleImageUpload();
} catch (RuntimeException $e) {
$error = $e->getMessage();
$image = '';
}
if (empty($error)) {
$success = $productModel->createProduct($categoryId, $name, $slug, $description, $price, $image, $stock, $featured);
if ($success) {
$message = 'Product created successfully.';
header('Location: admin.php?tab=products&msg=' . urlencode($message));
exit;
} else {
$error = 'Failed to create product. Slug may already be in use.';
}
}
}
}
if ($action === 'update_product') {
$productId = (int)$_POST['product_id'];
$categoryId = (int)$_POST['category_id'];
$name = trim($_POST['name']);
$slug = trim($_POST['slug']);
$description = trim($_POST['description']);
$price = (float)$_POST['price'];
$stock = (int)$_POST['stock'];
$featured = isset($_POST['featured']) ? 1 : 0;
if ($productId <= 0 || empty($name) || empty($slug) || $price < 0 || $stock < 0) {
$error = 'Invalid product data. Please check all fields.';
} else {
try {
$image = handleImageUpload();
} catch (RuntimeException $e) {
$error = $e->getMessage();
$image = '';
}
if (empty($error)) {
// If a new image was uploaded, delete the old one
if (!empty($_FILES['image_file']['name']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
$oldProduct = $productModel->getById($productId);
if ($oldProduct) {
deleteImageFile($oldProduct['image']);
}
}
$oldProduct = $productModel->getById($productId);
if ($oldProduct && empty($image)) {
$image = $oldProduct['image'];
}
$success = $productModel->updateProduct($productId, $categoryId, $name, $slug, $description, $price, $image, $stock, $featured);
if ($success) {
$message = 'Product updated successfully.';
header('Location: admin.php?tab=products&msg=' . urlencode($message));
exit;
} else {
$error = 'Failed to update product. Slug may already be in use.';
}
}
}
}
if ($action === 'delete_product') {
$productId = (int)$_POST['product_id'];
if ($productId > 0) {
$old = $productModel->getById($productId);
if ($old) {
deleteImageFile($old['image']);
}
$success = $productModel->deleteProduct($productId);
if ($success) {
$message = 'Product deleted successfully.';
} else {
$error = 'Failed to delete product.';
}
}
}
if ($action === 'update_order_status') {
$orderId = (int)$_POST['order_id'];
$status = $_POST['status'] ?? '';
if ($orderId > 0 && !empty($status)) {
$success = $orderModel->updateStatus($orderId, $status);
if ($success) {
$message = 'Order status updated successfully.';
} else {
$error = 'Failed to update order status.';
}
}
}
if ($action === 'delete_review') {
$reviewId = (int)$_POST['review_id'];
if ($reviewId > 0) {
$success = $reviewModel->deleteReview($reviewId);
if ($success) {
$message = 'Review deleted successfully.';
} else {
$error = 'Failed to delete review.';
}
}
}
if ($action === 'delete_user') {
$userId = (int)$_POST['user_id'];
if ($userId > 0) {
$success = $userModel->deleteUser($userId);
$message = $success ? 'User deleted successfully.' : 'Failed to delete user (cannot delete admins).';
}
}
if ($action === 'create_category') {
$name = trim($_POST['name']);
$slug = trim($_POST['slug']);
if (empty($name) || empty($slug)) {
$error = 'Category name and slug are required.';
} else {
$success = $productModel->createCategory($name, $slug);
$message = $success ? 'Category created successfully.' : 'Failed to create category. Slug may already exist.';
}
}
if ($action === 'update_category') {
$id = (int)$_POST['category_id'];
$name = trim($_POST['name']);
$slug = trim($_POST['slug']);
if ($id <= 0 || empty($name) || empty($slug)) {
$error = 'Invalid category data.';
} else {
$success = $productModel->updateCategory($id, $name, $slug);
$message = $success ? 'Category updated successfully.' : 'Failed to update category.';
}
}
if ($action === 'delete_category') {
$id = (int)$_POST['category_id'];
if ($id > 0) {
$productModel->deleteCategory($id);
$message = 'Category deleted successfully.';
}
}
}
}
// Check for redirect message
if (isset($_GET['msg'])) {
$message = $_GET['msg'];
}
$tab = $_GET['tab'] ?? 'dashboard';
$pageTitle = 'Admin Panel';
require_once 'includes/header.php';
?>
<div class="admin-page">
<div class="admin-header">
<h1><i class="fas fa-user-shield"></i> Admin Dashboard</h1>
<p>Control center for products, orders, and customer reviews.</p>
</div>
<!-- Admin Navigation Tabs -->
<div class="admin-tabs">
<a href="admin.php?tab=dashboard" class="admin-tab-btn <?= $tab === 'dashboard' ? 'active' : '' ?>">
<i class="fas fa-chart-line"></i> Dashboard
</a>
<a href="admin.php?tab=products" class="admin-tab-btn <?= in_array($tab, ['products', 'add_product', 'edit_product']) ? 'active' : '' ?>">
<i class="fas fa-boxes"></i> Products
</a>
<a href="admin.php?tab=orders" class="admin-tab-btn <?= in_array($tab, ['orders', 'order_detail']) ? 'active' : '' ?>">
<i class="fas fa-shopping-bag"></i> Orders
</a>
<a href="admin.php?tab=reviews" class="admin-tab-btn <?= $tab === 'reviews' ? 'active' : '' ?>">
<i class="fas fa-star"></i> Reviews
</a>
<a href="admin.php?tab=categories" class="admin-tab-btn <?= in_array($tab, ['categories', 'add_category', 'edit_category']) ? 'active' : '' ?>">
<i class="fas fa-tags"></i> Categories
</a>
<a href="admin.php?tab=users" class="admin-tab-btn <?= $tab === 'users' ? 'active' : '' ?>">
<i class="fas fa-users"></i> Users
</a>
</div>
<!-- Success/Error Feedback -->
<?php if (!empty($message)): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($message) ?></div>
<?php endif; ?>
<?php if (!empty($error)): ?>
<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<div class="admin-tab-content">
<!-- 1. DASHBOARD VIEW -->
<?php if ($tab === 'dashboard'):
// Fetch stats
$totalSales = $db->query("SELECT SUM(total_amount) FROM orders WHERE status != 'cancelled'")->fetchColumn() ?: 0.0;
$totalOrders = $db->query("SELECT COUNT(*) FROM orders")->fetchColumn() ?: 0;
$totalProducts = $db->query("SELECT COUNT(*) FROM products")->fetchColumn() ?: 0;
$totalReviews = $db->query("SELECT COUNT(*) FROM reviews")->fetchColumn() ?: 0;
$totalUsers = $db->query("SELECT COUNT(*) FROM users")->fetchColumn() ?: 0;
?>
<div class="admin-stats-grid">
<div class="admin-stat-card">
<div class="stat-icon"><i class="fas fa-dollar-sign"></i></div>
<div class="stat-info">
<h3><?= CURRENCY . number_format($totalSales, 2) ?></h3>
<p>Total Revenue (Active)</p>
</div>
</div>
<div class="admin-stat-card">
<div class="stat-icon"><i class="fas fa-shopping-cart"></i></div>
<div class="stat-info">
<h3><?= $totalOrders ?></h3>
<p>Total Orders</p>
</div>
</div>
<div class="admin-stat-card">
<div class="stat-icon"><i class="fas fa-tshirt"></i></div>
<div class="stat-info">
<h3><?= $totalProducts ?></h3>
<p>Total Products</p>
</div>
</div>
<div class="admin-stat-card">
<div class="stat-icon"><i class="fas fa-users"></i></div>
<div class="stat-info">
<h3><?= $totalUsers ?></h3>
<p>Registered Users</p>
</div>
</div>
</div>
<!-- Recent Orders Summary -->
<div class="admin-section-card">
<div class="card-header">
<h2><i class="fas fa-history"></i> Recent Orders</h2>
<a href="admin.php?tab=orders" class="btn-text">View All <i class="fas fa-arrow-right"></i></a>
</div>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>Order ID</th>
<th>Customer</th>
<th>Date</th>
<th>Total</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$recentOrders = $db->query("
SELECT o.*, u.full_name FROM orders o
JOIN users u ON o.user_id = u.id
ORDER BY o.created_at DESC LIMIT 5
")->fetchAll();
foreach ($recentOrders as $order): ?>
<tr>
<td>#<?= $order['id'] ?></td>
<td><?= htmlspecialchars($order['full_name']) ?></td>
<td><?= date('M d, Y', strtotime($order['created_at'])) ?></td>
<td><?= CURRENCY . number_format($order['total_amount'], 2) ?></td>
<td>
<span class="badge <?= Order::getStatusBadge($order['status']) ?>">
<?= ucfirst($order['status']) ?>
</span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<!-- 2. PRODUCTS VIEW -->
<?php elseif ($tab === 'products'):
$pPage = isset($_GET['p']) ? max(1, (int)$_GET['p']) : 1;
$pPerPage = 20;
$pOffset = ($pPage - 1) * $pPerPage;
$pSearch = trim($_GET['search'] ?? '');
$pCat = isset($_GET['pcat']) ? (int)$_GET['pcat'] : 0;
$allProducts = $productModel->getAllAdmin($pPerPage, $pOffset, $pSearch, $pCat);
$pTotal = $productModel->getAdminCount($pSearch, $pCat);
$pTotalPages = max(1, (int)ceil($pTotal / $pPerPage));
$allCategories = $productModel->getCategories();
$pQueryStr = 'tab=products' . ($pSearch ? '&search=' . urlencode($pSearch) : '') . ($pCat ? '&pcat=' . $pCat : '');
?>
<div class="admin-section-header">
<h2>Manage Products (<?= $pTotal ?>)</h2>
<a href="admin.php?tab=add_product" class="admin-btn-primary"><i class="fas fa-plus"></i> Add Product</a>
</div>
<form method="GET" style="display:flex;gap:12px;margin-bottom:16px;flex-wrap:wrap">
<input type="hidden" name="tab" value="products">
<input type="text" name="search" placeholder="Search products..." value="<?= htmlspecialchars($pSearch) ?>" style="padding:8px 14px;border:1px solid var(--border);border-radius:var(--radius-sm);flex:1;min-width:200px">
<select name="pcat" style="padding:8px 14px;border:1px solid var(--border);border-radius:var(--radius-sm)">
<option value="0">All Categories</option>
<?php foreach ($allCategories as $cat): ?>
<option value="<?= $cat['id'] ?>" <?= $pCat === (int)$cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
<?php endforeach; ?>
</select>
<button type="submit" class="admin-btn-primary" style="padding:8px 20px">Filter</button>
</form>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Stock</th>
<th>Featured</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($allProducts as $p): ?>
<tr>
<td>
<img src="<?= htmlspecialchars($p['image'] ?: 'assets/images/placeholder.png') ?>" alt="" class="table-img">
</td>
<td>
<strong><?= htmlspecialchars($p['name']) ?></strong>
<div class="table-subtext"><?= htmlspecialchars($p['slug']) ?></div>
</td>
<td><?= htmlspecialchars($p['category_name']) ?></td>
<td><?= CURRENCY . number_format($p['price'], 2) ?></td>
<td>
<span class="stock-indicator <?= $p['stock'] <= 5 ? 'low' : '' ?>">
<?= $p['stock'] ?> left
</span>
</td>
<td>
<?= $p['featured'] ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-secondary">No</span>' ?>
</td>
<td>
<div class="table-actions">
<a href="admin.php?tab=edit_product&id=<?= $p['id'] ?>" class="btn-icon text-info" title="Edit">
<i class="fas fa-edit"></i>
</a>
<form method="POST" onsubmit="return confirm('Are you sure you want to delete this product?');" style="display:inline">
<input type="hidden" name="action" value="delete_product">
<input type="hidden" name="product_id" value="<?= $p['id'] ?>">
<?= csrfField() ?>
<button type="submit" class="btn-icon text-danger" title="Delete">
<i class="fas fa-trash-alt"></i>
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php if ($pTotalPages > 1): ?>
<div class="pagination" style="margin-top:24px">
<?php if ($pPage > 1): ?>
<a href="?<?= $pQueryStr ?>&p=<?= $pPage - 1 ?>" class="pagination-link"><i class="fas fa-chevron-left"></i> Prev</a>
<?php endif; ?>
<?php for ($i = 1; $i <= $pTotalPages; $i++): ?>
<a href="?<?= $pQueryStr ?>&p=<?= $i ?>" class="pagination-link <?= $i === $pPage ? 'active' : '' ?>"><?= $i ?></a>
<?php endfor; ?>
<?php if ($pPage < $pTotalPages): ?>
<a href="?<?= $pQueryStr ?>&p=<?= $pPage + 1 ?>" class="pagination-link">Next <i class="fas fa-chevron-right"></i></a>
<?php endif; ?>
</div>
<?php endif; ?>
<!-- 3. ADD PRODUCT VIEW -->
<?php elseif ($tab === 'add_product'):
$categories = $productModel->getCategories();
?>
<div class="admin-section-header">
<h2>Add New Product</h2>
<a href="admin.php?tab=products" class="admin-btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>
<div class="admin-form-card">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="create_product">
<div class="form-row">
<div class="form-group">
<label for="name">Product Name</label>
<input type="text" id="name" name="name" required placeholder="e.g. Ergonomic Office Chair" oninput="document.getElementById('slug').value = this.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')">
</div>
<div class="form-group">
<label for="slug">URL Slug</label>
<input type="text" id="slug" name="slug" required placeholder="e.g. ergonomic-office-chair">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="category_id">Category</label>
<select id="category_id" name="category_id" required>
<?php foreach ($categories as $cat): ?>
<option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="price">Price (<?= CURRENCY ?>)</label>
<input type="number" id="price" name="price" step="0.01" min="0" required placeholder="0.00">
</div>
<div class="form-group">
<label for="stock">Initial Stock</label>
<input type="number" id="stock" name="stock" min="0" required placeholder="10">
</div>
</div>
<div class="form-group">
<label for="image_file">Upload Image</label>
<input type="file" id="image_file" name="image_file" accept="image/jpeg,image/png,image/gif,image/webp">
</div>
<div class="form-group">
<label for="image">Or paste Image URL</label>
<input type="text" id="image" name="image" placeholder="https://images.unsplash.com/...">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea id="description" name="description" rows="5" placeholder="Describe the product features..."></textarea>
</div>
<div class="form-group-checkbox">
<label for="featured">
<input type="checkbox" id="featured" name="featured" value="1">
<span>Feature on Homepage</span>
</label>
</div>
<?= csrfField() ?>
<button type="submit" class="admin-btn-primary">Save Product</button>
</form>
</div>
<!-- 4. EDIT PRODUCT VIEW -->
<?php elseif ($tab === 'edit_product'):
$productId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$product = $productModel->getById($productId);
if (!$product) {
echo '<p>Product not found.</p>';
} else {
$categories = $productModel->getCategories();
?>
<div class="admin-section-header">
<h2>Edit Product: <?= htmlspecialchars($product['name']) ?></h2>
<a href="admin.php?tab=products" class="admin-btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>
<div class="admin-form-card">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="update_product">
<input type="hidden" name="product_id" value="<?= $product['id'] ?>">
<div class="form-row">
<div class="form-group">
<label for="name">Product Name</label>
<input type="text" id="name" name="name" required value="<?= htmlspecialchars($product['name']) ?>" oninput="document.getElementById('slug').value = this.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')">
</div>
<div class="form-group">
<label for="slug">URL Slug</label>
<input type="text" id="slug" name="slug" required value="<?= htmlspecialchars($product['slug']) ?>">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="category_id">Category</label>
<select id="category_id" name="category_id" required>
<?php foreach ($categories as $cat): ?>
<option value="<?= $cat['id'] ?>" <?= $cat['id'] == $product['category_id'] ? 'selected' : '' ?>>
<?= htmlspecialchars($cat['name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="price">Price (<?= CURRENCY ?>)</label>
<input type="number" id="price" name="price" step="0.01" min="0" required value="<?= $product['price'] ?>">
</div>
<div class="form-group">
<label for="stock">Stock</label>
<input type="number" id="stock" name="stock" min="0" required value="<?= $product['stock'] ?>">
</div>
</div>
<?php if ($product['image']): ?>
<div class="form-group">
<label>Current Image</label>
<div class="admin-image-preview">
<img src="<?= htmlspecialchars($product['image']) ?>" alt="Current">
<span class="admin-image-preview-name"><?= htmlspecialchars(basename($product['image'])) ?></span>
</div>
</div>
<?php endif; ?>
<div class="form-group">
<label for="image_file">Upload New Image</label>
<input type="file" id="image_file" name="image_file" accept="image/jpeg,image/png,image/gif,image/webp">
<p class="form-help">Leave empty to keep the current image.</p>
</div>
<div class="form-group">
<label for="image">Or paste Image URL</label>
<input type="text" id="image" name="image" value="<?= htmlspecialchars($product['image'] ?? '') ?>" placeholder="https://images.unsplash.com/...">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea id="description" name="description" rows="5"><?= htmlspecialchars($product['description']) ?></textarea>
</div>
<div class="form-group-checkbox">
<label for="featured">
<input type="checkbox" id="featured" name="featured" value="1" <?= $product['featured'] ? 'checked' : '' ?>>
<span>Feature on Homepage</span>
</label>
</div>
<?= csrfField() ?>
<button type="submit" class="admin-btn-primary">Update Product</button>
</form>
</div>
<?php } ?>
<!-- 5. ORDERS VIEW -->
<?php elseif ($tab === 'orders'):
$oPage = isset($_GET['op']) ? max(1, (int)$_GET['op']) : 1;
$oPerPage = 20;
$oOffset = ($oPage - 1) * $oPerPage;
$allOrders = $orderModel->getAllOrdersPaginated($oPerPage, $oOffset);
$oTotal = $orderModel->getOrdersCount();
$oTotalPages = max(1, (int)ceil($oTotal / $oPerPage));
?>
<div class="admin-section-header">
<h2>Manage Orders (<?= $oTotal ?>)</h2>
</div>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>Order ID</th>
<th>Customer</th>
<th>Details</th>
<th>Shipping Address</th>
<th>Total</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($allOrders as $order): ?>
<tr>
<td>
<strong>#<?= $order['id'] ?></strong>
<div class="table-subtext"><?= date('M d, Y H:i', strtotime($order['created_at'])) ?></div>
</td>
<td>
<strong><?= htmlspecialchars($order['customer_name']) ?></strong>
<div class="table-subtext"><?= htmlspecialchars($order['customer_email']) ?></div>
</td>
<td>
<div class="table-actions" style="gap:8px">
<a href="admin.php?tab=order_detail&id=<?= $order['id'] ?>" class="btn-text-small">
<i class="fas fa-eye"></i> View
</a>
<a href="invoice.php?order_id=<?= $order['id'] ?>" class="btn-text-small" target="_blank">
<i class="fas fa-file-invoice"></i> Invoice
</a>
</div>
</td>
<td><div class="table-address"><?= nl2br(htmlspecialchars($order['shipping_address'])) ?></div></td>
<td><?= CURRENCY . number_format($order['total_amount'], 2) ?></td>
<td>
<span class="badge <?= Order::getStatusBadge($order['status']) ?>">
<?= ucfirst($order['status']) ?>
</span>
</td>
<td>
<form method="POST" class="order-status-form">
<input type="hidden" name="action" value="update_order_status">
<input type="hidden" name="order_id" value="<?= $order['id'] ?>">
<?= csrfField() ?>
<select name="status" class="select-sm" onchange="this.form.submit()">
<option value="pending" <?= $order['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
<option value="processing" <?= $order['status'] === 'processing' ? 'selected' : '' ?>>Processing</option>
<option value="completed" <?= $order['status'] === 'completed' ? 'selected' : '' ?>>Completed</option>
<option value="cancelled" <?= $order['status'] === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
</select>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php if ($oTotalPages > 1): ?>
<div class="pagination" style="margin-top:24px">
<?php if ($oPage > 1): ?>
<a href="?tab=orders&op=<?= $oPage - 1 ?>" class="pagination-link"><i class="fas fa-chevron-left"></i> Prev</a>
<?php endif; ?>
<?php for ($i = 1; $i <= $oTotalPages; $i++): ?>
<a href="?tab=orders&op=<?= $i ?>" class="pagination-link <?= $i === $oPage ? 'active' : '' ?>"><?= $i ?></a>
<?php endfor; ?>
<?php if ($oPage < $oTotalPages): ?>
<a href="?tab=orders&op=<?= $oPage + 1 ?>" class="pagination-link">Next <i class="fas fa-chevron-right"></i></a>
<?php endif; ?>
</div>
<?php endif; ?>
<!-- 6. ORDER DETAIL VIEW -->
<?php elseif ($tab === 'order_detail'):
$orderId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$detail = $orderModel->getOrderById($orderId);
if (!$detail): ?>
<div class="alert alert-danger">Order not found.</div>
<?php else: ?>
<div class="admin-section-header">
<h2>Order #<?= $detail['id'] ?> — Details</h2>
<a href="admin.php?tab=orders" class="admin-btn-secondary"><i class="fas fa-arrow-left"></i> Back to Orders</a>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:32px">
<div class="admin-section-card" style="margin-bottom:0">
<div class="card-header"><h2><i class="fas fa-user"></i> Customer</h2></div>
<p><strong><?= htmlspecialchars($detail['customer_name']) ?></strong></p>
<p style="color:var(--text-light)"><?= htmlspecialchars($detail['customer_email']) ?></p>
</div>
<div class="admin-section-card" style="margin-bottom:0">
<div class="card-header"><h2><i class="fas fa-truck"></i> Order Info</h2></div>
<p><strong>Status:</strong> <span class="badge <?= Order::getStatusBadge($detail['status']) ?>"><?= ucfirst($detail['status']) ?></span></p>
<p><strong>Date:</strong> <?= date('F d, Y H:i', strtotime($detail['created_at'])) ?></p>
<p><strong>Payment:</strong> <?= htmlspecialchars(ucwords(str_replace('_', ' ', $detail['payment_method']))) ?></p>
<p><strong>Total:</strong> <?= CURRENCY . number_format($detail['total_amount'], 2) ?></p>
<?php if (!empty($detail['notes'])): ?>
<p><strong>Notes:</strong> <?= nl2br(htmlspecialchars($detail['notes'])) ?></p>
<?php endif; ?>
</div>
</div>
<div class="admin-section-card">
<div class="card-header"><h2><i class="fas fa-map-marker-alt"></i> Shipping Address</h2></div>
<p><?= nl2br(htmlspecialchars($detail['shipping_address'])) ?></p>
</div>
<div class="admin-section-card">
<div class="card-header"><h2><i class="fas fa-boxes"></i> Items (<?= count($detail['items']) ?>)</h2></div>
<div class="table-responsive" style="border:none;padding:0">
<table class="admin-table">
<thead>
<tr><th>Product</th><th>Price</th><th>Qty</th><th>Subtotal</th></tr>
</thead>
<tbody>
<?php foreach ($detail['items'] as $item): ?>
<tr>
<td>
<div style="display:flex;align-items:center;gap:12px">
<img src="<?= htmlspecialchars($item['image'] ?: 'assets/images/placeholder.png') ?>" alt="" style="width:40px;height:40px;border-radius:6px;object-fit:cover">
<strong><?= htmlspecialchars($item['name']) ?></strong>
</div>
</td>
<td><?= CURRENCY . number_format($item['unit_price'], 2) ?></td>
<td><?= $item['quantity'] ?></td>
<td><?= CURRENCY . number_format($item['unit_price'] * $item['quantity'], 2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<td colspan="3" style="text-align:right;font-weight:700">Total:</td>
<td style="font-weight:700"><?= CURRENCY . number_format($detail['total_amount'], 2) ?></td>
</tr>
</tfoot>
</table>
</div>
</div>
<div class="admin-section-card">
<div class="card-header"><h2><i class="fas fa-edit"></i> Update Status</h2></div>
<form method="POST" style="display:flex;gap:12px;align-items:center">
<input type="hidden" name="action" value="update_order_status">
<input type="hidden" name="order_id" value="<?= $detail['id'] ?>">
<?= csrfField() ?>
<select name="status" class="select-sm" style="padding:10px 16px;font-size:.95rem">
<option value="pending" <?= $detail['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
<option value="processing" <?= $detail['status'] === 'processing' ? 'selected' : '' ?>>Processing</option>
<option value="completed" <?= $detail['status'] === 'completed' ? 'selected' : '' ?>>Completed</option>
<option value="cancelled" <?= $detail['status'] === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
</select>
<button type="submit" class="admin-btn-primary">Update</button>
</form>
</div>
<?php endif; ?>
<!-- 7. REVIEWS VIEW -->
<?php elseif ($tab === 'reviews'):
$rPage = isset($_GET['rp']) ? max(1, (int)$_GET['rp']) : 1;
$rPerPage = 20;
$rOffset = ($rPage - 1) * $rPerPage;
$allReviews = $reviewModel->getAllReviewsPaginated($rPerPage, $rOffset);
$rTotal = $reviewModel->getReviewsCount();
$rTotalPages = max(1, (int)ceil($rTotal / $rPerPage));
?>
<div class="admin-section-header">
<h2>Manage Customer Reviews (<?= $rTotal ?>)</h2>
</div>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>Review ID</th>
<th>Product</th>
<th>Reviewer</th>
<th>Rating</th>
<th>Comment</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($allReviews as $rev): ?>
<tr>
<td>#<?= $rev['id'] ?></td>
<td><?= htmlspecialchars($rev['product_name']) ?></td>
<td>
<strong><?= htmlspecialchars($rev['reviewer_name']) ?></strong>
<div class="table-subtext"><?= htmlspecialchars($rev['reviewer_email']) ?></div>
</td>
<td>
<span class="review-stars-admin">
<?php for ($i = 1; $i <= 5; $i++): ?>
<i class="fa<?= $i <= $rev['rating'] ? 's' : 'r' ?> fa-star text-warning"></i>
<?php endfor; ?>
</span>
</td>
<td><div class="table-comment"><?= nl2br(htmlspecialchars($rev['comment'])) ?></div></td>
<td><?= date('M d, Y', strtotime($rev['created_at'])) ?></td>
<td>
<form method="POST" onsubmit="return confirm('Are you sure you want to delete this review?');">
<input type="hidden" name="action" value="delete_review">
<input type="hidden" name="review_id" value="<?= $rev['id'] ?>">
<?= csrfField() ?>
<button type="submit" class="btn-icon text-danger" title="Delete Review">
<i class="fas fa-trash-alt"></i>
</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php if ($rTotalPages > 1): ?>
<div class="pagination" style="margin-top:24px">
<?php if ($rPage > 1): ?>
<a href="?tab=reviews&rp=<?= $rPage - 1 ?>" class="pagination-link"><i class="fas fa-chevron-left"></i> Prev</a>
<?php endif; ?>
<?php for ($i = 1; $i <= $rTotalPages; $i++): ?>
<a href="?tab=reviews&rp=<?= $i ?>" class="pagination-link <?= $i === $rPage ? 'active' : '' ?>"><?= $i ?></a>
<?php endfor; ?>
<?php if ($rPage < $rTotalPages): ?>
<a href="?tab=reviews&rp=<?= $rPage + 1 ?>" class="pagination-link">Next <i class="fas fa-chevron-right"></i></a>
<?php endif; ?>
</div>
<?php endif; ?>
<!-- 8. CATEGORIES VIEW -->
<?php elseif ($tab === 'categories' || $tab === 'add_category' || $tab === 'edit_category'): ?>
<?php if ($tab === 'add_category'): ?>
<div class="admin-section-header">
<h2>Add New Category</h2>
<a href="admin.php?tab=categories" class="admin-btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>
<div class="admin-form-card">
<form method="POST">
<input type="hidden" name="action" value="create_category">
<div class="form-row">
<div class="form-group">
<label for="cat_name">Category Name</label>
<input type="text" id="cat_name" name="name" required placeholder="e.g. Books" oninput="document.getElementById('cat_slug').value = this.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')">
</div>
<div class="form-group">
<label for="cat_slug">Slug</label>
<input type="text" id="cat_slug" name="slug" required placeholder="e.g. books">
</div>
</div>
<?= csrfField() ?>
<button type="submit" class="admin-btn-primary">Save Category</button>
</form>
</div>
<?php elseif ($tab === 'edit_category'): ?>
<?php $catId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$category = $productModel->getCategoryById($catId);
if (!$category): ?>
<p>Category not found.</p>
<?php else: ?>
<div class="admin-section-header">
<h2>Edit Category: <?= htmlspecialchars($category['name']) ?></h2>
<a href="admin.php?tab=categories" class="admin-btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
</div>
<div class="admin-form-card">
<form method="POST">
<input type="hidden" name="action" value="update_category">
<input type="hidden" name="category_id" value="<?= $category['id'] ?>">
<div class="form-row">
<div class="form-group">
<label for="cat_name">Category Name</label>
<input type="text" id="cat_name" name="name" required value="<?= htmlspecialchars($category['name']) ?>" oninput="document.getElementById('cat_slug').value = this.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')">
</div>
<div class="form-group">
<label for="cat_slug">Slug</label>
<input type="text" id="cat_slug" name="slug" required value="<?= htmlspecialchars($category['slug']) ?>">
</div>
</div>
<?= csrfField() ?>
<button type="submit" class="admin-btn-primary">Update Category</button>
</form>
</div>
<?php endif; ?>
<?php else: ?>
<div class="admin-section-header">
<h2>Manage Categories</h2>
<a href="admin.php?tab=add_category" class="admin-btn-primary"><i class="fas fa-plus"></i> Add Category</a>
</div>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Slug</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php $allCategories = $productModel->getCategories(); ?>
<?php foreach ($allCategories as $cat): ?>
<tr>
<td>#<?= $cat['id'] ?></td>
<td><strong><?= htmlspecialchars($cat['name']) ?></strong></td>
<td><code><?= htmlspecialchars($cat['slug']) ?></code></td>
<td>
<div class="table-actions">
<a href="admin.php?tab=edit_category&id=<?= $cat['id'] ?>" class="btn-icon text-info" title="Edit">
<i class="fas fa-edit"></i>
</a>
<form method="POST" onsubmit="return confirm('Delete this category? Products in it will also be removed.');" style="display:inline">
<input type="hidden" name="action" value="delete_category">
<input type="hidden" name="category_id" value="<?= $cat['id'] ?>">
<?= csrfField() ?>
<button type="submit" class="btn-icon text-danger" title="Delete">
<i class="fas fa-trash-alt"></i>
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
<!-- 8. USERS VIEW -->
<?php elseif ($tab === 'users'):
$uPage = isset($_GET['up']) ? max(1, (int)$_GET['up']) : 1;
$uPerPage = 20;
$uOffset = ($uPage - 1) * $uPerPage;
$allUsers = $userModel->getAllUsersPaginated($uPerPage, $uOffset);
$uTotal = $userModel->getUsersCount();
$uTotalPages = max(1, (int)ceil($uTotal / $uPerPage));
?>
<div class="admin-section-header">
<h2>Manage Users (<?= $uTotal ?>)</h2>
</div>
<div class="table-responsive">
<table class="admin-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Orders</th>
<th>Admin</th>
<th>Joined</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($allUsers as $u): ?>
<tr>
<td>#<?= $u['id'] ?></td>
<td><strong><?= htmlspecialchars($u['full_name']) ?></strong></td>
<td><?= htmlspecialchars($u['email']) ?></td>
<td><?= htmlspecialchars($u['phone'] ?: '-') ?></td>
<td><?= $u['order_count'] ?></td>
<td><?= $u['is_admin'] ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-secondary">No</span>' ?></td>
<td class="table-subtext"><?= date('M d, Y', strtotime($u['created_at'])) ?></td>
<td>
<?php if (!$u['is_admin']): ?>
<form method="POST" onsubmit="return confirm('Delete user <?= htmlspecialchars($u['full_name']) ?>? This cannot be undone.');" style="display:inline">
<input type="hidden" name="action" value="delete_user">
<input type="hidden" name="user_id" value="<?= $u['id'] ?>">
<?= csrfField() ?>
<button type="submit" class="btn-icon text-danger" title="Delete User">
<i class="fas fa-trash-alt"></i>
</button>
</form>
<?php else: ?>
<span class="table-subtext">Protected</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php if ($uTotalPages > 1): ?>
<div class="pagination" style="margin-top:24px">
<?php if ($uPage > 1): ?>
<a href="?tab=users&up=<?= $uPage - 1 ?>" class="pagination-link"><i class="fas fa-chevron-left"></i> Prev</a>
<?php endif; ?>
<?php for ($i = 1; $i <= $uTotalPages; $i++): ?>
<a href="?tab=users&up=<?= $i ?>" class="pagination-link <?= $i === $uPage ? 'active' : '' ?>"><?= $i ?></a>
<?php endfor; ?>
<?php if ($uPage < $uTotalPages): ?>
<a href="?tab=users&up=<?= $uPage + 1 ?>" class="pagination-link">Next <i class="fas fa-chevron-right"></i></a>
<?php endif; ?>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
</div>