<?php
// ============================================================
// SETUP INICIAL — cria o primeiro admin no banco
// Acesse UMA vez: /admin/setup.php
// Depois delete ou bloqueie este arquivo
// ============================================================
require_once __DIR__ . '/../config.php';

function db(): PDO {
    static $pdo = null;
    if ($pdo === null) {
        $pdo = new PDO(
            'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4',
            DB_USER, DB_PASS,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
        );
    }
    return $pdo;
}

$done  = false;
$error = '';

try {
    $count = (int) db()->query("SELECT COUNT(*) FROM admins")->fetchColumn();
    if ($count > 0) {
        die('<p style="font-family:sans-serif;padding:2rem;color:#dc2626">Setup já foi realizado. Delete este arquivo por segurança.</p>');
    }
} catch (Throwable $e) {
    $error = 'Erro ao conectar no banco: ' . $e->getMessage();
}

if (!$error && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $name  = trim($_POST['name']  ?? '');
    $email = trim($_POST['email'] ?? '');
    $pass  = $_POST['pass']  ?? '';
    $pass2 = $_POST['pass2'] ?? '';

    if (!$name || !$email || !$pass) {
        $error = 'Preencha todos os campos.';
    } elseif ($pass !== $pass2) {
        $error = 'As senhas não conferem.';
    } elseif (strlen($pass) < 8) {
        $error = 'A senha deve ter pelo menos 8 caracteres.';
    } else {
        $hash = password_hash($pass, PASSWORD_DEFAULT);
        db()->prepare("INSERT INTO admins (name, email, password_hash) VALUES (?,?,?)")
             ->execute([$name, $email, $hash]);
        $done = true;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Setup — MonitorPing Licenças</title>
<style>
  body { font-family: sans-serif; background: #0f172a; color: #e2e8f0; display:flex; align-items:center; justify-content:center; min-height:100vh; margin:0; }
  .box { background:#1e293b; padding:2rem; border-radius:8px; width:360px; }
  h2 { color:#38bdf8; margin:0 0 1.5rem; }
  label { display:block; font-size:.85rem; color:#94a3b8; margin-bottom:.3rem; }
  input { width:100%; padding:.55rem; border:1px solid #334155; border-radius:4px; background:#0f172a; color:#e2e8f0; margin-bottom:1rem; box-sizing:border-box; }
  button { width:100%; padding:.7rem; background:#0ea5e9; border:none; border-radius:4px; color:#fff; font-size:1rem; cursor:pointer; }
  .error { background:#7f1d1d; color:#fecaca; padding:.6rem; border-radius:4px; margin-bottom:1rem; font-size:.9rem; }
  .ok { background:#166534; color:#bbf7d0; padding:.6rem; border-radius:4px; font-size:.9rem; }
  small { color:#64748b; font-size:.8rem; }
</style>
</head>
<body>
<div class="box">
  <h2>Criar Admin</h2>
  <?php if ($done): ?>
    <div class="ok">Admin criado com sucesso! <strong>Delete este arquivo agora.</strong></div>
    <p style="margin-top:1rem"><a href="login.php" style="color:#38bdf8">Ir para o login</a></p>
  <?php else: ?>
    <?php if ($error): ?><div class="error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
    <form method="post">
      <label>Nome</label>
      <input type="text" name="name" required>
      <label>E-mail</label>
      <input type="email" name="email" required>
      <label>Senha</label>
      <input type="password" name="pass" required>
      <label>Confirmar Senha</label>
      <input type="password" name="pass2" required>
      <button type="submit">Criar Admin</button>
    </form>
    <p style="margin-top:1rem"><small>Delete este arquivo após o setup.</small></p>
  <?php endif; ?>
</div>
</body>
</html>
