<?php
/**
 * Shared helpers for tenant admin invite APIs (dashboard Profile → Admin team).
 * Requires firebase-admin-bootstrap.local.php + firebase-rtdb-admin.php.
 */

require_once __DIR__ . '/firebase-rtdb-admin.php';

/** Panel ids that can be granted to invited staff (must match dashboard.js TENANT_ADMIN_PANEL_IDS). */
function tenant_admin_panel_id_whitelist(): array {
    return [
        'home',
        'completed-orders',
        'incomplete-orders',
        'order-detail',
        'customers',
        'visitor-spy',
        'detective-brain',
        'live-ads-overview',
        'live-ads-facebook',
        'ai-ads-manager',
        'facebook-page-post',
        'hosting',
        'files',
        'customization',
        'swapno-theme',
        'manage-banners',
        'shipping-settings',
        'policy-settings',
        'integrations',
        'tiktok-settings',
        'notifications',
        'products',
        'add-category',
        'website-icons',
        'category-display',
        'general-settings',
        'color-settings',
        'theme',
    ];
}

function tenant_admin_sanitize_email_key(string $email): string {
    return preg_replace('/[.#$\[\]\/]/', '_', strtolower(trim($email)));
}

function tenant_admin_json_response(int $code, array $payload): void {
    http_response_code($code);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * @return array{boot: array, dbUrl: string, accessToken: string, webKey: string}
 */
function tenant_admin_require_bootstrap(): array {
    $bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
    if (!is_readable($bootPath)) {
        tenant_admin_json_response(503, ['status' => 'error', 'message' => 'Server not configured: firebase-admin-bootstrap.local.php missing.']);
    }
    $boot = include $bootPath;
    if (!is_array($boot)) {
        tenant_admin_json_response(503, ['status' => 'error', 'message' => 'Invalid firebase-admin-bootstrap.local.php.']);
    }
    $saPath = isset($boot['service_account_json_path']) ? trim((string) $boot['service_account_json_path']) : '';
    $dbUrl = isset($boot['firebase_database_url']) ? trim((string) $boot['firebase_database_url']) : '';
    $webKey = isset($boot['firebase_web_api_key']) ? trim((string) $boot['firebase_web_api_key']) : '';
    if ($saPath === '' || $dbUrl === '' || $webKey === '' || $webKey === 'PASTE_FIREBASE_WEB_API_KEY_HERE') {
        tenant_admin_json_response(503, ['status' => 'error', 'message' => 'Bootstrap config incomplete.']);
    }
    $tok = firebase_service_account_access_token($saPath);
    if (isset($tok['error']) || empty($tok['access_token'])) {
        tenant_admin_json_response(503, ['status' => 'error', 'message' => 'Service account token failed: ' . ($tok['error'] ?? 'unknown')]);
    }
    return [
        'boot' => $boot,
        'dbUrl' => $dbUrl,
        'accessToken' => $tok['access_token'],
        'webKey' => $webKey,
    ];
}

/** @return array{uid: string, email: string} */
function tenant_admin_lookup_id_token(string $idToken, string $webKey): array {
    $idToken = trim($idToken);
    if ($idToken === '') {
        tenant_admin_json_response(400, ['status' => 'error', 'message' => 'idToken is required.']);
    }
    $url = 'https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=' . rawurlencode($webKey);
    if (!function_exists('curl_init')) {
        tenant_admin_json_response(500, ['status' => 'error', 'message' => 'PHP curl extension required.']);
    }
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['idToken' => $idToken]),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    if ($res === false) {
        tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Could not verify idToken.']);
    }
    $data = json_decode($res, true);
    if (empty($data['users'][0]['localId'])) {
        $msg = isset($data['error']['message']) ? (string) $data['error']['message'] : 'Invalid or expired idToken.';
        tenant_admin_json_response(401, ['status' => 'error', 'message' => $msg]);
    }
    return [
        'uid' => (string) $data['users'][0]['localId'],
        'email' => isset($data['users'][0]['email']) ? strtolower(trim((string) $data['users'][0]['email'])) : '',
    ];
}

/** @return array<string, mixed>|null */
function tenant_admin_get_admin_node(string $dbUrl, string $accessToken, string $clientId, string $uid): ?array {
    $path = 'clients/' . $clientId . '/admins/' . $uid;
    $snap = firebase_rtdb_get($dbUrl, $path, $accessToken);
    if (isset($snap['error'])) {
        tenant_admin_json_response(500, ['status' => 'error', 'message' => 'RTDB read failed: ' . $snap['error']]);
    }
    $d = $snap['data'] ?? null;
    return is_array($d) ? $d : null;
}

function tenant_admin_is_truthy_member(?array $node): bool {
    return $node !== null && firebase_rtdb_is_truthy_admin($node);
}

/** Owner: legacy nodes without role, or explicit role owner. */
function tenant_admin_is_store_owner(?array $node): bool {
    if (!tenant_admin_is_truthy_member($node)) {
        return false;
    }
    if (!isset($node['role']) || $node['role'] === null || $node['role'] === '') {
        return true;
    }
    return (string) $node['role'] === 'owner';
}

function tenant_admin_password_ok(string $password): bool {
    if (strlen($password) < 8) {
        return false;
    }
    if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
        return false;
    }
    return true;
}

/**
 * @param mixed $raw
 * @return array<string, bool>
 */
function tenant_admin_normalize_permissions_map($raw): array {
    $whitelist = array_fill_keys(tenant_admin_panel_id_whitelist(), true);
    $out = [];
    if (!is_array($raw)) {
        return $out;
    }
    foreach ($raw as $k => $v) {
        $key = is_string($k) ? trim($k) : '';
        if ($key === '' || !isset($whitelist[$key])) {
            continue;
        }
        $out[$key] = (bool) $v;
    }
    return $out;
}

function tenant_admin_require_post_json(): array {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        tenant_admin_json_response(405, ['status' => 'error', 'message' => 'Method not allowed']);
    }
    $raw = file_get_contents('php://input');
    $body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
    if (!is_array($body)) {
        tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Invalid JSON']);
    }
    return $body;
}

function tenant_admin_require_client_id(array $body): string {
    $clientId = isset($body['clientId']) ? trim((string) $body['clientId']) : '';
    if ($clientId === '' || !preg_match('/^[a-zA-Z0-9_-]{1,120}$/', $clientId)) {
        tenant_admin_json_response(400, ['status' => 'error', 'message' => 'Valid clientId is required.']);
    }
    return $clientId;
}
