<?php
/**
 * cPanel SSR entry: serves shop-classic.html / shop-default.html with inline
 * window.__INITIAL_STATE__ for first paint (tenant-specific).
 *
 * Routing: .htaccess rewrites shop-classic.html / shop-default.html here.
 * Requires api/firebase-admin-bootstrap.local.php + service account JSON on server.
 */

declare(strict_types=1);

$root = __DIR__;
$theme = isset($_GET['ssr_theme']) && $_GET['ssr_theme'] === 'default' ? 'default' : 'classic';
$htmlFile = $theme === 'default' ? $root . DIRECTORY_SEPARATOR . 'shop-default.html' : $root . DIRECTORY_SEPARATOR . 'shop-classic.html';

if (!is_readable($htmlFile)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Shop HTML template not found.';
    exit;
}

require_once $root . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'firebase-rtdb-admin.php';
require_once $root . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'ssr-shop-bootstrap.inc.php';

$initialJson = null;
$cfg = ssr_shop_load_firebase_config();
$siteKey = ssr_shop_resolve_site_key();

if ($cfg && $siteKey !== '') {
    $cacheKey = null;
    $tokenRes = firebase_service_account_access_token($cfg['service_account_json_path']);
    if (empty($tokenRes['error']) && !empty($tokenRes['access_token'])) {
        $token = (string) $tokenRes['access_token'];
        $dbUrl = (string) $cfg['firebase_database_url'];
        $resolved = ssr_shop_resolve_client_id($dbUrl, $token, $siteKey);
        if (empty($resolved['error']) && !empty($resolved['clientId'])) {
            $clientId = (string) $resolved['clientId'];
            $cacheKey = ssr_shop_cache_key($clientId, $siteKey);
            $cached = ssr_shop_cache_get($cacheKey, 90);
            if (is_array($cached) && isset($cached['clientId'], $cached['settings'])
                && is_array($cached['productsVal'] ?? null) && count($cached['productsVal']) > 0) {
                $initialJson = $cached;
            } else {
                $built = ssr_shop_build_initial_state($clientId, $dbUrl, $token, 10);
                if (!empty($built['payload'])) {
                    $pv = $built['payload']['productsVal'] ?? [];
                    if (is_array($pv) && count($pv) > 0) {
                        $initialJson = $built['payload'];
                        ssr_shop_cache_set($cacheKey, $initialJson);
                    }
                }
            }
        }
    }
}

$html = file_get_contents($htmlFile);
if (!is_string($html)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Could not read shop template.';
    exit;
}

if ($initialJson !== null) {
    $json = json_encode($initialJson, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS);
    if ($json !== false) {
        $inject = '<script>window.__INITIAL_STATE__=' . $json . ';</script>';
        $pos = stripos($html, '</head>');
        if ($pos !== false) {
            $html = substr($html, 0, $pos) . $inject . "\n" . substr($html, $pos);
        } else {
            $html = $inject . "\n" . $html;
        }
    }
}

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
echo $html;
