<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_login();
$db = get_db();

// add admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    if ($username && $password) {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $db->prepare('INSERT INTO admins (username,password) VALUES (:u,:p)');
        try {
            $stmt->execute([':u'=>$username,':p'=>$hash]);
            flash_set('success','User admin ditambahkan');
        } catch (Exception $e) {
            flash_set('error','Gagal: '.$e->getMessage());
        }
    } else {
        flash_set('error','Username & password wajib diisi');
    }
    header('Location: users.php');
    exit;
}

// delete admin
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    // prevent deleting self
    if ($id == ($_SESSION['admin_id'] ?? 0)) {
        flash_set('error','Tidak bisa menghapus user yang sedang login');
    } else {
        $stmt = $db->prepare('DELETE FROM admins WHERE id = :id');
        $stmt->execute([':id'=>$id]);
        flash_set('success','User dihapus');
    }
    header('Location: users.php');
    exit;
}

$admins = $db->query('SELECT id,username FROM admins ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);

require __DIR__ . '/_header.php';
?>

<h1>Manajemen Users Admin</h1>
<?php if ($m = flash_get('success')): ?><div class="alert alert-success"><?php echo e($m); ?></div><?php endif; ?>
<?php if ($m = flash_get('error')): ?><div class="alert alert-danger"><?php echo e($m); ?></div><?php endif; ?>

<h4>Tambah Admin</h4>
<form method="post" class="form-inline mb-3">
  <input type="hidden" name="action" value="add">
  <div class="form-group mr-2"><input name="username" placeholder="username" class="form-control"></div>
  <div class="form-group mr-2"><input name="password" type="password" placeholder="password" class="form-control"></div>
  <button class="btn btn-primary">Tambah</button>
</form>

<table class="table table-striped">
  <thead><tr><th>ID</th><th>Username</th><th>Aksi</th></tr></thead>
  <tbody>
    <?php foreach ($admins as $a): ?>
      <tr>
        <td><?php echo e($a['id']); ?></td>
        <td><?php echo e($a['username']); ?></td>
        <td>
          <?php if ($a['username'] !== ($_SESSION['admin_user'] ?? '')): ?>
            <a class="btn btn-sm btn-danger" href="users.php?delete=<?php echo e($a['id']); ?>" onclick="return confirm('Hapus user?')">Hapus</a>
          <?php else: ?>
            <em>Current</em>
          <?php endif; ?>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<?php
require __DIR__ . '/_footer.php';
?>
