<?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';
require_once __DIR__ . '/../includes/auth.php';

$token = requireAuth();
$userId = getUserId($token);
$db = supabase($token);

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET' || ($_SERVER['REQUEST_METHOD'] === 'POST' && (getInput()['action'] ?? '') === 'list')) {
    $items = $db->get('cosmetics', ['select' => 'id,name,type,rarity,price_coins,price_gems,description', 'order' => 'price_coins.asc']);
    jsonResponse(['items' => is_array($items) && !isset($items['error']) ? $items : []]);
}

$input = getInput();
$action = $input['action'] ?? '';

if ($action === 'purchase') {
    $cosmeticId = $input['cosmetic_id'] ?? '';
    if (!$cosmeticId) jsonError('cosmetic_id required');

    $items = $db->get('cosmetics', ['id' => 'eq.' . $cosmeticId, 'limit' => 1]);
    $item = is_array($items) && !empty($items) && !isset($items['error']) ? $items[0] : null;
    if (!$item) jsonError('Item not found', 404);

    $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'coins,gems', 'limit' => 1]);
    $profile = is_array($profiles) && !empty($profiles) ? $profiles[0] : ['coins' => 0, 'gems' => 0];
    $coins = $profile['coins'] ?? 0;
    $gems = $profile['gems'] ?? 0;
    $priceCoin = $item['price_coins'] ?? 0;
    $priceGem = $item['price_gems'] ?? 0;

    if ($priceCoin > 0 && $coins < $priceCoin) jsonError('Insufficient coins');
    if ($priceGem > 0 && $gems < $priceGem) jsonError('Insufficient gems');

    $owned = $db->get('player_cosmetics', ['player_id' => 'eq.' . $userId, 'cosmetic_id' => 'eq.' . $cosmeticId, 'select' => 'id']);
    if (!empty($owned) && !isset($owned['error'])) jsonError('Already owned');

    if ($priceCoin > 0) {
        $db->update('profiles', ['coins' => $coins - $priceCoin], ['id' => 'eq.' . $userId]);
    }
    if ($priceGem > 0) {
        $db->update('profiles', ['gems' => $gems - $priceGem], ['id' => 'eq.' . $userId]);
    }

    $db->insert('player_cosmetics', ['player_id' => $userId, 'cosmetic_id' => $cosmeticId, 'is_equipped' => false]);

    $sdb = supabaseService();
    $sdb->insert('economy_transactions', [
        'player_id' => $userId,
        'type' => 'purchase',
        'currency' => $priceCoin > 0 ? 'coins' : 'gems',
        'amount' => -($priceCoin > 0 ? $priceCoin : $priceGem),
        'balance_after' => $priceCoin > 0 ? ($coins - $priceCoin) : ($gems - $priceGem),
        'description' => 'Purchase: ' . ($item['name'] ?? $cosmeticId)
    ]);

    jsonResponse(['success' => true, 'item' => $item]);
}

if ($action === 'equip') {
    $cosmeticId = $input['cosmetic_id'] ?? '';
    if (!$cosmeticId) jsonError('cosmetic_id required');

    $item = $db->getOne('cosmetics', ['id' => 'eq.' . $cosmeticId, 'select' => 'type']);
    if (!$item) jsonError('Item not found', 404);

    $db->update('player_cosmetics', ['is_equipped' => false], ['player_id' => 'eq.' . $userId, 'cosmetic_id' => "not.eq.{$cosmeticId}"]);
    $db->update('player_cosmetics', ['is_equipped' => true], ['player_id' => 'eq.' . $userId, 'cosmetic_id' => 'eq.' . $cosmeticId]);

    jsonResponse(['success' => true]);
}

jsonError('Invalid action');
