<?php
$pageTitle = 'Data Admin';
require_once __DIR__ . '/includes/header.php';

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        if ($id === (int) $_SESSION['user_id']) {
            flash('error', 'Tidak dapat menghapus akun yang sedang login.');
        } else {
            $stmt = $db->prepare('DELETE FROM users WHERE id = ?');
            $stmt->execute([$id]);
            flash('success', 'User berhasil dihapus.');
        }
        header('Location: users.php');
        exit;
    }

    $nama = trim($_POST['nama'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $role = trim($_POST['role'] ?? 'Admin');
    $password = $_POST['password'] ?? '';

    if ($nama === '' || $username === '') {
        flash('error', 'Nama dan username wajib diisi.');
    } else {
        if ($action === 'create') {
            if ($password === '') {
                flash('error', 'Password wajib diisi untuk user baru.');
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $db->prepare('INSERT INTO users (username, password, nama, role) VALUES (?, ?, ?, ?)');
                try {
                    $stmt->execute([$username, $hash, $nama, $role]);
                    flash('success', 'Admin berhasil ditambahkan.');
                } catch (PDOException $e) {
                    flash('error', 'Username sudah digunakan.');
                }
            }
        } elseif ($action === 'update') {
            $id = (int) ($_POST['id'] ?? 0);
            if ($password !== '') {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $db->prepare('UPDATE users SET username=?, password=?, nama=?, role=? WHERE id=?');
                $stmt->execute([$username, $hash, $nama, $role, $id]);
            } else {
                $stmt = $db->prepare('UPDATE users SET username=?, nama=?, role=? WHERE id=?');
                $stmt->execute([$username, $nama, $role, $id]);
            }
            flash('success', 'Admin berhasil diperbarui.');
        }
        header('Location: users.php');
        exit;
    }
}

$search = trim($_GET['q'] ?? '');
$sql = 'SELECT * FROM users';
$params = [];
if ($search !== '') {
    $sql .= ' WHERE nama LIKE ? OR username LIKE ? OR role LIKE ?';
    $term = '%' . $search . '%';
    $params = [$term, $term, $term];
}
$sql .= ' ORDER BY created_at DESC';
$stmt = $db->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();

$success = flash('success');
$error = flash('error');
?>

<div class="page-header">
  <h1>Data Admin</h1>
  <p class="breadcrumb"><a href="dashboard.php">Dashboard</a> / Admin</p>
</div>
<div class="page-body">
  <?php if ($success): ?><div class="alert alert-success"><?= e($success) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endif; ?>

  <div class="rules-box">
    <strong>Aturan</strong>
    Anda memiliki akses untuk melihat, mencari, mengubah, serta menghapus data admin.
  </div>

  <div class="card">
    <div class="card-header">
      <h2>Daftar Admin</h2>
      <button type="button" class="btn btn-success" data-modal-open="modalUser" onclick="resetUserForm()">
        <i class="fas fa-plus"></i> Tambah Admin
      </button>
    </div>
    <div class="card-body">
      <form method="get" action="users.php" class="toolbar" id="formSearchUser" data-skip-validation>
        <div class="search-box">
          <i class="fas fa-search"></i>
          <input type="text" name="q" id="searchUserInput"
                 placeholder="Cari Admin..." value="<?= e($search) ?>"
                 data-table-search="tableUser" autocomplete="off">
        </div>
      </form>
      <div class="table-responsive">
        <table class="data-table" id="tableUser">
          <thead>
            <tr>
              <th>No</th>
              <th>Profil</th>
              <th>Nama</th>
              <th>Username</th>
              <th>Sebagai</th>
              <th>Tanggal Daftar</th>
              <th>Status</th>
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($users as $i => $u): ?>
            <tr>
              <td><?= $i + 1 ?></td>
              <td><span class="avatar"><?= strtoupper(mb_substr($u['nama'], 0, 1)) ?></span></td>
              <td><?= e($u['nama']) ?></td>
              <td><?= e($u['username']) ?></td>
              <td><?= e($u['role']) ?></td>
              <td><?= date('d M Y', strtotime($u['created_at'])) ?></td>
              <td><span class="badge badge-aktif">Aktif</span></td>
              <td>
                <div class="action-btns">
                  <button type="button" class="btn-icon" title="Edit"
                    onclick='editUser(<?= json_encode($u, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                    <i class="fas fa-edit"></i>
                  </button>
                  <?php if ((int)$u['id'] !== (int)$_SESSION['user_id']): ?>
                  <form method="post" style="display:inline" data-confirm-delete data-confirm-title="Hapus Data Admin?" data-confirm-text="Data yang dihapus tidak dapat dikembalikan.">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= $u['id'] ?>">
                    <button type="submit" class="btn-icon delete" title="Hapus"><i class="fas fa-trash"></i></button>
                  </form>
                  <?php endif; ?>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($users)): ?>
            <tr id="rowEmptyUser">
              <td colspan="8" style="text-align:center;color:var(--text-muted)">
                <?= $search !== '' ? 'Admin tidak ditemukan.' : 'Belum ada data admin.' ?>
              </td>
            </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<div class="modal-overlay" id="modalUser">
  <div class="modal">
    <div class="modal-header">
      <h3 id="modalUserTitle">Tambah Admin</h3>
      <button type="button" class="modal-close" data-modal-close>&times;</button>
    </div>
    <form method="post" id="formUser" novalidate>
      <input type="hidden" name="action" id="userAction" value="create">
      <input type="hidden" name="id" id="userId" value="">
      <div class="modal-body">
        <div class="form-group">
          <label>Nama</label>
          <input type="text" name="nama" id="userNama" class="form-control" required>
        </div>
        <div class="form-group">
          <label>Username</label>
          <input type="text" name="username" id="userUsername" class="form-control" required>
        </div>
        <div class="form-group">
          <label>Role</label>
          <select name="role" id="userRole" class="form-control">
            <option value="Admin">Admin</option>
          </select>
        </div>
        <div class="form-group">
          <label>Password <small id="passHint">(wajib untuk user baru)</small></label>
          <input type="password" name="password" id="userPassword" class="form-control">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" data-modal-close>Batal</button>
        <button type="submit" class="btn btn-success">Simpan</button>
      </div>
    </form>
  </div>
</div>

<script>
(function () {
  var input = document.getElementById('searchUserInput');
  var table = document.getElementById('tableUser');
  if (!input || !table) return;

  input.addEventListener('input', function () {
    var q = this.value.toLowerCase().trim();
    var rows = table.querySelectorAll('tbody tr:not(#rowEmptyUser)');
    rows.forEach(function (row) {
      var match = row.textContent.toLowerCase().includes(q);
      row.style.display = match ? 'table-row' : 'none';
    });
  });
})();

function resetUserForm() {
  document.getElementById('modalUserTitle').textContent = 'Tambah Admin';
  document.getElementById('userAction').value = 'create';
  document.getElementById('userId').value = '';
  document.getElementById('formUser').reset();
  document.getElementById('userPassword').required = true;
  document.getElementById('passHint').textContent = '(wajib untuk user baru)';
  document.querySelectorAll('#formUser .form-validation-alert').forEach(function (el) { el.remove(); });
  document.querySelectorAll('#formUser .is-invalid').forEach(function (el) { el.classList.remove('is-invalid'); });
}
function editUser(u) {
  document.getElementById('modalUserTitle').textContent = 'Edit Admin';
  document.getElementById('userAction').value = 'update';
  document.getElementById('userId').value = u.id;
  document.getElementById('userNama').value = u.nama;
  document.getElementById('userUsername').value = u.username;
  document.getElementById('userRole').value = u.role;
  document.getElementById('userPassword').value = '';
  document.getElementById('userPassword').required = false;
  document.getElementById('passHint').textContent = '(kosongkan jika tidak diubah)';
  openModal('modalUser');
}
</script>

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