<?php
require_once __DIR__ . '/_db.php';

$pdo = db();
$msg = $error = '';
$me  = (int)$_SESSION['admin_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    // Criar novo admin
    if (($_POST['action'] ?? '') === 'create') {
        $name  = trim($_POST['name']  ?? '');
        $email = trim($_POST['email'] ?? '');
        $pass  = $_POST['pass'] ?? '';
        if (!$name || !$email || !$pass) {
            $error = 'Preencha todos os campos.';
        } elseif (strlen($pass) < 8) {
            $error = 'Senha mínima de 8 caracteres.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'E-mail inválido.';
        } else {
            $dup = $pdo->prepare("SELECT id FROM admins WHERE email=?");
            $dup->execute([$email]);
            if ($dup->fetch()) {
                $error = 'E-mail já cadastrado.';
            } else {
                $pdo->prepare("INSERT INTO admins (name,email,password_hash) VALUES (?,?,?)")
                    ->execute([$name, $email, password_hash($pass, PASSWORD_DEFAULT)]);
                $msg = 'Admin criado com sucesso.';
            }
        }
    }

    // Alterar senha — exige senha atual para qualquer alteração
    if (($_POST['action'] ?? '') === 'change_pass') {
        $aid       = (int)$_POST['admin_id'];
        $cur_pass  = $_POST['current_pass'] ?? '';
        $new_pass  = $_POST['new_pass'] ?? '';

        // Busca o admin logado para verificar a senha atual
        $me_row = $pdo->prepare("SELECT password_hash FROM admins WHERE id=?");
        $me_row->execute([$me]);
        $me_row = $me_row->fetch();

        if (!$me_row || !password_verify($cur_pass, $me_row['password_hash'])) {
            $error = 'Senha atual incorreta.';
        } elseif (strlen($new_pass) < 8) {
            $error = 'Nova senha mínima de 8 caracteres.';
        } else {
            $pdo->prepare("UPDATE admins SET password_hash=? WHERE id=?")
                ->execute([password_hash($new_pass, PASSWORD_DEFAULT), $aid]);
            $msg = 'Senha alterada com sucesso.';
        }
    }
}

// Deletar admin — via POST com CSRF (não mais via GET)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    csrf_verify();
    $aid = (int)$_POST['admin_id'];
    if ($aid === $me) {
        $error = 'Você não pode deletar sua própria conta.';
    } else {
        // Garante que reste pelo menos 1 admin
        $count = (int)$pdo->query("SELECT COUNT(*) FROM admins")->fetchColumn();
        if ($count <= 1) {
            $error = 'Não é possível remover o último administrador.';
        } else {
            $pdo->prepare("DELETE FROM admins WHERE id=?")->execute([$aid]);
            $msg = 'Admin removido.';
        }
    }
}

$admins = $pdo->query("SELECT id, name, email, created_at FROM admins ORDER BY created_at")->fetchAll();

$page_title  = 'Administradores';
$current_nav = 'admins';
require __DIR__ . '/_layout.php';
?>

<h1>Administradores</h1>

<?php if ($msg): ?><div class="alert alert-ok"><?= h($msg) ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-err"><?= h($error) ?></div><?php endif; ?>

<!-- Novo admin -->
<div class="card">
  <h2>Novo Administrador</h2>
  <form method="post">
    <?= csrf_field() ?>
    <input type="hidden" name="action" value="create">
    <div class="form-row">
      <div><label>Nome</label><input type="text" name="name" required></div>
      <div><label>E-mail</label><input type="email" name="email" required></div>
      <div><label>Senha (mín. 8 chars)</label><input type="password" name="pass" required></div>
    </div>
    <div class="form-actions"><button type="submit" class="btn btn-blue">Criar Admin</button></div>
  </form>
</div>

<!-- Lista -->
<div class="card" style="padding:0;overflow:hidden">
<table>
  <thead><tr><th>Nome</th><th>E-mail</th><th>Cadastro</th><th>Ações</th></tr></thead>
  <tbody>
  <?php foreach ($admins as $a): ?>
  <tr>
    <td><?= h($a['name']) ?> <?= $a['id'] === $me ? '<span class="badge badge-ok">Você</span>' : '' ?></td>
    <td><?= h($a['email']) ?></td>
    <td><?= date('d/m/Y', strtotime($a['created_at'])) ?></td>
    <td>
      <!-- Alterar senha: exige senha atual -->
      <form method="post" style="display:inline-flex;gap:.3rem;align-items:center;flex-wrap:wrap">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="change_pass">
        <input type="hidden" name="admin_id" value="<?= $a['id'] ?>">
        <input type="password" name="current_pass" placeholder="Senha atual" style="width:120px;padding:.25rem .5rem;font-size:.8rem" required>
        <input type="password" name="new_pass" placeholder="Nova senha" style="width:120px;padding:.25rem .5rem;font-size:.8rem" required>
        <button type="submit" class="btn btn-gray btn-sm">Alterar</button>
      </form>
      <?php if ($a['id'] !== $me): ?>
      <form method="post" style="display:inline-block;margin-left:.3rem"
            onsubmit="return confirm('Remover este admin permanentemente?')">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="delete">
        <input type="hidden" name="admin_id" value="<?= $a['id'] ?>">
        <button type="submit" class="btn btn-red btn-sm">Remover</button>
      </form>
      <?php endif; ?>
    </td>
  </tr>
  <?php endforeach; ?>
  </tbody>
</table>
</div>

</div></body></html>
