<?php
/**
 * Shared user registration (first or subsequent) for auth API and install wizard.
 */

declare(strict_types=1);

require_once __DIR__ . '/../security/sanitize.php';
require_once __DIR__ . '/store.php';

/**
 * @param array $body Same shape as authRegister JSON (email, username, fullname, phone, password).
 * @param bool $ignoreSignupGate When true (installer only), skips allow_user_registration check.
 * @return array The persisted user row (internal shape).
 * @throws RuntimeException Validation / conflict errors with user-facing Spanish messages.
 */
function antara_auth_register_user(array $body, bool $ignoreSignupGate = false): array
{
    $cfg = AntaraStore::configRead();
    if (!$ignoreSignupGate && !$cfg['allow_user_registration']) {
        throw new RuntimeException('La creación de nuevos usuarios está deshabilitada por el administrador.');
    }

    $email = AntaraSanitize::email($body['email'] ?? '');
    $username = AntaraSanitize::username($body['username'] ?? ($body['fullname'] ?? ''));
    $phone = AntaraSanitize::phone($body['phone'] ?? '') ?? '';
    $password = AntaraSanitize::password($body['password'] ?? '');

    if (!$email && !$username) {
        throw new RuntimeException('Email o nombre de usuario requeridos.');
    }
    if (!$password) {
        throw new RuntimeException('La contraseña debe tener al menos 8 caracteres.');
    }

    if ($email && AntaraStore::findUserByLogin($email)) {
        throw new RuntimeException('Ya existe una cuenta con ese correo.');
    }
    if ($username && AntaraStore::findUserByLogin($username)) {
        throw new RuntimeException('Ya existe una cuenta con ese usuario.');
    }

    $blob = AntaraStore::usersAll();
    $hasSuper = false;
    foreach ($blob['users'] as $u) {
        if (($u['role'] ?? '') === AntaraStore::ROLE_SUPER
            && empty($u['deletedAt'])
            && ($u['active'] ?? true)
            && empty($u['blocked'])) {
            $hasSuper = true;
            break;
        }
    }
    $role = $hasSuper ? AntaraStore::ROLE_USER : AntaraStore::ROLE_SUPER;

    $patch = [
        'email'        => (string)($email ?: ''),
        'username'     => (string)($username ?: ''),
        'phone'        => $phone,
        'role'         => $role,
        'active'       => true,
        'passwordHash' => password_hash($password, PASSWORD_DEFAULT),
        'requirePasswordReset' => false,
    ];
    if (isset($body['branchId']) && is_string($body['branchId'])) {
        $bid = trim($body['branchId']);
        if ($bid !== '') {
            $patch['branchId'] = $bid;
        }
    }

    return AntaraStore::upsertUser($patch);
}

/** Count of users that are not soft-deleted. */
function antara_auth_active_user_count(): int
{
    $blob = AntaraStore::usersAll();
    $n = 0;
    foreach ($blob['users'] ?? [] as $u) {
        if (empty($u['deletedAt'])) {
            $n++;
        }
    }
    return $n;
}

/**
 * When the instance still allows anonymous desktop, switch to login-required
 * and disable public-desktop-without-users (same as install "first user" finish).
 */
function antara_auth_privatize_public_desktop(): void
{
    $cfg = AntaraStore::configRead();
    if (!empty($cfg['login_required'])) {
        return;
    }
    AntaraStore::configWrite([
        'login_required'               => true,
        'public_desktop_without_users' => false,
    ]);
}
