<?php
// One-time helper to create the first CMS admin from the browser, for
// hosts without SSH/Terminal access to run a CLI script. Refuses to run
// once any admin_users row exists — delete this whole setup/ folder after
// you've created your account.

$config = require __DIR__ . '/../includes/config.php';
$db = $config['db'];

try {
    $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]
    );
} catch (PDOException $e) {
    die('No se pudo conectar a la base de datos. Revisa backend/config.php.');
}

$adminCount = (int) $pdo->query('SELECT COUNT(*) AS c FROM admin_users')->fetch()['c'];
$message = null;
$done = false;

if ($adminCount > 0) {
    $message = 'Ya existe al menos un administrador. Por seguridad, borra la carpeta backend/setup/ del servidor.';
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $setupKey = $_POST['setup_key'] ?? '';
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (!hash_equals($config['setup_key'], $setupKey)) {
        $message = 'Clave de configuración incorrecta.';
    } elseif ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = 'Correo inválido.';
    } elseif (strlen($password) < 8) {
        $message = 'La contraseña debe tener al menos 8 caracteres.';
    } else {
        $stmt = $pdo->prepare('INSERT INTO admin_users (email, password_hash) VALUES (?, ?)');
        $stmt->execute([$email, password_hash($password, PASSWORD_DEFAULT)]);
        $done = true;
        $message = 'Administrador creado. Ya puedes borrar la carpeta backend/setup/ y usar /admin/login en el sitio.';
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head><meta charset="UTF-8"><title>AVI CMS · Crear administrador</title>
<style>
  body{font-family:system-ui,-apple-system,sans-serif;background:#0b0b0f;color:#f5f5f8;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}
  form,.msg{width:360px;background:#15151a;padding:32px;border-radius:16px;border:1px solid #2c2c34}
  h1{font-size:18px;margin:0 0 20px}
  label{display:block;font-size:13px;color:#a0a0ac;margin-bottom:6px}
  input{width:100%;box-sizing:border-box;background:#0b0b0f;border:1px solid #2c2c34;border-radius:8px;padding:10px 12px;color:#f5f5f8;margin-bottom:16px;font-size:14px}
  button{width:100%;background:#23ba60;color:#06120a;border:none;border-radius:8px;padding:10px;font-weight:600;cursor:pointer}
  p{font-size:14px;line-height:1.6;color:#d0d0d6}
</style>
</head>
<body>
<?php if ($done || $adminCount > 0): ?>
  <div class="msg"><h1>AVI CMS</h1><p><?= htmlspecialchars($message) ?></p></div>
<?php else: ?>
  <form method="post">
    <h1>Crear administrador del CMS</h1>
    <?php if ($message): ?><p style="color:#ff8a80"><?= htmlspecialchars($message) ?></p><?php endif; ?>
    <label>Clave de configuración (setup_key en config.php)</label>
    <input type="password" name="setup_key" required>
    <label>Correo</label>
    <input type="email" name="email" required>
    <label>Contraseña (mín. 8 caracteres)</label>
    <input type="password" name="password" required minlength="8">
    <button type="submit">Crear administrador</button>
  </form>
<?php endif; ?>
</body>
</html>
