<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';

$db = supabaseService();
$gameKey = $_GET['game_key'] ?? null;
$orgId = $_GET['org_id'] ?? null;

$theme = [];

$platform = $db->get('platform_theme', ['select' => 'key,value', 'limit' => 50]);
if (is_array($platform) && !isset($platform['error'])) {
    foreach ($platform as $row) {
        $theme[$row['key']] = $row['value'];
    }
}

if ($gameKey) {
    $gameTheme = $db->get('game_theme_overrides', ['game_key' => 'eq.' . $gameKey, 'select' => 'key,value']);
    if (is_array($gameTheme) && !isset($gameTheme['error'])) {
        foreach ($gameTheme as $row) {
            $theme[$row['key']] = $row['value'];
        }
    }
}

if ($orgId) {
    $orgTheme = $db->get('org_theme_overrides', ['org_id' => 'eq.' . $orgId, 'select' => 'key,value']);
    if (is_array($orgTheme) && !isset($orgTheme['error'])) {
        foreach ($orgTheme as $row) {
            $theme[$row['key']] = $row['value'];
        }
    }
}

echo json_encode(['theme' => $theme], JSON_UNESCAPED_UNICODE);
