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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'method not allowed']);
    exit;
}

$adminUser = $_POST['admin_user'] ?? '';
$adminPass = $_POST['admin_pass'] ?? '';

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

if (empty($_FILES['file'])) {
    http_response_code(400);
    echo json_encode(['error' => 'no file uploaded']);
    exit;
}

$file = $_FILES['file'];
$key = $_POST['key'] ?? '';
$category = $_POST['category'] ?? 'assets';

if (!$key) {
    http_response_code(400);
    echo json_encode(['error' => 'key is required']);
    exit;
}

$allowed = ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp', 'image/gif'];
if (!in_array($file['type'], $allowed)) {
    http_response_code(400);
    echo json_encode(['error' => 'invalid file type']);
    exit;
}

$maxSize = 2 * 1024 * 1024;
if ($file['size'] > $maxSize) {
    http_response_code(400);
    echo json_encode(['error' => 'file too large (max 2MB)']);
    exit;
}

$uploadDir = __DIR__ . '/../public/uploads/theme/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$safeKey = preg_replace('/[^a-zA-Z0-9_-]/', '_', $key);
$filename = $safeKey . '.' . $ext;
$destPath = $uploadDir . $filename;

if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    http_response_code(500);
    echo json_encode(['error' => 'upload failed']);
    exit;
}

$publicUrl = '/public/uploads/theme/' . $filename;

$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'])) {
    supabase_rest('PATCH', 'theme_settings?key=eq.' . urlencode($key), [
        'value' => $publicUrl,
        'category' => $category,
        'label' => $_POST['label'] ?? $key,
        'updated_at' => date('c'),
    ], SUPABASE_SERVICE_KEY);
} else {
    supabase_rest('POST', 'theme_settings', [
        'key' => $key,
        'value' => $publicUrl,
        'category' => $category,
        'label' => $_POST['label'] ?? $key,
    ], SUPABASE_SERVICE_KEY);
}

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