<?php

declare(strict_types=1);

require __DIR__ . '/dev-db.php';

/**
 * CLI-only bootstrap: grants (or confirms) platform-admin/backoffice access
 * for an existing user by email. There is no web UI to grant the first
 * platform admin on purpose, so this can only be done with direct DB/shell
 * access, not through any public endpoint.
 *
 * Usage: php scripts/grant-platform-admin.php someone@example.com
 */

$email = trim((string)($argv[1] ?? ''));
if ($email === '') {
    fwrite(STDERR, "Usage: php scripts/grant-platform-admin.php <email>\n");
    exit(1);
}

$emailNorm = strtolower($email);
$pdo = dev_pdo();

$stmt = $pdo->prepare('SELECT id, display_name FROM users WHERE email_norm = ?');
$stmt->execute([$emailNorm]);
$user = $stmt->fetch();

if ($user === false) {
    fwrite(STDERR, "Kein Nutzerkonto mit dieser E-Mail gefunden. Zuerst registrieren/einloggen, dann erneut ausführen.\n");
    exit(1);
}

$stmt = $pdo->prepare('SELECT 1 FROM platform_admins WHERE user_id = ?');
$stmt->execute([(int)$user['id']]);
if ($stmt->fetchColumn() !== false) {
    echo "{$email} ist bereits Platform-Admin.\n";
    exit(0);
}

$pdo->prepare('INSERT INTO platform_admins (user_id) VALUES (?)')->execute([(int)$user['id']]);

echo "{$email} ({$user['display_name']}) ist jetzt Platform-Admin und kann das Back-Office unter backoffice.php nutzen.\n";
