<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';
header('Cache-Control: no-cache, must-revalidate');

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

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Public endpoint — returns full theme + assets for player app
    $sdb = supabaseService();

    // Get all theme values
    $themeRows = $sdb->get('platform_theme', ['select' => 'id,value,category']);
    $theme = [];
    if (is_array($themeRows) && !isset($themeRows['error'])) {
        foreach ($themeRows as $row) {
            $theme[$row['id']] = $row['value'];
        }
    }

    // Get all assets
    $assetRows = $sdb->get('platform_assets', ['select' => 'id,asset_url,dimensions']);
    $assets = [];
    if (is_array($assetRows) && !isset($assetRows['error'])) {
        foreach ($assetRows as $row) {
            if ($row['asset_url']) {
                $assets[$row['id']] = $row['asset_url'];
            }
        }
    }

    $theme['assets'] = $assets;
    echo json_encode($theme, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($method === 'POST') {
    // Admin endpoint — saves theme values to Supabase
    $input = getInput();
    $action = $input['action'] ?? '';

    $sdb = supabaseService();

    if ($action === 'save_theme') {
        $values = $input['values'] ?? [];
        foreach ($values as $key => $value) {
            if (empty($key) || $value === null) continue;
            $existing = $sdb->get('platform_theme', ['id' => 'eq.' . $key, 'select' => 'id', 'limit' => 1]);
            if (!empty($existing) && !isset($existing['error'])) {
                $sdb->update('platform_theme', ['value' => $value], ['id' => 'eq.' . $key]);
            } else {
                $sdb->insert('platform_theme', [
                    'id' => $key,
                    'category' => categorizeKey($key),
                    'group_name' => 'player_app',
                    'label' => $key,
                    'value' => $value,
                    'default_value' => $value,
                    'value_type' => (strpos($value, '#') === 0) ? 'hex' : 'string'
                ]);
            }
        }
        // Also update local theme.json so admin page stays in sync
        $themeFile = __DIR__ . '/../public/assets/brand/theme.json';
        $brandDir = dirname($themeFile);
        if (!is_dir($brandDir)) mkdir($brandDir, 0777, true);
        $local = file_exists($themeFile) ? (json_decode(file_get_contents($themeFile), true) ?: []) : [];
        $local = array_merge($local, $values);
        file_put_contents($themeFile, json_encode($local, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        jsonResponse(['success' => true]);
    }

    if ($action === 'save_asset') {
        $slot = $input['slot'] ?? '';
        $url = $input['url'] ?? '';
        if (!$slot) jsonError('slot required');

        $existing = $sdb->get('platform_assets', ['id' => 'eq.' . $slot, 'select' => 'id', 'limit' => 1]);
        if (!empty($existing) && !isset($existing['error'])) {
            $sdb->update('platform_assets', ['asset_url' => $url], ['id' => 'eq.' . $slot]);
        } else {
            $sdb->insert('platform_assets', [
                'id' => $slot,
                'category' => 'custom',
                'label' => $slot,
                'asset_url' => $url
            ]);
        }
        jsonResponse(['success' => true]);
    }

    jsonError('Invalid action');
}

function categorizeKey(string $key): string {
    if (strpos($key, 'bg_') === 0) return 'color';
    if (strpos($key, 'ludo_') === 0) return 'game';
    if (strpos($key, 'board_') === 0) return 'game';
    if (strpos($key, 'chess_') === 0) return 'game';
    if (strpos($key, 'anim_') === 0) return 'animation';
    if (strpos($key, 'btn_') === 0) return 'button';
    if (strpos($key, 'juice_') === 0) return 'juice';
    return 'color';
}
