<?php
$active = 'users';
$pageTitle = 'Users (App Customers)';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

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

$q = trim($_GET['q'] ?? '');
$params = [];
$sql = "SELECT u.*, (SELECT COUNT(*) FROM user_orders WHERE user_id=u.id) order_count FROM users u";
if ($q !== '') {
  $sql .= " WHERE u.name LIKE ? OR u.phone LIKE ? OR u.email LIKE ?";
  $like = "%$q%";
  $params = [$like, $like, $like];
}
$sql .= " ORDER BY u.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0">Users (App Customers)</h4>
    <div class="text-muted small">Registered users from the customer app</div>
  </div>
  <a class="btn btn-dark" href="user_form.php">+ Add User</a>
</div>

<form class="row g-2 mb-3" method="get">
  <div class="col-md-6 col-lg-4">
    <input class="form-control" name="q" placeholder="Search by name, phone, email" value="<?php echo htmlspecialchars($q); ?>">
  </div>
  <div class="col-auto">
    <button class="btn btn-outline-dark" type="submit">Search</button>
  </div>
</form>

<div class="card p-3">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Phone</th>
          <th>Email</th>
          <th>Orders</th>
          <th>Registered</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($users as $u): ?>
        <tr>
          <td class="fw-semibold"><?php echo (int)$u['id']; ?></td>
          <td><?php echo htmlspecialchars($u['name']); ?></td>
          <td><?php echo htmlspecialchars($u['phone']); ?></td>
          <td><?php echo htmlspecialchars($u['email'] ?? '-'); ?></td>
          <td><?php echo (int)($u['order_count'] ?? 0); ?></td>
          <td class="small"><?php echo date('M d, Y', strtotime($u['created_at'])); ?></td>
          <td class="text-end">
            <a class="btn btn-sm btn-outline-dark" href="user_form.php?id=<?php echo (int)$u['id']; ?>">Edit</a>
            <a class="btn btn-sm btn-dark" href="user_orders.php?user_id=<?php echo (int)$u['id']; ?>">Orders</a>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (count($users) === 0): ?>
        <tr><td colspan="7" class="text-muted">No users found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
