<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
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;
            // Upsert: try update first, if no rows affected, insert
            $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'
                ]);
            }
        }
        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';
}
