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

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $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'] : [];
    echo json_encode(['settings' => $settings]);
    exit;
}

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $adminUser = $input['admin_user'] ?? '';
    $adminPass = $input['admin_pass'] ?? '';

    if ($adminUser !== 'admin' || $adminPass !== 'Alarcade123#') {
        http_response_code(403);
        echo json_encode(['error' => 'forbidden']);
        exit;
    }

    $action = $input['action'] ?? '';

    if ($action === 'save') {
        $settings = $input['settings'] ?? [];
        $errors = [];

        foreach ($settings as $item) {
            $key = $item['key'] ?? '';
            $value = $item['value'] ?? '';
            $category = $item['category'] ?? 'colors';
            $label = $item['label'] ?? $key;

            if (!$key || !$value) continue;

            $existing = supabase_rest('GET', 'theme_settings?key=eq.' . urlencode($key) . '&select=id', [], SUPABASE_SERVICE_KEY);

            if (!empty($existing['data']) && is_array($existing['data']) && !isset($existing['data']['code'])) {
                $res = supabase_rest('PATCH', 'theme_settings?key=eq.' . urlencode($key), [
                    'value' => $value,
                    'category' => $category,
                    'label' => $label,
                    'updated_at' => date('c'),
                ], SUPABASE_SERVICE_KEY);
            } else {
                $res = supabase_rest('POST', 'theme_settings', [
                    'key' => $key,
                    'value' => $value,
                    'category' => $category,
                    'label' => $label,
                ], SUPABASE_SERVICE_KEY);
            }

            if ($res['status'] >= 400) {
                $errors[] = $key;
            }
        }

        echo json_encode(['ok' => true, 'errors' => $errors]);

    } elseif ($action === 'delete') {
        $key = $input['key'] ?? '';
        if ($key) {
            supabase_rest('DELETE', 'theme_settings?key=eq.' . urlencode($key), [], SUPABASE_SERVICE_KEY);
        }
        echo json_encode(['ok' => true]);

    } elseif ($action === 'upload') {
        echo json_encode(['error' => 'use /api/theme-upload for file uploads']);

    } else {
        echo json_encode(['error' => 'invalid action']);
    }
}
