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

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

if (!check_feature_flag('cosmetics_shop_enabled')) {
    http_response_code(403);
    echo json_encode(['error' => 'feature_disabled', 'message' => 'المتجر معطل حالياً']);
    exit;
}

$token = get_auth_token();

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $type = $_GET['type'] ?? 'board_theme';

    // Get cosmetics filtered by type, only purchasable items
    $res = supabase_rest('GET', "cosmetics?type=eq.{$type}&is_purchasable=eq.true&select=*&order=price_coins.asc", [], $token);
    $items = ($res['status'] === 200 && is_array($res['data']) && !isset($res['data']['code'])) ? $res['data'] : [];

    if (!empty($items)) {
        // Get owned cosmetics for the current user
        $ownedRes = supabase_rest('GET', 'player_cosmetics?select=cosmetic_id,is_equipped', [], $token);
        $ownedMap = [];
        if ($ownedRes['status'] === 200 && is_array($ownedRes['data'])) {
            foreach ($ownedRes['data'] as $pc) {
                $ownedMap[$pc['cosmetic_id']] = $pc['is_equipped'] ?? false;
            }
        }
        foreach ($items as &$item) {
            $item['owned'] = isset($ownedMap[$item['id']]);
            $item['equipped'] = $ownedMap[$item['id']] ?? false;
        }
    }

    echo json_encode(['items' => $items]);

} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';

    if ($action === 'buy') {
        $cosmeticId = $input['item_id'] ?? '';

        // Fetch cosmetic details
        $itemRes = supabase_rest('GET', "cosmetics?id=eq.{$cosmeticId}&select=*", [], $token);
        if (empty($itemRes['data'])) {
            http_response_code(404);
            echo json_encode(['error' => 'item not found']);
            exit;
        }
        $item = $itemRes['data'][0];

        if (!($item['is_purchasable'] ?? false)) {
            http_response_code(400);
            echo json_encode(['error' => 'هذا العنصر غير متاح للشراء']);
            exit;
        }

        // Check if already owned
        $ownedCheck = supabase_rest('GET', "player_cosmetics?cosmetic_id=eq.{$cosmeticId}&select=id", [], $token);
        if (!empty($ownedCheck['data'])) {
            http_response_code(400);
            echo json_encode(['error' => 'أنت تملك هذا العنصر بالفعل']);
            exit;
        }

        // Get player profile
        $profileRes = supabase_rest('GET', 'profiles?select=id,coins,gems', [], $token);
        if (empty($profileRes['data'])) {
            http_response_code(400);
            echo json_encode(['error' => 'profile not found']);
            exit;
        }
        $profile = $profileRes['data'][0];

        // Determine currency: prefer gems if price_gems is set and coins price is 0 or null
        $priceCoins = $item['price_coins'] ?? 0;
        $priceGems = $item['price_gems'] ?? 0;

        // Use coins by default, use gems if specified in request
        $useCurrency = $input['currency'] ?? 'coins';

        if ($useCurrency === 'gems' && $priceGems > 0) {
            if (($profile['gems'] ?? 0) < $priceGems) {
                http_response_code(400);
                echo json_encode(['error' => 'رصيد الجواهر غير كافي']);
                exit;
            }
            $newBalance = ($profile['gems'] ?? 0) - $priceGems;
            $deductCurrency = 'gems';
            $deductPrice = $priceGems;
            // Deduct gems
            supabase_rest('PATCH', 'profiles?id=eq.' . $profile['id'], [
                'gems' => $newBalance
            ], $token);
        } else {
            if (($profile['coins'] ?? 0) < $priceCoins) {
                http_response_code(400);
                echo json_encode(['error' => 'رصيد العملات غير كافي']);
                exit;
            }
            $newBalance = ($profile['coins'] ?? 0) - $priceCoins;
            $deductCurrency = 'coins';
            $deductPrice = $priceCoins;
            // Deduct coins
            supabase_rest('PATCH', 'profiles?id=eq.' . $profile['id'], [
                'coins' => $newBalance
            ], $token);
        }

        // Insert into player_cosmetics
        $insertRes = supabase_rest('POST', 'player_cosmetics', [
            'player_id' => $profile['id'],
            'cosmetic_id' => $cosmeticId,
            'acquired_via' => 'purchase',
            'is_equipped' => false,
        ], $token);

        if ($insertRes['status'] >= 400) {
            http_response_code(400);
            echo json_encode(['error' => 'فشل في إتمام الشراء']);
            exit;
        }

        // Log economy_transaction for shop purchase
        supabase_rest('POST', 'economy_transactions', [
            'player_id' => $profile['id'],
            'type' => 'shop_purchase',
            'currency' => $deductCurrency,
            'amount' => -$deductPrice,
            'balance_after' => $newBalance,
            'reason' => 'Purchased cosmetic: ' . ($item['name'] ?? $cosmeticId),
            'source_id' => $cosmeticId,
        ], SUPABASE_SERVICE_KEY);

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

    } elseif ($action === 'equip') {
        $cosmeticId = $input['item_id'] ?? '';
        $equip = $input['equip'] ?? true;

        // Get the cosmetic type to unequip others of same type
        $itemRes = supabase_rest('GET', "cosmetics?id=eq.{$cosmeticId}&select=type", [], $token);
        if (empty($itemRes['data'])) {
            http_response_code(404);
            echo json_encode(['error' => 'item not found']);
            exit;
        }
        $cosmeticType = $itemRes['data'][0]['type'];

        // Get player_id
        $profileRes = supabase_rest('GET', 'profiles?select=id', [], $token);
        if (empty($profileRes['data'])) {
            http_response_code(400);
            echo json_encode(['error' => 'profile not found']);
            exit;
        }
        $playerId = $profileRes['data'][0]['id'];

        if ($equip) {
            // Unequip all cosmetics of same type for this player
            // Get all equipped cosmetics of same type
            $equippedRes = supabase_rest('GET', "player_cosmetics?player_id=eq.{$playerId}&is_equipped=eq.true&select=id,cosmetic_id", [], $token);
            if (!empty($equippedRes['data'])) {
                foreach ($equippedRes['data'] as $equipped) {
                    // Check if this cosmetic is of the same type
                    $typeCheck = supabase_rest('GET', "cosmetics?id=eq.{$equipped['cosmetic_id']}&type=eq.{$cosmeticType}&select=id", [], $token);
                    if (!empty($typeCheck['data'])) {
                        supabase_rest('PATCH', "player_cosmetics?id=eq.{$equipped['id']}", [
                            'is_equipped' => false
                        ], $token);
                    }
                }
            }

            // Equip the selected cosmetic
            supabase_rest('PATCH', "player_cosmetics?player_id=eq.{$playerId}&cosmetic_id=eq.{$cosmeticId}", [
                'is_equipped' => true
            ], $token);
        } else {
            // Unequip
            supabase_rest('PATCH', "player_cosmetics?player_id=eq.{$playerId}&cosmetic_id=eq.{$cosmeticId}", [
                'is_equipped' => false
            ], $token);
        }

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

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