<?php
$active = 'user_orders';
$pageTitle = 'User Orders';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

try { $pdo->query("SELECT 1 FROM user_orders LIMIT 1"); } catch (Exception $e) {
  echo "<div class='alert alert-warning'>User tables not found. Run database/user_tables.sql first.</div>";
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$userId = (int)($_GET['user_id'] ?? 0);
$status = trim($_GET['status'] ?? '');
$q = trim($_GET['q'] ?? '');

$params = [];
$sql = "
  SELECT o.*, u.name user_name, u.phone user_phone, u.email user_email
  FROM user_orders o
  JOIN users u ON u.id=o.user_id
  WHERE 1=1
";
if ($userId) { $sql .= " AND o.user_id=?"; $params[] = $userId; }
if ($status !== '') { $sql .= " AND o.status=?"; $params[] = $status; }
if ($q !== '') { $sql .= " AND (o.order_number LIKE ? OR u.name LIKE ? OR u.phone LIKE ?)"; $like = "%$q%"; $params = array_merge($params, [$like, $like, $like]); }
$sql .= " ORDER BY o.created_at DESC LIMIT 200";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll();

function orderStatusBadge($s) {
  $map = ['pending'=>'warning','confirmed'=>'info','in_progress'=>'primary','completed'=>'success','cancelled'=>'danger'];
  return '<span class="badge bg-' . ($map[$s] ?? 'secondary') . '">' . htmlspecialchars($s) . '</span>';
}
function paymentBadge($s) {
  $map = ['pending'=>'warning','paid'=>'success','refunded'=>'secondary'];
  return '<span class="badge bg-' . ($map[$s] ?? 'secondary') . '">' . htmlspecialchars($s) . '</span>';
}
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0">User Orders</h4>
    <div class="text-muted small">Orders placed via customer app</div>
  </div>
</div>

<form class="row g-2 mb-3" method="get">
  <?php if ($userId): ?><input type="hidden" name="user_id" value="<?php echo $userId; ?>"><?php endif; ?>
  <div class="col-md-3">
    <input class="form-control" name="q" placeholder="Order #, name, phone" value="<?php echo htmlspecialchars($q); ?>">
  </div>
  <div class="col-md-2">
    <select class="form-select" name="status">
      <option value="">All statuses</option>
      <option value="pending" <?php echo $status==='pending'?'selected':''; ?>>Pending</option>
      <option value="confirmed" <?php echo $status==='confirmed'?'selected':''; ?>>Confirmed</option>
      <option value="in_progress" <?php echo $status==='in_progress'?'selected':''; ?>>In Progress</option>
      <option value="completed" <?php echo $status==='completed'?'selected':''; ?>>Completed</option>
      <option value="cancelled" <?php echo $status==='cancelled'?'selected':''; ?>>Cancelled</option>
    </select>
  </div>
  <div class="col-auto">
    <button class="btn btn-outline-dark" type="submit">Filter</button>
  </div>
</form>

<div class="card p-3">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th>Order #</th>
          <th>Customer</th>
          <th>Status</th>
          <th>Payment</th>
          <th>Mode</th>
          <th>Total</th>
          <th>Date</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($orders as $o): ?>
        <tr>
          <td class="fw-semibold"><?php echo htmlspecialchars($o['order_number']); ?></td>
          <td>
            <?php echo htmlspecialchars($o['user_name']); ?>
            <div class="small text-muted"><?php echo htmlspecialchars($o['user_phone']); ?></div>
          </td>
          <td><?php echo orderStatusBadge($o['status']); ?></td>
          <td><?php echo paymentBadge($o['payment_status']); ?></td>
          <td><span class="badge bg-secondary"><?php echo htmlspecialchars($o['payment_mode'] ?? 'online'); ?></span></td>
          <td>₹<?php echo number_format($o['total_amount']); ?></td>
          <td class="small"><?php echo date('M d, H:i', strtotime($o['created_at'])); ?></td>
          <td class="text-end">
            <a class="btn btn-sm btn-dark" href="user_order_view.php?id=<?php echo (int)$o['id']; ?>">View</a>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (count($orders) === 0): ?>
        <tr><td colspan="8" class="text-muted">No orders found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
