<?php
// CLI tool: php seed_admin.php <username> <password> [location]
// Creates an initial admin user in the encrypted database.
// If the DB doesn't exist yet, it is created from schema.sql.

if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    echo "CLI only\n";
    exit(1);
}

require_once __DIR__ . '/db_init.php';

$usage = "Usage: php seed_admin.php <username> <password> [location]\n";

$username = $argv[1] ?? '';
$password = $argv[2] ?? '';
$location = $argv[3] ?? '';

if ($username === '' || $password === '') {
    fwrite(STDERR, $usage);
    exit(1);
}

if (strlen($password) < 6) {
    fwrite(STDERR, "Error: Password must be at least 6 characters.\n");
    exit(1);
}

try {
    [$pdo, $tmpDb, $lockFp] = qdb_open(true);

    $existing = $pdo->prepare("SELECT userID FROM users WHERE username = :u");
    $existing->execute([':u' => $username]);
    if ($existing->fetch()) {
        qdb_discard($tmpDb, $lockFp);
        fwrite(STDERR, "Error: User '$username' already exists.\n");
        exit(1);
    }

    $adminID = bin2hex(random_bytes(16));
    $userID  = bin2hex(random_bytes(16));
    $hash    = password_hash($password, PASSWORD_DEFAULT);
    $now     = time();

    $pdo->beginTransaction();

    $pdo->prepare("INSERT INTO admin (adminID, username, location) VALUES (:id, :u, :loc)")
        ->execute([':id' => $adminID, ':u' => $username, ':loc' => $location]);

    $pdo->prepare(
        "INSERT INTO users (userID, username, passwordHash, role, entityID, mustChangePassword, createdAt)
         VALUES (:uid, :u, :hash, 'admin', :eid, 1, :now)"
    )->execute([':uid' => $userID, ':u' => $username, ':hash' => $hash, ':eid' => $adminID, ':now' => $now]);

    $pdo->commit();
    $pdo = null;

    qdb_save($tmpDb, $lockFp);
    echo "Admin user '$username' created successfully (must change password on first login).\n";

} catch (Throwable $e) {
    if (isset($tmpDb, $lockFp)) qdb_discard($tmpDb, $lockFp);
    fwrite(STDERR, "Error: " . $e->getMessage() . "\n");
    exit(1);
}
