<?php
/**
 * Loads theme overrides from DB and outputs a <style> block with CSS variable overrides.
 * Caches in a local file for 60 seconds to avoid hitting Supabase on every request.
 */

require_once __DIR__ . '/../config/database.php';

function get_theme_overrides(): array {
    $cacheFile = __DIR__ . '/../storage/theme-cache.json';
    $cacheTTL = 60;

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTTL) {
        $cached = json_decode(file_get_contents($cacheFile), true);
        if (is_array($cached)) return $cached;
    }

    $res = supabase_rest('GET', 'theme_settings?select=key,value,category', [], SUPABASE_SERVICE_KEY);
    $settings = ($res['status'] === 200 && is_array($res['data']) && !isset($res['data']['code'])) ? $res['data'] : [];

    $cacheDir = dirname($cacheFile);
    if (!is_dir($cacheDir)) mkdir($cacheDir, 0755, true);
    file_put_contents($cacheFile, json_encode($settings));

    return $settings;
}

function render_theme_style(): void {
    $settings = get_theme_overrides();
    if (empty($settings)) return;

    $cssVars = [];
    $assetOverrides = [];

    foreach ($settings as $s) {
        $key = $s['key'];
        $value = $s['value'];
        $category = $s['category'];

        if ($category === 'assets' || $category === 'icons' || $category === 'pieces') {
            $assetOverrides[$key] = $value;
        } else {
            $cssVars[] = '  --' . htmlspecialchars($key) . ': ' . htmlspecialchars($value) . ';';
        }
    }

    if (!empty($cssVars)) {
        echo "<style id=\"theme-overrides\">\n:root {\n" . implode("\n", $cssVars) . "\n}\n</style>\n";
    }

    if (!empty($assetOverrides)) {
        echo "<script>window.__themeAssets = " . json_encode($assetOverrides) . ";</script>\n";
    }
}

render_theme_style();
