<?php
/**
 * Create the first admin account.
 * Usage:  php src/bin/seed_admin.php <username> <password> <first_name>
 * Delete this file from the server after you're done.
 */
declare(strict_types=1);

chdir(dirname(__DIR__, 2));
define('MAT_ROOT', __DIR__ . '/../..');
$config = require MAT_ROOT . '/config.php';
$GLOBALS['mat_config'] = $config;

require MAT_ROOT . '/src/autoload.php';
require MAT_ROOT . '/src/helpers.php';
$_SESSION = [];

use App\Repositories\Container;

$username = $argv[1] ?? 'admin';
$password = $argv[2] ?? 'changeme123';
$first    = $argv[3] ?? 'Admin';

if (strlen($password) < 8) {
    fwrite(STDERR, "Password must be 8+ characters.\n");
    exit(1);
}

if (Container::users()->findByUsername($username)) {
    fwrite(STDERR, "Username '{$username}' already exists.\n");
    exit(1);
}

$user = Container::users()->save([
    'username'   => strtolower($username),
    'role'       => 'ADMIN',
    'first_name' => $first,
    'last_name'  => '',
    'email'      => null,
    'password_hash' => password_hash($password, PASSWORD_DEFAULT),
    'pin_hash'   => null,
    'is_active'  => true,
]);

echo "✓ Admin account created: {$user['username']}\n";
echo "  Log in at /hub/login with username '{$user['username']}' and the password you provided.\n";
echo "  You'll be asked to set a PIN on first login.\n";
echo "\n⚠ Delete this script from your server after seeding.\n";
