<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../app/Utils.php';
require_once __DIR__ . '/../../app/Models/Admin.php';
require_once __DIR__ . '/../../app/Models/Parcel.php';

// Check admin login
if (!Admin::isLoggedIn()) {
    Utils::redirect('/routex/admin/login');
}

$parcel_model = new Parcel($pdo);
$error = $_SESSION['error'] ?? null;
$success = $_SESSION['success'] ?? null;
unset($_SESSION['error']);
unset($_SESSION['success']);

// Handle Delete Request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    if (!Utils::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['error'] = 'Security token invalid. Please try again.';
    } else {
        $parcel_id = $_POST['parcel_id'] ?? null;
        if ($parcel_id) {
            if ($parcel_model->delete($parcel_id)) {
                $_SESSION['success'] = 'Parcel deleted successfully.';
            } else {
                $_SESSION['error'] = 'Failed to delete parcel.';
            }
        }
    }
    Utils::redirect('/routex/admin/parcels');
}

// Fetching parcels
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15;
$offset = ($page - 1) * $limit;
$status_filter = $_GET['status'] ?? null;
$search_query = $_GET['q'] ?? null;

$parcels = $parcel_model->getAll($limit, $offset, $status_filter, $search_query);
$total_parcels = $parcel_model->getCount($status_filter, $search_query);
$total_pages = ceil($total_parcels / $limit);

$csrf_token = Utils::generateCSRFToken();
$page_title = 'All Parcels - Admin';
require_once __DIR__ . '/../../includes/trackheader.php';
?>

<section class="min-h-screen bg-gray-100 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- Header -->
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-8 gap-4">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">All Shipments</h1>
                <p class="text-gray-600">Manage all parcels in the system.</p>
            </div>
            <div class="flex gap-3">
                <a href="/routex/admin/dashboard" class="btn-secondary"><i class="fas fa-arrow-left mr-2"></i>Dashboard</a>
                <a href="/routex/admin/parcel-create" class="btn-primary"><i class="fas fa-plus mr-2"></i>Create Parcel</a>
            </div>
        </div>

        <?php if ($error): ?>
        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6" role="alert">
            <p><?php echo htmlspecialchars($error); ?></p>
        </div>
        <?php endif; ?>
        <?php if ($success): ?>
        <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6" role="alert">
            <p><?php echo htmlspecialchars($success); ?></p>
        </div>
        <?php endif; ?>

        <!-- Filters and Search -->
        <div class="bg-white rounded-xl shadow-md p-4 mb-6">
            <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <input type="text" name="q" placeholder="Search by Tracking ID, Name, Email..." value="<?php echo htmlspecialchars($search_query ?? ''); ?>" class="w-full border rounded-lg px-4 py-2">
                <select name="status" class="w-full border rounded-lg px-4 py-2">
                    <option value="">All Statuses</option>
                    <?php foreach (Utils::getStatusList() as $key => $label): ?>
                        <option value="<?php echo $key; ?>" <?php echo ($status_filter === $key) ? 'selected' : ''; ?>><?php echo $label; ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="btn-primary justify-center">Filter</button>
            </form>
        </div>

        <!-- Parcels Table -->
        <div class="bg-white rounded-xl shadow-md border border-gray-100 overflow-hidden">
            <div class="overflow-x-auto table-container">
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tracking ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Sender</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Receiver</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                            <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        <?php if (empty($parcels)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-10 text-gray-500">No parcels found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($parcels as $parcel): ?>
                            <tr class="hover:bg-gray-50 transition">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <a href="/routex/admin/parcel-edit?id=<?php echo $parcel['id']; ?>" class="font-mono text-sm font-semibold text-blue-600 hover:underline">#<?php echo htmlspecialchars($parcel['tracking_code']); ?></a>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($parcel['sender_name']); ?></div>
                                    <div class="text-xs text-gray-500"><?php echo htmlspecialchars($parcel['sender_city']); ?></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($parcel['receiver_name']); ?></div>
                                    <div class="text-xs text-gray-500"><?php echo htmlspecialchars($parcel['receiver_country']); ?></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo Utils::getStatusColor($parcel['status']); ?>">
                                        <?php echo Utils::getStatusLabel($parcel['status']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    <?php echo Utils::formatDate($parcel['created_at']); ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <div class="flex items-center justify-end">
                                        <a href="/routex/admin/parcel-edit?id=<?php echo $parcel['id']; ?>" class="text-gray-400 hover:text-blue-600 transition" title="Edit">
                                            <i class="fas fa-edit text-lg"></i>
                                        </a>
                                        <form method="POST" onsubmit="return confirm('Are you sure you want to delete this parcel and all its history? This action cannot be undone.');" class="inline-block ml-4">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="parcel_id" value="<?php echo $parcel['id']; ?>">
                                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                            <button type="submit" class="text-gray-400 hover:text-red-600 transition" title="Delete">
                                                <i class="fas fa-trash-alt text-lg"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="mt-6 flex justify-center">
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="?page=<?php echo $i; ?>&status=<?php echo htmlspecialchars($status_filter ?? ''); ?>&q=<?php echo htmlspecialchars($search_query ?? ''); ?>" class="<?php echo ($i == $page) ? 'z-10 bg-blue-50 border-blue-500 text-blue-600' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'; ?> relative inline-flex items-center px-4 py-2 border text-sm font-medium">
                        <?php echo $i; ?>
                    </a>
                <?php endfor; ?>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</section>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>

```

### 2. Update `dashboard.php`

Next, let's add the delete button to your dashboard for consistency. This involves adding the button to the table and the logic to handle the deletion.

```diff
--- a/c/xampp/htdocs/routex/pages/admin/dashboard.php
+++ b/c/xampp/htdocs/routex/pages/admin/dashboard.php
@@ -12,6 +12,27 @@
 $review_model = new Review($pdo);
 $admin_model = new Admin($pdo);
 
+// Handle Delete Request from Dashboard
+if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_parcel') {
+    if (Utils::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
+        $parcel_id = $_POST['parcel_id'] ?? null;
+        if ($parcel_id) {
+            // Assumes delete() method exists in Parcel model
+            if ($parcel_model->delete($parcel_id)) {
+                $_SESSION['success'] = 'Parcel deleted successfully.';
+            } else {
+                $_SESSION['error'] = 'Failed to delete parcel.';
+            }
+        }
+    } else {
+        $_SESSION['error'] = 'Security token invalid.';
+    }
+    Utils::redirect('/routex/admin/dashboard');
+}
+
 $stats = $parcel_model->getStats();
 $current_admin = $admin_model->getCurrentAdmin();
 $recent_parcels = $parcel_model->getAll(5, 0);
+
+$csrf_token = Utils::generateCSRFToken();
+$error = $_SESSION['error'] ?? null;
+$success = $_SESSION['success'] ?? null;
+unset($_SESSION['error']);
+unset($_SESSION['success']);
 ?>
 
 <section class="min-h-screen bg-gray-100 py-8">
@@ -29,6 +50,17 @@
                 </a>
             </div>
         </div>
+
+        <?php if ($error): ?>
+        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6" role="alert">
+            <p><?php echo htmlspecialchars($error); ?></p>
+        </div>
+        <?php endif; ?>
+        <?php if ($success): ?>
+        <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6" role="alert">
+            <p><?php echo htmlspecialchars($success); ?></p>
+        </div>
+        <?php endif; ?>
 
         <!-- Stats Cards -->
         <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
@@ -112,9 +144,19 @@
                                     </span>
                                 </td>
                                 <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
-                                    <a href="/routex/admin/parcel-edit?id=<?php echo $parcel['id']; ?>" class="text-gray-400 hover:text-blue-600 transition">
-                                        <i class="fas fa-edit text-lg"></i>
-                                    </a>
+                                    <div class="flex items-center justify-end">
+                                        <a href="/routex/admin/parcel-edit?id=<?php echo $parcel['id']; ?>" class="text-gray-400 hover:text-blue-600 transition" title="Edit">
+                                            <i class="fas fa-edit text-lg"></i>
+                                        </a>
+                                        <form method="POST" onsubmit="return confirm('Are you sure you want to delete this parcel?');" class="inline-block ml-4">
+                                            <input type="hidden" name="action" value="delete_parcel">
+                                            <input type="hidden" name="parcel_id" value="<?php echo $parcel['id']; ?>">
+                                            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
+                                            <button type="submit" class="text-gray-400 hover:text-red-600 transition" title="Delete">
+                                                <i class="fas fa-trash-alt text-lg"></i>
+                                            </button>
+                                        </form>
+                                    </div>
                                 </td>
                             </tr>
                             <?php endforeach; ?>

```

### 3. Required Model and Utility Methods

For the new page and delete functionality to work, you need to add or update a few methods in your existing classes.

**A. In `app/Models/Parcel.php`:**

You need a `delete()` method and updated `getAll()` and `getCount()` methods to handle filtering and searching. Add the following methods inside your `Parcel` class.

```php
public function delete($id) {
    try {
        $this->pdo->beginTransaction();

        // Delete related updates first to maintain database integrity
        $stmt_updates = $this->pdo->prepare("DELETE FROM parcel_updates WHERE parcel_id = ?");
        $stmt_updates->execute([$id]);

        // Delete the parcel
        $stmt_parcel = $this->pdo->prepare("DELETE FROM parcels WHERE id = ?");
        $stmt_parcel->execute([$id]);

        $this->pdo->commit();
        return true;
    } catch (PDOException $e) {
        $this->pdo->rollBack();
        // Optionally log the error: error_log($e->getMessage());
        return false;
    }
}

public function getAll($limit = 10, $offset = 0, $status = null, $search = null) {
    $sql = "SELECT * FROM parcels";
    $where = [];
    $params = [];

    if ($status) {
        $where[] = "status = ?";
        $params[] = $status;
    }
    if ($search) {
        $where[] = "(tracking_code LIKE ? OR sender_name LIKE ? OR receiver_name LIKE ? OR sender_email LIKE ? OR receiver_email LIKE ?)";
        for ($i=0; $i<5; $i++) {
            $params[] = '%' . $search . '%';
        }
    }

    if (!empty($where)) {
        $sql .= " WHERE " . implode(' AND ', $where);
    }

    $sql .= " ORDER BY created_at DESC LIMIT ? OFFSET ?";
    $params[] = $limit;
    $params[] = $offset;

    $stmt = $this->pdo->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

public function getCount($status = null, $search = null) {
    $sql = "SELECT COUNT(*) FROM parcels";
    $where = [];
    $params = [];

     if ($status) {
        $where[] = "status = ?";
        $params[] = $status;
    }
    if ($search) {
        $where[] = "(tracking_code LIKE ? OR sender_name LIKE ? OR receiver_name LIKE ? OR sender_email LIKE ? OR receiver_email LIKE ?)";
        for ($i=0; $i<5; $i++) {
            $params[] = '%' . $search . '%';
        }
    }

    if (!empty($where)) {
        $sql .= " WHERE " . implode(' AND ', $where);
    }

    $stmt = $this->pdo->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchColumn();
}
```

**B. In `app/Utils.php`:**

The filter dropdown needs a list of all possible statuses. Add this `getStatusList()` static method to your `Utils` class.

```php
public static function getStatusList() {
    return [
        'pending' => 'Pending',
        'in_transit' => 'In Transit',
        'out_for_delivery' => 'Out for Delivery',
        'delivered' => 'Delivered',
        'on_hold' => 'On Hold',
        'returned' => 'Returned',
        'cancelled' => 'Cancelled',
    ];
}
```

After adding these files and methods, your `parcels.php` page will be fully functional, allowing you to delete shipments safely.

<!--
[PROMPT_SUGGESTION]How can I add a "soft delete" feature instead of permanently deleting parcels?[/PROMPT_SUGGESTION]
[PROMPT_SUGGESTION]Add bulk-delete functionality to the parcels page with checkboxes.[/PROMPT_SUGGESTION]
-->
