<?php require_once '../includes/header.php';

// ---------- Filters & Pagination ----------
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 15;
$offset = ($page - 1) * $perPage;

$statusFilter = $_GET['status'] ?? '';
$search       = trim($_GET['search'] ?? '');
$dateFrom     = $_GET['date_from'] ?? '';
$dateTo       = $_GET['date_to'] ?? '';

$where = "WHERE 1=1";
$params = [];

if ($statusFilter !== '') {
    $where .= " AND o.status = :status";
    $params[':status'] = $statusFilter;
}
if ($search !== '') {
    // Escape special LIKE characters
    $escaped = addcslashes($search, '%_');
    $where .= " AND (o.order_number LIKE :s1 OR o.customer_name LIKE :s2 OR o.customer_phone LIKE :s3)";
    $params[':s1'] = "%$escaped%";
    $params[':s2'] = "%$escaped%";
    $params[':s3'] = "%$escaped%";
}
if ($dateFrom !== '') {
    $where .= " AND DATE(o.created_at) >= :date_from";
    $params[':date_from'] = $dateFrom;
}
if ($dateTo !== '') {
    $where .= " AND DATE(o.created_at) <= :date_to";
    $params[':date_to'] = $dateTo;
}

// Count + total collect (selling + courier fee) for summary
$countStmt = $pdo->prepare("
    SELECT COUNT(*), COALESCE(SUM(o.total_selling + o.courier_fee), 0)
    FROM orders o
    $where
");
$countStmt->execute($params);
$summary = $countStmt->fetch(PDO::FETCH_NUM);
$totalOrders = (int)$summary[0];
$totalCollect = (float)$summary[1];
$totalPages = ceil($totalOrders / $perPage);

// Fetch orders
$orderStmt = $pdo->prepare("
    SELECT o.*, u.reseller_name, u.shop_name
    FROM orders o
    LEFT JOIN users u ON o.user_id = u.id
    $where
    ORDER BY o.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$orderStmt->execute($params);
$orders = $orderStmt->fetchAll();

$statuses = ['pending', 'confirmed', 'packaging', 'shipping', 'delivered', 'partial_delivery', 'returned', 'paid_return', 'cancelled', 'lost'];
?>

<h1 class="h2 mb-4">Orders</h1>

<?php $flash = getFlash(); if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Filter card -->
<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-2">
                <label class="form-label">Search</label>
                <input type="text" name="search" class="form-control" placeholder="Order / Customer / Phone" value="<?= htmlspecialchars($search) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">All</option>
                    <?php foreach ($statuses as $s): ?>
                        <option value="<?= $s ?>" <?= $statusFilter === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Date From</label>
                <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($dateFrom) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Date To</label>
                <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($dateTo) ?>">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">Filter</button>
            </div>
            <div class="col-md-2">
                <a href="orders.php" class="btn btn-outline-secondary w-100">Reset</a>
            </div>
        </form>
    </div>
</div>

<!-- Orders Table -->
<div class="card shadow-sm">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Order #</th>
                        <th>Customer</th>
                        <th>Reseller</th>
                        <th>Collect from Customer</th>   <!-- Updated header -->
                        <th>Status</th>
                        <th>Date</th>
                        <th class="text-end">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($orders)): ?>
                    <tr><td colspan="7" class="text-center py-3">No orders found.</td></tr>
                <?php else: foreach ($orders as $order):
                    // Collect from customer = selling + courier fee
                    $totalCollectRow = (float)$order['total_selling'] + (float)$order['courier_fee'];

                    $statusClass = match($order['status']) {
                        'pending' => 'bg-warning text-dark',
                        'confirmed' => 'bg-info text-dark',
                        'packaging' => 'bg-secondary',
                        'shipping' => 'bg-primary',
                        'delivered' => 'bg-success',
                        'cancelled' => 'bg-danger',
                        'returned' => 'bg-dark',
                        default => 'bg-light text-dark'
                    };
                ?>
                    <tr>
                        <td><a href="order_details.php?id=<?= $order['id'] ?>" class="text-decoration-none fw-bold">#<?= htmlspecialchars($order['order_number']) ?></a></td>
                        <td><?= htmlspecialchars($order['customer_name'] ?? 'N/A') ?><br><small class="text-muted"><?= htmlspecialchars($order['customer_phone'] ?? '') ?></small></td>
                        <td><?= htmlspecialchars($order['reseller_name'] ?? $order['shop_name'] ?? 'N/A') ?></td>
                        <td>৳<?= number_format($totalCollectRow, 2) ?></td>   <!-- Collect amount -->
                        <td><span class="badge <?= $statusClass ?>"><?= htmlspecialchars($order['status']) ?></span></td>
                        <td><?= date('d M Y', strtotime($order['created_at'])) ?></td>
                        <td class="text-end">
                            <a href="order_details.php?id=<?= $order['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye"></i> View</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <!-- Summary row uses total collect -->
                <tr class="table-secondary fw-bold">
                    <td colspan="3" class="text-end">Total (<?= $totalOrders ?> orders):</td>
                    <td>৳<?= number_format($totalCollect, 2) ?></td>
                    <td colspan="3"></td>
                </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Pagination -->
<?php if ($totalPages > 1): ?>
<nav class="mt-4">
    <ul class="pagination justify-content-center">
        <li class="page-item <?= $page == 1 ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page-1 ?>&status=<?= urlencode($statusFilter) ?>&search=<?= urlencode($search) ?>&date_from=<?= urlencode($dateFrom) ?>&date_to=<?= urlencode($dateTo) ?>">&laquo;</a>
        </li>
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                <a class="page-link" href="?page=<?= $i ?>&status=<?= urlencode($statusFilter) ?>&search=<?= urlencode($search) ?>&date_from=<?= urlencode($dateFrom) ?>&date_to=<?= urlencode($dateTo) ?>"><?= $i ?></a>
            </li>
        <?php endfor; ?>
        <li class="page-item <?= $page == $totalPages ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page+1 ?>&status=<?= urlencode($statusFilter) ?>&search=<?= urlencode($search) ?>&date_from=<?= urlencode($dateFrom) ?>&date_to=<?= urlencode($dateTo) ?>">&raquo;</a>
        </li>
    </ul>
</nav>
<?php endif; ?>

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