<?php
header('Content-Type: application/json; charset=UTF-8');
require_once __DIR__ . '/firebase-rtdb-admin.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
    exit;
}

$raw = file_get_contents('php://input');
$body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
if (!is_array($body)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
    exit;
}

$idToken = isset($body['idToken']) ? trim((string) $body['idToken']) : '';
$siteName = isset($body['siteName']) ? trim((string) $body['siteName']) : '';
$clientIdHint = isset($body['clientId']) ? trim((string) $body['clientId']) : '';
$subdomainHint = isset($body['subdomain']) ? trim((string) $body['subdomain']) : '';

if ($idToken === '') {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'idToken is required.']);
    exit;
}

$bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (!is_readable($bootPath)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Server not configured: firebase-admin-bootstrap.local.php missing.']);
    exit;
}
$boot = include $bootPath;
if (!is_array($boot)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Invalid firebase-admin-bootstrap.local.php.']);
    exit;
}

$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') {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Bootstrap config incomplete.']);
    exit;
}

function auth_lookup_user($idToken, $webApiKey) {
    $url = 'https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=' . rawurlencode($webApiKey);
    $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) return ['error' => '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.';
        return ['error' => $msg];
    }
    return [
        'uid' => (string) $data['users'][0]['localId'],
        'email' => isset($data['users'][0]['email']) ? strtolower(trim((string) $data['users'][0]['email'])) : ''
    ];
}

function normalize_subdomain($raw) {
    $s = strtolower(trim((string) $raw));
    $s = preg_replace('/\s+/', '-', $s);
    $s = preg_replace('/[^a-z0-9-]/', '', $s);
    $s = preg_replace('/-+/', '-', $s);
    $s = preg_replace('/^-+|-+$/', '', $s);
    return (string) $s;
}

function subdomain_variants($raw) {
    $base = normalize_subdomain($raw);
    $set = [];
    if ($base !== '') {
        $set[$base] = true;
        $set[$base . '-'] = true;
        $set['-' . $base] = true;
        $set[str_replace('-', '', $base)] = true;
    }
    return array_keys($set);
}

function pick_client_from_user_sites($dbUrl, $accessToken, $uid) {
    $snap = firebase_rtdb_get($dbUrl, 'userSites/' . $uid, $accessToken);
    if (isset($snap['error']) || !is_array($snap['data'])) return null;
    foreach ($snap['data'] as $cid => $site) {
        if (!empty($cid)) {
            $sub = is_array($site) && !empty($site['subdomain']) ? (string) $site['subdomain'] : '';
            $name = is_array($site) && !empty($site['siteName']) ? (string) $site['siteName'] : $sub;
            return ['clientId' => (string) $cid, 'subdomain' => $sub, 'siteName' => $name];
        }
    }
    return null;
}

function pick_client_from_site_name($dbUrl, $accessToken, $siteName) {
    foreach (subdomain_variants($siteName) as $key) {
        $snap = firebase_rtdb_get($dbUrl, 'publicSiteMappings/' . $key, $accessToken);
        if (!isset($snap['error']) && !empty($snap['data'])) {
            return ['clientId' => (string) $snap['data'], 'subdomain' => $key, 'siteName' => trim((string) $siteName)];
        }
    }
    return null;
}

$lookup = auth_lookup_user($idToken, $webKey);
if (isset($lookup['error'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => $lookup['error']]);
    exit;
}
$uid = $lookup['uid'];
$email = $lookup['email'];

$dbTok = firebase_service_account_access_token($saPath);
if (isset($dbTok['error'])) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Firebase admin token error: ' . $dbTok['error']]);
    exit;
}
$dbAccess = $dbTok['access_token'];

$resolved = null;
if ($clientIdHint !== '') {
    $resolved = ['clientId' => $clientIdHint, 'subdomain' => $subdomainHint, 'siteName' => $siteName];
}
if ($resolved === null) {
    $resolved = pick_client_from_user_sites($dbUrl, $dbAccess, $uid);
}
if ($resolved === null && $siteName !== '') {
    $resolved = pick_client_from_site_name($dbUrl, $dbAccess, $siteName);
}
if ($resolved === null) {
    http_response_code(404);
    echo json_encode(['status' => 'error', 'message' => 'Site not found. Check the business name.']);
    exit;
}

$clientId = (string) $resolved['clientId'];
$uidAdminSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/admins/' . $uid, $dbAccess);
if (!isset($uidAdminSnap['error']) && firebase_rtdb_is_truthy_admin($uidAdminSnap['data'] ?? null)) {
    if ($resolved['siteName'] === '' || $resolved['subdomain'] === '') {
        $siteSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/siteSettings/siteName', $dbAccess);
        if (!isset($siteSnap['error']) && is_string($siteSnap['data'])) $resolved['siteName'] = $siteSnap['data'];
    }
    echo json_encode(['status' => 'success', 'siteInfo' => ['clientId' => $clientId, 'subdomain' => $resolved['subdomain'], 'siteName' => $resolved['siteName']]], JSON_UNESCAPED_UNICODE);
    exit;
}

$adminsSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/admins', $dbAccess);
if (isset($adminsSnap['error']) || !is_array($adminsSnap['data'])) {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'You are not authorized for this site.']);
    exit;
}

$legacyRole = '';
foreach ($adminsSnap['data'] as $admin) {
    if (!is_array($admin)) continue;
    $adminEmail = isset($admin['email']) ? strtolower(trim((string) $admin['email'])) : '';
    if ($adminEmail !== '' && $adminEmail === $email) {
        $legacyRole = isset($admin['role']) ? (string) $admin['role'] : 'owner';
        break;
    }
}
if ($legacyRole === '') {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'You are not authorized for this site.']);
    exit;
}

$migrate = firebase_rtdb_patch($dbUrl, 'clients/' . $clientId . '/admins', $dbAccess, [
    $uid => [
        'email' => $email,
        'role' => $legacyRole,
        'migratedAt' => time() * 1000
    ]
]);
if (isset($migrate['error'])) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Could not update admin access.']);
    exit;
}

if ($resolved['siteName'] === '' || $resolved['subdomain'] === '') {
    $siteSettingsSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/siteSettings', $dbAccess);
    if (!isset($siteSettingsSnap['error']) && is_array($siteSettingsSnap['data'])) {
        if ($resolved['siteName'] === '' && !empty($siteSettingsSnap['data']['siteName'])) $resolved['siteName'] = (string) $siteSettingsSnap['data']['siteName'];
    }
}

echo json_encode([
    'status' => 'success',
    'migrated' => true,
    'siteInfo' => [
        'clientId' => $clientId,
        'subdomain' => $resolved['subdomain'],
        'siteName' => $resolved['siteName']
    ]
], JSON_UNESCAPED_UNICODE);
