<?php
/**
 * POST JSON: { idToken, clientId, newEmail, newPassword, permissions?: object }
 * Creates Firebase Auth user + clients/{clientId}/admins/{newUid} with role staff.
 * Only store owners may call.
 */
require_once __DIR__ . '/tenant-admin-common.php';

$body = tenant_admin_require_post_json();
$clientId = tenant_admin_require_client_id($body);
$idToken = isset($body['idToken']) ? trim((string) $body['idToken']) : '';
$newEmail = isset($body['newEmail']) ? trim(strtolower((string) $body['newEmail'])) : '';
$newPassword = isset($body['newPassword']) ? (string) $body['newPassword'] : '';
$permsIn = $body['permissions'] ?? [];
$hintSub = isset($body['siteSubdomain']) ? trim((string) $body['siteSubdomain']) : '';
$hintName = isset($body['siteDisplayName']) ? trim((string) $body['siteDisplayName']) : '';

if (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Invalid email.']);
}
if (!tenant_admin_password_ok($newPassword)) {
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Password must be at least 8 characters and include letters and numbers.']);
}

$ctx = tenant_admin_require_bootstrap();
$dbUrl = $ctx['dbUrl'];
$accessToken = $ctx['accessToken'];
$webKey = $ctx['webKey'];

$actor = tenant_admin_lookup_id_token($idToken, $webKey);
$actorUid = $actor['uid'];

$actorNode = tenant_admin_get_admin_node($dbUrl, $accessToken, $clientId, $actorUid);
if (!tenant_admin_is_store_owner($actorNode)) {
    tenant_admin_json_response(403, ['status' => 'error', 'message' => 'Only the store owner can invite admins.']);
}

$perms = tenant_admin_normalize_permissions_map($permsIn);
$hasNonHome = false;
foreach ($perms as $k => $v) {
    if ($v && (string) $k !== 'home') {
        $hasNonHome = true;
        break;
    }
}
if (!$hasNonHome) {
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Select at least one section besides Home.']);
}

$siteStubSnap = firebase_rtdb_get($dbUrl, 'userSites/' . $actorUid . '/' . $clientId, $accessToken);
if (isset($siteStubSnap['error'])) {
    tenant_admin_json_response(500, ['status' => 'error', 'message' => 'Could not read site mapping: ' . $siteStubSnap['error']]);
}
$siteStub = is_array($siteStubSnap['data'] ?? null) ? $siteStubSnap['data'] : [];
if ($siteStub === [] || (empty($siteStub['subdomain']) && $hintSub !== '')) {
    if ($hintSub !== '' && $hintName !== '') {
        $mapSnap = firebase_rtdb_get($dbUrl, 'publicSiteMappings/' . $hintSub, $accessToken);
        $mapped = isset($mapSnap['data']) ? (string) $mapSnap['data'] : '';
        if ($mapped === $clientId) {
            $siteStub = ['subdomain' => $hintSub, 'siteName' => $hintName];
        }
    }
}
if ($siteStub === [] || empty($siteStub['subdomain'])) {
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Could not resolve site subdomain for new user. Open dashboard from this store and try again, or pass siteSubdomain + siteDisplayName that match publicSiteMappings.']);
}
if (empty($siteStub['siteName'])) {
    $siteStub['siteName'] = (string) ($siteStub['subdomain'] ?? 'Store');
}

$auth = firebase_identity_sign_up_email($webKey, $newEmail, $newPassword);
if (isset($auth['error'])) {
    $code = (string) ($auth['firebaseCode'] ?? $auth['error']);
    if (stripos($code, 'EMAIL_EXISTS') !== false) {
        tenant_admin_json_response(409, ['status' => 'error', 'message' => 'This email is already registered.']);
    }
    if (stripos($code, 'WEAK_PASSWORD') !== false) {
        tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Password rejected as too weak.']);
    }
    tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Auth error: ' . $auth['error']]);
}

$newUid = $auth['uid'];
$idTokenNew = $auth['idToken'] ?? '';

$adminRecord = [
    'email' => $newEmail,
    'role' => 'staff',
    'permissions' => $perms,
    'createdBy' => $actorUid,
    'createdAt' => time() * 1000,
];

$put = firebase_rtdb_put($dbUrl, 'clients/' . $clientId . '/admins/' . $newUid, $accessToken, $adminRecord);
if (isset($put['error']) || (($put['http'] ?? 500) >= 400)) {
    if ($idTokenNew !== '') {
        firebase_identity_delete_account($webKey, $idTokenNew);
    }
    tenant_admin_json_response(500, ['status' => 'error', 'message' => 'Failed to save admin record: ' . ($put['error'] ?? 'HTTP ' . ($put['http'] ?? ''))]);
}

$emailKey = tenant_admin_sanitize_email_key($newEmail);
$patch = [
    'userSites/' . $newUid . '/' . $clientId => $siteStub,
    'usersByEmail/' . $emailKey . '/' . $clientId => $siteStub,
];
$patchRes = firebase_rtdb_patch($dbUrl, '', $accessToken, $patch);
if (isset($patchRes['error']) || (($patchRes['http'] ?? 500) >= 400)) {
    firebase_rtdb_delete($dbUrl, 'clients/' . $clientId . '/admins/' . $newUid, $accessToken);
    if ($idTokenNew !== '') {
        firebase_identity_delete_account($webKey, $idTokenNew);
    }
    tenant_admin_json_response(500, ['status' => 'error', 'message' => 'Failed to link user site (rolled back): ' . ($patchRes['error'] ?? '')]);
}

tenant_admin_json_response(200, [
    'status' => 'success',
    'message' => 'Admin invited.',
    'uid' => $newUid,
]);
