<?php

declare(strict_types=1);

/**
 * bin/create_platform_admin.php
 *
 * Usage: php bin/create_platform_admin.php "Your Name" you@example.com
 *
 * Creates (or updates the password of) the platform_admins row you use
 * to log into admin.<APP_DOMAIN>/platform/login — this is YOUR login,
 * completely separate from any tenant's CRM users. Prints a one-time
 * generated password, same discipline as bin/seed.php.
 */

require __DIR__ . '/../app/Core/Autoloader.php';

use App\Core\Autoloader;
use App\Core\Database;
use App\Core\Env;

Autoloader::register(dirname(__DIR__));
Env::load(dirname(__DIR__) . '/.env');

[, $name, $email] = array_pad($argv, 3, null);

if ($name === null || $email === null) {
    fwrite(STDERR, "Usage: php bin/create_platform_admin.php \"Your Name\" you@example.com\n");
    exit(1);
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    fwrite(STDERR, "'{$email}' doesn't look like a valid email address.\n");
    exit(1);
}

$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%';
$password = '';
for ($i = 0; $i < 20; $i++) {
    $password .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}

$hash = password_hash($password, PASSWORD_ARGON2ID);
$pdo = Database::connection();

$stmt = $pdo->prepare(
    'INSERT INTO platform_admins (name, email, password_hash, is_active, created_at, updated_at)
     VALUES (:name, :email, :hash, 1, NOW(), NOW())
     ON DUPLICATE KEY UPDATE name = VALUES(name), password_hash = VALUES(password_hash), is_active = 1'
);
$stmt->execute(['name' => $name, 'email' => $email, 'hash' => $hash]);

echo "Platform admin ready.\n\n";
echo "  Email:    {$email}\n";
echo "  Password: {$password}\n\n";
echo "This password is never stored anywhere else — copy it now. Log in at\n";
echo "https://admin." . (Env::get('APP_DOMAIN', '<your-domain>')) . "/platform/login\n";
