<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$role = isset($_GET['role']) ? trim($_GET['role']) : '';
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

$where = [];
$params = [];

if ($status !== '') {
    $where[] = 'u.status = ?';
    $params[] = $status;
}
if ($role !== '') {
    $where[] = 'ur.role = ?';
    $params[] = $role;
}
if ($q !== '') {
    $where[] = '(u.username LIKE ? OR u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)';
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$users = $db->getAll(
    "SELECT u.*, ur.role, ur.assigned_at
     FROM users u
     LEFT JOIN user_roles ur ON u.id = ur.user_id
     $whereSql
     ORDER BY u.created_at DESC
     LIMIT 200",
    $params
);

$pageTitle = 'Users';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Users</h1>
    <p class="text-muted mb-0">Manage user accounts and roles</p>
  </div>
  <div>
    <a href="users_edit.php" class="btn btn-primary">
      <i class="fas fa-plus me-2"></i>Add User
    </a>
  </div>
</div>

<div class="card mb-4">
  <div class="card-header">
    <form method="get" class="row g-3">
      <div class="col-sm-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">All</option>
          <?php foreach (['active','inactive','suspended','pending'] as $opt): ?>
            <option value="<?php echo $opt; ?>" <?php echo $status===$opt?'selected':''; ?>><?php echo ucfirst($opt); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Role</label>
        <select name="role" class="form-select">
          <option value="">All</option>
          <?php foreach (['super_admin','admin','regional_admin','instructor','student'] as $opt): ?>
            <option value="<?php echo $opt; ?>" <?php echo $role===$opt?'selected':''; ?>><?php echo ucwords(str_replace('_',' ',$opt)); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-4">
        <label class="form-label">Search</label>
        <input type="text" name="q" class="form-control" placeholder="username, email, name" value="<?php echo htmlspecialchars($q); ?>">
      </div>
      <div class="col-sm-2 align-self-end">
        <button class="btn btn-primary w-100" type="submit">Filter</button>
      </div>
    </form>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover mb-0">
        <thead>
          <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Name</th>
            <th>Role</th>
            <th>Region</th>
            <th>Status</th>
            <th>Created</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$users): ?>
            <tr><td colspan="9" class="text-center text-muted py-4">No users found.</td></tr>
          <?php else: foreach ($users as $u): ?>
            <tr>
              <td><?php echo (int)$u['id']; ?></td>
              <td><?php echo htmlspecialchars($u['username']); ?></td>
              <td><?php echo htmlspecialchars($u['email']); ?></td>
              <td><?php echo htmlspecialchars(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? '')); ?></td>
              <td>
                <span class="badge bg-<?php echo $u['role']==='super_admin'?'danger':($u['role']==='admin'?'warning':'secondary'); ?>">
                  <?php echo htmlspecialchars(ucwords(str_replace('_',' ',$u['role'] ?? ''))); ?>
                </span>
              </td>
              <td><?php echo htmlspecialchars($u['region'] ?? ''); ?></td>
              <td>
                <span class="badge bg-<?php echo $u['status']==='active'?'success':($u['status']==='suspended'?'danger':'secondary'); ?>">
                  <?php echo htmlspecialchars(ucfirst($u['status'] ?? '')); ?>
                </span>
              </td>
              <td><?php echo htmlspecialchars($u['created_at'] ?? ''); ?></td>
              <td class="text-nowrap">
                <a href="users_edit.php?id=<?php echo (int)$u['id']; ?>" class="btn btn-sm btn-outline-primary me-1">
                  <i class="fas fa-edit"></i>
                </a>
                <a href="users_view.php?id=<?php echo (int)$u['id']; ?>" class="btn btn-sm btn-outline-secondary me-1">
                  <i class="fas fa-eye"></i>
                </a>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
