<details><summary>(+)</summary>
   <script>
        function stringToArrayBuffer(str) {
            var encoder = new TextEncoder();
            return encoder.encode(str);
        }
        function arrayBufferToString(buffer) {
            var decoder = new TextDecoder();
            return decoder.decode(buffer);
        }
        async function decryptAES(ciphertext, key, iv) {
            var decrypted = await crypto.subtle.decrypt(
                {
                    name: "AES-CBC",
                    iv: iv
                },
                key,
                ciphertext
            );
            return new Uint8Array(decrypted);
        }
        async function handleDecrypt(event) {
            event.preventDefault();
            var password = document.getElementById("password").value;
            var encryptedHex = document.getElementById("encryptedOutput").value;
            var passwordBuffer = stringToArrayBuffer(password);
            var keyMaterial = await crypto.subtle.importKey(
                "raw",
                passwordBuffer,
                { name: "PBKDF2" },
                false,
                ["deriveKey"]
            );
            var aesKey = await crypto.subtle.deriveKey(
                {
                    name: "PBKDF2",
                    salt: new Uint8Array(16), // Use a random salt for real-world scenarios
                    iterations: 100000,
                    hash: "SHA-256"
                },
                keyMaterial,
                { name: "AES-CBC", length: 256 },
                true,
                ["encrypt", "decrypt"]
            );
            var ivHex = encryptedHex.substr(0, 32);
            var ciphertextHex = encryptedHex.substr(32);
            var ivBytes = new Uint8Array(ivHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
            var ciphertextBytes = new Uint8Array(ciphertextHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
            var decryptedBytes = await decryptAES(ciphertextBytes, aesKey, ivBytes);
            var decryptedHTML = arrayBufferToString(decryptedBytes);
            document.getElementById("decryptedOutput").innerHTML = decryptedHTML;
        }
    </script>
    <form onsubmit="handleDecrypt(event)">
        <input type="password" id="password" required>
        <textarea id="encryptedOutput" rows="10" cols="50" style="display: none;">c987b42fefe6c78273c41b37e5f4cf0d1b43bbd3a209853c3e51e92cf2af1b12af4a85d1adac969930680f3cd3ad7b43448acbd7d2c1e439ff5046a9708090cc628117fa7cd9bf6dfb3a30efb51d4288704306b09c8c1a361226c5dda6d698e42aa9c892e0f676aaf82dcc76d686f799d3ba75ea34269243af35f95c72cbe5f65fe9503ad6bee79e5938b322b3d6e4f52ea79cc7841e491d92dd1847b135fdcd6de08d2076a85de4cb1060356a1b1dd0</textarea>
        <input type="submit" value="Decrypt">
</form><div><div id="decryptedOutput"></div></div></details>

<?php
// Price Comparison Script for Steam Games
define('DEFAULT_STEAM_API_KEY', 'YOUR_STEAM_API_KEY');

// Function to extract app ID from URL
function extractAppIdFromUrl($url) {
    preg_match('/\/app\/(\d+)\//', $url, $matches);
    return $matches[1] ?? null;
}

// Function to fetch current price from Steam API
function fetchCurrentPrice($appId, $cc = 'EUR', $lang = 'en') {
    $apiKey = DEFAULT_STEAM_API_KEY;
    $url = "https://store.steampowered.com/api/appdetails?appids={$appId}&cc={$cc}&l={$lang}&key={$apiKey}";
    
    $context = stream_context_create([
        'http' => [
            'timeout' => 15,
            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"
        ]
    ]);
    
    $response = @file_get_contents($url, false, $context);
    $data = json_decode($response, true);

    if (isset($data[$appId]['data'])) {
        $gameData = $data[$appId]['data'];
        
        if (isset($gameData['price_overview'])) {
            return [
                'final_formatted' => $gameData['price_overview']['final_formatted'],
                'final' => $gameData['price_overview']['final'],
                'discount_percent' => $gameData['price_overview']['discount_percent'],
                'initial_formatted' => $gameData['price_overview']['initial_formatted'],
                'initial' => $gameData['price_overview']['initial']
            ];
        } elseif (isset($gameData['is_free']) && $gameData['is_free']) {
            return [
                'final_formatted' => 'Free',
                'final' => 0,
                'discount_percent' => 0,
                'initial_formatted' => 'Free',
                'initial' => 0
            ];
        }
    }
    
    return null;
}

// Function to convert price string to numeric value
function priceToNumeric($priceString) {
    if ($priceString === 'Free') return 0;
    
    // Remove currency symbols and commas, keep only numbers and decimal separator
    $cleanPrice = preg_replace('/[^\d,\.]/', '', $priceString);
    
    // Handle European format (comma as decimal separator)
    if (strpos($cleanPrice, ',') !== false && strpos($cleanPrice, '.') !== false) {
        // If both comma and dot exist, comma is likely decimal separator
        $cleanPrice = str_replace('.', '', $cleanPrice); // Remove thousand separators
        $cleanPrice = str_replace(',', '.', $cleanPrice); // Convert comma to decimal point
    } elseif (strpos($cleanPrice, ',') !== false) {
        // Only comma exists - check if it's decimal or thousand separator
        $parts = explode(',', $cleanPrice);
        if (strlen(end($parts)) === 2) {
            // Last part is 2 digits, likely decimal
            $cleanPrice = str_replace(',', '.', $cleanPrice);
        } else {
            // Comma as thousand separator
            $cleanPrice = str_replace(',', '', $cleanPrice);
        }
    }
    
    return floatval($cleanPrice);
}

// Function to compare prices and detect drops
function comparePrices($storedPrice, $currentPrice) {
    $storedNumeric = priceToNumeric($storedPrice);
    $currentNumeric = priceToNumeric($currentPrice['final_formatted']);
    
    if ($storedNumeric === 0 && $currentNumeric === 0) {
        return ['status' => 'same', 'change' => 0, 'percent' => 0];
    }
    
    if ($storedNumeric > $currentNumeric) {
        $change = $storedNumeric - $currentNumeric;
        $percent = ($change / $storedNumeric) * 100;
        return [
            'status' => 'drop',
            'change' => $change,
            'percent' => round($percent, 1),
            'old_price' => $storedPrice,
            'new_price' => $currentPrice['final_formatted']
        ];
    } elseif ($storedNumeric < $currentNumeric) {
        $change = $currentNumeric - $storedNumeric;
        $percent = ($change / $storedNumeric) * 100;
        return [
            'status' => 'increase',
            'change' => $change,
            'percent' => round($percent, 1),
            'old_price' => $storedPrice,
            'new_price' => $currentPrice['final_formatted']
        ];
    } else {
        return ['status' => 'same', 'change' => 0, 'percent' => 0];
    }
}

// Function to format currency
function formatCurrency($amount, $currency = 'EUR') {
    $symbols = ['EUR' => '€', 'USD' => '$', 'GBP' => '£'];
    $symbol = $symbols[$currency] ?? $currency;
    
    return number_format($amount, 2, ',', '.') . $symbol;
}

// Main execution
$jsonFile = 'games_data.json';
$results = [];

if (file_exists($jsonFile)) {
    $data = json_decode(file_get_contents($jsonFile), true);
    
    if (!empty($data)) {
        echo "<!DOCTYPE html>
        <html lang='en'>
        <head>
            <meta charset='UTF-8'>
            <title>Steam Price Checker</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
                .container { max-width: 1200px; margin: 0 auto; }
                .game-card { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; }
                .price-drop { background: #e7ffe7; border-left: 4px solid #00ba07; }
                .price-increase { background: #ffe7e7; border-left: 4px solid #ba0000; }
                .no-change { background: #f0f0f0; border-left: 4px solid #666; }
                .error { background: #fffae7; border-left: 4px solid #baa300; }
                .price-badge { padding: 3px 8px; border-radius: 3px; font-weight: bold; }
                .drop { background: #00ba07; color: white; }
                .increase { background: #ba0000; color: white; }
                .same { background: #666; color: white; }
                .stats { background: #e7f3ff; padding: 15px; margin: 20px 0; border-radius: 5px; }
                .loading { color: #666; font-style: italic; }
                h1 { color: #333; }
                .game-title { font-size: 18px; font-weight: bold; margin-bottom: 5px; }
                .price-comparison { font-size: 16px; margin: 5px 0; }
                .discount { color: #00ba07; font-weight: bold; }
                .last-checked { font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class='container'>
                <h1>Steam Price Checker</h1>
                <div class='stats'>
                    <strong>Checking prices for " . count($data) . " games...</strong>
                    <p>Currency: EUR | Last updated: " . date('Y-m-d H:i:s') . "</p>
                </div>";
        
        $totalGames = count($data);
        $priceDrops = 0;
        $priceIncreases = 0;
        $noChanges = 0;
        $errors = 0;
        
        foreach ($data as $index => $game) {
            echo "<div class='game-card loading' id='game-{$index}'>";
            echo "Checking: <strong>{$game['title']}</strong>...";
            echo "</div>";
            
            // Flush output to show progress
            flush();
            ob_flush();
            
            $appId = extractAppIdFromUrl($game['url']);
            $currentPrice = fetchCurrentPrice($appId, 'EUR', 'en');
            
            if ($currentPrice) {
                $comparison = comparePrices($game['price'], $currentPrice);
                
                $statusClass = $comparison['status'] . '-change';
                if ($comparison['status'] === 'drop') $priceDrops++;
                elseif ($comparison['status'] === 'increase') $priceIncreases++;
                else $noChanges++;
                
                echo "<script>document.getElementById('game-{$index}').outerHTML = " . json_encode("
                    <div class='game-card {$statusClass}'>
                        <div class='game-title'>{$game['title']}</div>
                        <div class='price-comparison'>
                            Stored: {$game['price']} → Current: {$currentPrice['final_formatted']}
                            " . ($comparison['status'] !== 'same' ? 
                                "<span class='price-badge {$comparison['status']}'>" . 
                                strtoupper($comparison['status']) . " " . 
                                ($comparison['percent'] > 0 ? formatCurrency($comparison['change']) . " ({$comparison['percent']}%)" : '') . 
                                "</span>" : '') . "
                        </div>
                        " . ($currentPrice['discount_percent'] > 0 ? 
                            "<div class='discount'>🏷️ Currently {$currentPrice['discount_percent']}% off (Original: {$currentPrice['initial_formatted']})</div>" : '') . "
                        <div class='last-checked'>Last checked in database: {$game['date']}</div>
                        <div><small><a href='{$game['url']}' target='_blank'>View on Steam</a></small></div>
                    </div>
                ") . ";</script>";
                
                flush();
                ob_flush();
                
            } else {
                $errors++;
                echo "<script>document.getElementById('game-{$index}').outerHTML = " . json_encode("
                    <div class='game-card error'>
                        <div class='game-title'>{$game['title']}</div>
                        <div>❌ Could not fetch current price</div>
                        <div class='last-checked'>Stored price: {$game['price']} | Last checked: {$game['date']}</div>
                    </div>
                ") . ";</script>";
                
                flush();
                ob_flush();
            }
            
            // Small delay to avoid hitting rate limits
            usleep(500000); // 0.5 second delay
        }
        
        // Final statistics
        echo "<div class='stats'>
                <h3>Summary</h3>
                <p>Total Games: {$totalGames}</p>
                <p style='color: #00ba07;'>Price Drops: {$priceDrops}</p>
                <p style='color: #ba0000;'>Price Increases: {$priceIncreases}</p>
                <p style='color: #666;'>No Changes: {$noChanges}</p>
                <p style='color: #baa300;'>Errors: {$errors}</p>
            </div>";
        
        echo "</div></body></html>";
        
    } else {
        echo "<p>No game data found in the JSON file.</p>";
    }
} else {
    echo "<p>JSON file not found: {$jsonFile}</p>";
}
?>
