<?php
// CLI only: php tools/create_user.php. Never expose account provisioning over HTTP.
declare(strict_types=1);
if (PHP_SAPI !== 'cli') { http_response_code(404); exit; }
require_once __DIR__ . '/../authentication/api/connect.php';
function prompt(string $label): string {
    fwrite(STDOUT, $label);
    $value = fgets(STDIN);
    if ($value === false) { throw new RuntimeException('Input ended'); }
    return rtrim($value, "\r\n");
}
try {
    $username = trim(prompt('Username: '));
    $email = trim(prompt('Email: '));
    $role = trim(prompt('Role (admin/staff/student): '));
    $password = prompt('Password (input is visible; at least 12 characters, max 72 UTF-8 bytes): ');
    $confirm = prompt('Confirm password: ');
    $length = preg_match_all('/./us', $password);
    if ($username === '' || strlen($username) > 100 || strlen($email) > 150 || !filter_var($email, FILTER_VALIDATE_EMAIL)
        || !in_array($role, ['admin', 'staff', 'student'], true)
        || $length === false || $length < 12 || strlen($password) > 72 || trim($password) === '' || $password !== $confirm) {
        throw new RuntimeException('Invalid account details or passwords do not match');
    }
    $database = db();
    $stmt = $database->prepare('SELECT id FROM users WHERE username IN (?, ?) OR email IN (?, ?) LIMIT 1');
    $stmt->execute([$username, $email, $username, $email]);
    if ($stmt->fetch()) { throw new RuntimeException('Username or email is already used'); }
    $stmt = $database->prepare('INSERT INTO users (username, email, password_hash, role, is_active) VALUES (?, ?, ?, ?, 1)');
    $stmt->execute([$username, $email, password_hash($password, PASSWORD_DEFAULT), $role]);
    fwrite(STDOUT, 'Account created. User ID: ' . $database->lastInsertId() . PHP_EOL);
    fwrite(STDOUT, "Create its student/staff/admin profile separately when building those modules.\n");
} catch (Throwable $e) {
    fwrite(STDERR, $e instanceof mysqli_sql_exception ? "Database operation failed. Check configuration and duplicate accounts.\n" : $e->getMessage() . PHP_EOL);
    exit(1);
}
