<?php
// public/users/index.php
declare(strict_types=1);
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../includes/layout.php';
require_once __DIR__.'/../../includes/flash.php';
require_role('admin');

global $pdo;

// Search & pagination
$q = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;

$params = [];
$where = "";
if ($q !== '') {
  $where = "WHERE (name LIKE :q OR email LIKE :q OR role LIKE :q)";
  $params[':q'] = "%$q%";
}

// Count
$sqlCount = "SELECT COUNT(*) AS c FROM users $where";
$stmt = $pdo->prepare($sqlCount);
$stmt->execute($params);
$total = (int)$stmt->fetch()['c'];

// Data
$sql = "SELECT id, name, email, role, status, created_at
        FROM users $where
        ORDER BY id DESC
        LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

$pages = max(1, (int)ceil($total / $perPage));

render_header('Users', 'users');
$flash = get_flash();
if ($flash): ?>
  <div class="alert alert-<?= htmlspecialchars($flash['type']) ?>"><?= htmlspecialchars($flash['message']) ?></div>
<?php endif; ?>

<div class="card">
  <div class="card-header d-flex align-items-center">
    <form class="form-inline ml-auto" method="get">
      <div class="input-group">
        <input type="text" class="form-control" name="q" placeholder="Search name/email/role" value="<?= htmlspecialchars($q) ?>">
        <div class="input-group-append">
          <button class="btn btn-outline-secondary" type="submit"><i class="fas fa-search"></i></button>
        </div>
      </div>
    </form>
    <!--<a href="create.php" class="btn btn-primary ml-2"><i class="fas fa-plus"></i> Add User</a> -->
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped mb-0">
        <thead>
          <tr>
            <th style="width:70px;">ID</th>
            <th>Name</th>
            <th>Email</th>
            <th style="width:140px;">Role</th>
            <th style="width:110px;">Status</th>
            <th style="width:180px;">Created</th>
            <th style="width:160px;">Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="7" class="text-center text-muted p-4">No users found.</td></tr>
          <?php else: foreach ($rows as $r): ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td><?= htmlspecialchars($r['name']) ?></td>
              <td><?= htmlspecialchars($r['email']) ?></td>
              <td><span class="badge badge-info text-uppercase"><?= htmlspecialchars($r['role']) ?></span></td>
              <td>
                <?php if ($r['status']==='active'): ?>
                  <span class="badge badge-success">Active</span>
                <?php else: ?>
                  <span class="badge badge-secondary">Inactive</span>
                <?php endif; ?>
              </td>
              <td><?= htmlspecialchars($r['created_at']) ?></td>
              <td class="data-actions">
                <a class="btn btn-sm btn-outline-primary" href="edit.php?id=<?= (int)$r['id'] ?>"><i class="fas fa-edit"></i> Edit</a>
                <form method="post" action="delete.php" class="d-inline" onsubmit="return confirm('Delete this user?');">
                  <?= csrf_field(); ?>
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i> Delete</button>
                </form>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php if ($pages > 1): ?>
  <div class="card-footer">
    <nav>
      <ul class="pagination mb-0">
        <?php for ($i=1; $i <= $pages; $i++): ?>
          <li class="page-item <?= $i===$page?'active':'' ?>">
            <a class="page-link" href="?<?= http_build_query(['q'=>$q,'page'=>$i]) ?>"><?= $i ?></a>
          </li>
        <?php endfor; ?>
      </ul>
    </nav>
  </div>
  <?php endif; ?>
</div>

<?php render_footer();
