<?php
/**
 * Create a new store (RTDB + Firebase Auth) matching setup.html wizard paths.
 * Auth: Identity Toolkit accounts:signUp with web API key from bootstrap (no extra SA OAuth scope).
 */
require_once __DIR__ . '/_super_admin_common.php';
require_once __DIR__ . '/sa_client_bootstrap_template.php';

const SA_CREATE_SITE_MAX_PER_HOUR = 10;

function sa_create_site_rate_consume($cfg) {
    sa_session_start_secure($cfg);
    $now = time();
    $k = 'sa_create_site_rate';
    $state = isset($_SESSION[$k]) && is_array($_SESSION[$k]) ? $_SESSION[$k] : ['window_start' => $now, 'count' => 0];
    if (($now - (int) ($state['window_start'] ?? $now)) > 3600) {
        $state = ['window_start' => $now, 'count' => 0];
    }
    if ((int) ($state['count'] ?? 0) >= SA_CREATE_SITE_MAX_PER_HOUR) {
        return false;
    }
    $state['count'] = (int) ($state['count'] ?? 0) + 1;
    $_SESSION[$k] = $state;
    return true;
}

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

function sa_parse_rtdb_post_name($name) {
    $name = (string) $name;
    if ($name === '') {
        return '';
    }
    if (preg_match('#/([^/]+)$#', $name, $m)) {
        return $m[1];
    }
    return $name;
}

$body = sa_require_post_json();
[$actorUid, $actorEmail, $dbUrl, $accessToken, $cfg, $webKey] = sa_require_super_admin_session_with_db();

$siteName = trim((string) ($body['siteName'] ?? ''));
$adminEmail = trim((string) ($body['adminEmail'] ?? ''));
$adminPassword = (string) ($body['adminPassword'] ?? '');
$rawSub = isset($body['subdomain']) ? trim((string) $body['subdomain']) : '';
$subdomain = $rawSub !== '' ? sa_normalize_subdomain($rawSub) : sa_normalize_subdomain($siteName);
$logoUrl = trim((string) ($body['logoUrl'] ?? ''));
$bannerUrl = trim((string) ($body['bannerUrl'] ?? ''));
$phone = trim((string) ($body['phone'] ?? ''));
$activeDesign = trim((string) ($body['activeDesign'] ?? 'ghorerbazar'));
if ($activeDesign === '') {
    $activeDesign = 'ghorerbazar';
}

if ($siteName === '' || mb_strlen($siteName) > 120) {
    sa_json_response(400, ['status' => 'error', 'message' => 'Invalid site name.']);
}
if (!filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
    sa_json_response(400, ['status' => 'error', 'message' => 'Invalid admin email.']);
}
if (!sa_password_ok($adminPassword)) {
    sa_json_response(400, ['status' => 'error', 'message' => 'Password must be at least 8 characters and include both letters and numbers.']);
}
if ($subdomain === '' || strlen($subdomain) < 2 || strlen($subdomain) > 48) {
    sa_json_response(400, ['status' => 'error', 'message' => 'Invalid subdomain (use 2–48 letters, numbers, hyphens).']);
}
if (in_array($subdomain, sa_reserved_subdomains_list(), true)) {
    sa_json_response(400, ['status' => 'error', 'message' => 'This subdomain is reserved. Choose another.']);
}

$mapSnap = firebase_rtdb_get($dbUrl, 'publicSiteMappings/' . $subdomain, $accessToken);
if (isset($mapSnap['error'])) {
    sa_json_response(500, ['status' => 'error', 'message' => 'Could not check subdomain: ' . $mapSnap['error']]);
}
if (($mapSnap['data'] ?? null) !== null) {
    sa_json_response(409, ['status' => 'error', 'message' => 'Subdomain already in use.']);
}

if (!sa_create_site_rate_consume($cfg)) {
    sa_json_response(429, ['status' => 'error', 'message' => 'Too many site creations this hour. Try again later.']);
}

$auth = firebase_identity_sign_up_email($webKey, $adminEmail, $adminPassword);
if (isset($auth['error'])) {
    $code = (string) ($auth['firebaseCode'] ?? $auth['error']);
    if (stripos($code, 'EMAIL_EXISTS') !== false) {
        sa_json_response(409, ['status' => 'error', 'message' => 'This email is already registered in Firebase Auth.']);
    }
    if (stripos($code, 'WEAK_PASSWORD') !== false) {
        sa_json_response(400, ['status' => 'error', 'message' => 'Firebase rejected the password as too weak.']);
    }
    sa_json_response(400, ['status' => 'error', 'message' => 'Auth error: ' . $auth['error']]);
}

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

$record = sa_build_new_client_record($siteName, $subdomain, $logoUrl, $bannerUrl, $phone, $adminEmail, $activeDesign);
$record = sa_merge_admin_into_record($record, $uid, $adminEmail);

$postRes = firebase_rtdb_post($dbUrl, 'clients', $accessToken, $record);
if (isset($postRes['error']) || (($postRes['http'] ?? 500) >= 400)) {
    if ($idToken !== '') {
        firebase_identity_delete_account($webKey, $idToken);
    }
    $err = $postRes['error'] ?? ('HTTP ' . ($postRes['http'] ?? ''));
    sa_json_response(500, ['status' => 'error', 'message' => 'Failed to create client record: ' . $err]);
}

$clientId = sa_parse_rtdb_post_name($postRes['data']['name'] ?? '');
if ($clientId === '') {
    if ($idToken !== '') {
        firebase_identity_delete_account($webKey, $idToken);
    }
    sa_json_response(500, ['status' => 'error', 'message' => 'Could not read new client id from database.']);
}

$emailKey = sa_sanitize_email_key($adminEmail);
$siteStub = ['subdomain' => $subdomain, 'siteName' => $siteName];
$patch = [
    'publicSiteMappings/' . $subdomain => $clientId,
    'userSites/' . $uid . '/' . $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, $accessToken);
    if ($idToken !== '') {
        firebase_identity_delete_account($webKey, $idToken);
    }
    $err = $patchRes['error'] ?? ('HTTP ' . ($patchRes['http'] ?? ''));
    sa_json_response(500, ['status' => 'error', 'message' => 'Failed to link site mappings (rolled back): ' . $err]);
}

sa_audit_log($dbUrl, $accessToken, $actorUid, $actorEmail, 'create_client', $clientId, [
    'subdomain' => $subdomain,
    'adminEmail' => $adminEmail,
]);

$dashboardUrl = null;
$bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (is_readable($bootPath)) {
    $boot = include $bootPath;
    if (is_array($boot)) {
        $base = trim((string) ($boot['store_dashboard_base_url'] ?? ''));
        if ($base !== '') {
            $siteInfoJson = json_encode([
                'clientId' => $clientId,
                'subdomain' => $subdomain,
                'siteName' => $siteName,
            ], JSON_UNESCAPED_UNICODE);
            $dashboardUrl = rtrim($base, '/') . '/index.html#siteInfo=' . rawurlencode($siteInfoJson);
        }
    }
}

sa_json_response(200, [
    'status' => 'success',
    'message' => 'Site created.',
    'clientId' => $clientId,
    'subdomain' => $subdomain,
    'adminUid' => $uid,
    'dashboardUrl' => $dashboardUrl,
]);
