<?php
session_start();
$page_title = 'All Orders';
$active_nav = 'orders';
include("includes/header.php");

// ── Filters ──────────────────────────────────────────────────────────────
$statuses = ['all','pending','confirmed','preparing','ready','completed','cancelled'];
$status   = in_array($_GET['status'] ?? 'all', $statuses, true) ? ($_GET['status'] ?? 'all') : 'all';
$rest_id  = (int)($_GET['restaurant'] ?? 0);
$q        = trim($_GET['q'] ?? '');

$where  = [];
$params = [];
$types  = '';
if ($status !== 'all') { $where[] = "o.order_status = ?"; $params[] = $status; $types .= 's'; }
if ($rest_id > 0)      { $where[] = "o.restaurant_id = ?"; $params[] = $rest_id; $types .= 'i'; }
if ($q !== '') {
    $where[] = "(u.name LIKE CONCAT('%',?,'%') OR u.email LIKE CONCAT('%',?,'%') OR o.payment_reference LIKE CONCAT('%',?,'%'))";
    array_push($params, $q, $q, $q); $types .= 'sss';
}
$where_sql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// ── Pagination ───────────────────────────────────────────────────────────
$per  = 25;
$page = max(1, (int)($_GET['page'] ?? 1));
$off  = ($page - 1) * $per;

$cnt_stmt = $conn->prepare("SELECT COUNT(*) FROM orders o LEFT JOIN users u ON o.user_id=u.id $where_sql");
if ($types) $cnt_stmt->bind_param($types, ...$params);
$cnt_stmt->execute();
$total = (int)$cnt_stmt->get_result()->fetch_row()[0];
$pages = max(1, (int)ceil($total / $per));

$sql = "SELECT o.id, o.total_amount, o.payment_method, o.payment_status, o.order_status,
               o.payment_reference, o.created_at, o.table_number,
               u.name AS customer_name, u.email AS customer_email,
               r.name AS restaurant_name
        FROM orders o
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN restaurants r ON o.restaurant_id = r.id
        $where_sql
        ORDER BY o.created_at DESC
        LIMIT $per OFFSET $off";
$stmt = $conn->prepare($sql);
if ($types) $stmt->bind_param($types, ...$params);
$stmt->execute();
$orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Status counts for the filter pills
$counts = ['all' => 0];
$cr = $conn->query("SELECT order_status s, COUNT(*) c FROM orders GROUP BY order_status");
while ($row = $cr->fetch_assoc()) { $counts[$row['s']] = (int)$row['c']; $counts['all'] += (int)$row['c']; }

// Restaurants for the dropdown
$rests = $conn->query("SELECT id, name FROM restaurants ORDER BY name")->fetch_all(MYSQLI_ASSOC);

$badge = [
    'pending'   => 'badge-warning', 'confirmed' => 'badge-primary',
    'preparing' => 'badge-primary', 'ready'     => 'badge-success',
    'completed' => 'badge-success', 'cancelled' => 'badge-error',
];
function qs(array $overrides): string {
    return '?' . http_build_query(array_merge($_GET, $overrides));
}
?>

<div class="anim-up">

<!-- Header -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em">All Orders</h2>
    <p style="font-size:.84rem;color:var(--text-muted);margin-top:4px"><?php echo number_format($total); ?> order<?php echo $total !== 1 ? 's' : ''; ?> across the platform</p>
  </div>
</div>

<!-- Status pills -->
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px">
  <?php foreach ($statuses as $s): ?>
  <a href="<?php echo htmlspecialchars(qs(['status' => $s, 'page' => 1])); ?>"
     class="btn <?php echo $status === $s ? 'btn-primary' : 'btn-secondary'; ?> btn-sm">
    <?php echo ucfirst($s); ?> (<?php echo number_format($counts[$s] ?? 0); ?>)
  </a>
  <?php endforeach; ?>
</div>

<!-- Filters -->
<div class="card" style="padding:14px 18px;margin-bottom:16px">
  <form method="GET" style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
    <input type="hidden" name="status" value="<?php echo htmlspecialchars($status); ?>">
    <div style="flex:1;min-width:200px">
      <input type="text" name="q" value="<?php echo htmlspecialchars($q); ?>" placeholder="Search customer, email, reference…" class="form-control">
    </div>
    <select name="restaurant" class="form-control" style="width:auto;min-width:160px">
      <option value="0">All Restaurants</option>
      <?php foreach ($rests as $r): ?>
      <option value="<?php echo (int)$r['id']; ?>" <?php echo $rest_id === (int)$r['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($r['name']); ?></option>
      <?php endforeach; ?>
    </select>
    <button type="submit" class="btn btn-secondary btn-md">Filter</button>
    <?php if ($q !== '' || $rest_id > 0 || $status !== 'all'): ?>
    <a href="orders.php" class="btn btn-secondary btn-md">Clear</a>
    <?php endif; ?>
  </form>
</div>

<!-- Orders table -->
<div class="card">
  <?php if (!$orders): ?>
    <div style="padding:48px;text-align:center;color:var(--text-muted);font-size:.85rem">No orders match these filters.</div>
  <?php else: ?>
  <div style="overflow-x:auto">
  <table class="data-table">
    <thead>
      <tr><th>Order</th><th>Customer</th><th>Restaurant</th><th>Amount</th><th>Payment</th><th>Status</th><th>Date</th></tr>
    </thead>
    <tbody>
    <?php foreach ($orders as $o): ?>
      <tr>
        <td>
          <div style="font-weight:700;font-size:.85rem">#<?php echo str_pad((string)$o['id'], 4, '0', STR_PAD_LEFT); ?></div>
          <?php if ($o['table_number']): ?><div style="font-size:.72rem;color:var(--text-muted)">Table <?php echo htmlspecialchars($o['table_number']); ?></div><?php endif; ?>
        </td>
        <td>
          <div style="font-weight:600;font-size:.83rem"><?php echo htmlspecialchars($o['customer_name'] ?? '—'); ?></div>
          <div style="font-size:.72rem;color:var(--text-muted)"><?php echo htmlspecialchars($o['customer_email'] ?? ''); ?></div>
        </td>
        <td style="font-size:.83rem"><?php echo htmlspecialchars($o['restaurant_name'] ?? '—'); ?></td>
        <td style="font-weight:700;font-size:.84rem">₦<?php echo number_format((float)$o['total_amount'], 2); ?></td>
        <td>
          <span class="badge <?php echo $o['payment_status'] === 'paid' ? 'badge-success' : ($o['payment_status'] === 'failed' ? 'badge-error' : 'badge-warning'); ?>">
            <?php echo ucfirst($o['payment_status']); ?>
          </span>
          <div style="font-size:.7rem;color:var(--text-muted);margin-top:3px"><?php echo ucfirst($o['payment_method']); ?></div>
        </td>
        <td><span class="badge <?php echo $badge[$o['order_status']] ?? 'badge-muted'; ?>"><?php echo ucfirst($o['order_status']); ?></span></td>
        <td style="font-size:.78rem;color:var(--text-muted);white-space:nowrap"><?php echo date('M j, Y g:ia', strtotime($o['created_at'])); ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  </div>
  <?php endif; ?>

  <?php if ($pages > 1): ?>
  <div style="padding:14px 18px;border-top:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px">
    <span style="font-size:.78rem;color:var(--text-muted)">Page <?php echo $page; ?> of <?php echo $pages; ?></span>
    <div style="display:flex;gap:6px">
      <?php if ($page > 1): ?><a href="<?php echo htmlspecialchars(qs(['page' => $page - 1])); ?>" class="btn btn-secondary btn-sm">← Prev</a><?php endif; ?>
      <?php if ($page < $pages): ?><a href="<?php echo htmlspecialchars(qs(['page' => $page + 1])); ?>" class="btn btn-secondary btn-sm">Next →</a><?php endif; ?>
    </div>
  </div>
  <?php endif; ?>
</div>

</div>

<?php include("includes/footer.php"); ?>
