#!/usr/bin/env php
<?php

declare(strict_types=1);

use Xamma\Database\Database;
use Xamma\Support\Environment;

$root = dirname(__DIR__);
require $root . '/vendor/autoload.php';
Environment::load($root . '/.env');
$database = new Database(require $root . '/config/database.php');
if (!$database->connected()) {
    fwrite(STDERR, "The database is not configured or cannot be reached. Complete the browser installation guide first.\n");
    exit(1);
}

$email = trim((string) ($argv[1] ?? ''));
$name = trim((string) ($argv[2] ?? ''));
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || $name === '') {
    fwrite(STDERR, "Usage: php bin/create-admin email@example.com \"Display Name\"\n");
    exit(1);
}

fwrite(STDOUT, 'Password: ');
$canHideInput = PHP_OS_FAMILY !== 'Windows' && function_exists('shell_exec');
if ($canHideInput) {
    shell_exec('stty -echo');
}
$password = trim((string) fgets(STDIN));
if ($canHideInput) {
    shell_exec('stty echo');
    fwrite(STDOUT, "\n");
}
if (strlen($password) < 12) {
    fwrite(STDERR, "The password must contain at least 12 characters.\n");
    exit(1);
}

$database->execute(
    "INSERT INTO main_users (email, password_hash, display_name, role, is_active, created_at, updated_at) VALUES (:email, :password_hash, :display_name, 'admin', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)",
    ['email' => strtolower($email), 'password_hash' => password_hash($password, PASSWORD_DEFAULT), 'display_name' => $name]
);
fwrite(STDOUT, "Administrator created.\n");
