<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../core/helpers.php';
requireRole('admin');

$pageTitle  = 'Manajemen User';
$activePage = 'users';

$search = sanitize($_GET['q'] ?? '');
$role   = sanitize($_GET['role'] ?? '');
$page   = max(1, (int)($_GET['page'] ?? 1));
$perPage = 15;

$where  = ['1=1'];
$params = [];
if ($search) { $where[] = '(u.nama LIKE ? OR u.username LIKE ? OR u.email LIKE ?)'; $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($role)   { $where[] = 'u.role = ?'; $params[] = $role; }

$whereStr = implode(' AND ', $where);
$sql = "SELECT u.*, s.nama_sekolah FROM users u LEFT JOIN sekolah s ON s.id=u.sekolah_id WHERE {$whereStr} ORDER BY u.created_at DESC";
$pag = paginate($sql, $params, $perPage, $page);
$baseUrl = BASE_URL . '/modules/users/index.php?q=' . urlencode($search) . '&role=' . urlencode($role);

require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-people-fill me-2 text-primary"></i>Manajemen User</h1>
    <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li><li class="breadcrumb-item active">Users</li></ol></nav>
  </div>
  <a href="form.php" class="btn btn-primary"><i class="bi bi-person-plus me-1"></i>Tambah User</a>
</div>

<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" class="row g-2 align-items-end">
      <div class="col-sm-6"><input type="text" name="q" class="form-control form-control-sm" placeholder="Cari nama, username, email…" value="<?= e($search) ?>"></div>
      <div class="col-sm-3">
        <select name="role" class="form-select form-select-sm">
          <option value="">Semua Role</option>
          <option value="admin"   <?= $role==='admin'?'selected':'' ?>>Administrator</option>
          <option value="dinas"   <?= $role==='dinas'?'selected':'' ?>>Dinas Pendidikan</option>
          <option value="sekolah" <?= $role==='sekolah'?'selected':'' ?>>Sekolah</option>
        </select>
      </div>
      <div class="col-auto d-flex gap-2">
        <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search"></i></button>
        <a href="index.php" class="btn btn-outline-secondary btn-sm">Reset</a>
      </div>
    </form>
  </div>
</div>

<div class="card">
  <div class="card-header">
    <span class="card-header-title"><i class="bi bi-person-badge me-2"></i>Daftar Pengguna</span>
    <span class="badge bg-primary-subtle text-primary"><?= $pag['total'] ?> user</span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr><th>#</th><th>Nama</th><th>Username</th><th>Email</th><th>Role</th><th>Sekolah</th><th>Status</th><th>Login Terakhir</th><th>Aksi</th></tr>
      </thead>
      <tbody>
        <?php if(empty($pag['data'])): ?>
        <tr><td colspan="9" class="text-center py-4 text-muted">Tidak ada pengguna</td></tr>
        <?php else: ?>
        <?php $no=($pag['current']-1)*$pag['per_page']+1; ?>
        <?php foreach($pag['data'] as $row): ?>
        <tr>
          <td class="text-muted"><?= $no++ ?></td>
          <td class="fw-600"><?= e($row['nama']) ?></td>
          <td><code><?= e($row['username']) ?></code></td>
          <td><?= e($row['email']) ?></td>
          <td>
            <?php $roleClass=['admin'=>'badge-role-admin','dinas'=>'badge-role-dinas','sekolah'=>'badge-role-sekolah']; ?>
            <span class="badge <?= $roleClass[$row['role']] ?? '' ?>"><?= ucfirst($row['role']) ?></span>
          </td>
          <td><?= $row['nama_sekolah'] ? e(mb_strimwidth($row['nama_sekolah'],0,30,'…')) : '<span class="text-muted">—</span>' ?></td>
          <td>
            <?php if($row['aktif']): ?>
            <span class="badge bg-success-subtle text-success">Aktif</span>
            <?php else: ?>
            <span class="badge bg-secondary-subtle text-secondary">Nonaktif</span>
            <?php endif; ?>
          </td>
          <td style="font-size:.78rem;white-space:nowrap"><?= $row['last_login'] ? formatTanggal($row['last_login'],'d M Y H:i') : '<span class="text-muted">Belum pernah</span>' ?></td>
          <td>
            <div class="d-flex gap-1">
              <a href="form.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-warning" title="Edit"><i class="bi bi-pencil"></i></a>
              <?php if($row['id'] != $_SESSION['user_id']): ?>
              <a href="delete.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-outline-danger"
                 data-confirm="Hapus user <?= e($row['nama']) ?>?" title="Hapus"><i class="bi bi-trash"></i></a>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
  <?php if($pag['pages']>1): ?>
  <div class="card-footer d-flex justify-content-between align-items-center flex-wrap gap-2">
    <span class="text-muted small">Menampilkan <?= count($pag['data']) ?> dari <?= $pag['total'] ?> data</span>
    <?= renderPagination($pag,$baseUrl) ?>
  </div>
  <?php endif; ?>
</div>

<?php require_once ROOT_PATH . '/views/layouts/footer.php'; ?>
