<?php
// Default Steam API Key (replace with your own or leave blank)
define('DEFAULT_STEAM_API_KEY', 'YOUR_STEAM_API_KEY');

// Function to extract the last part of the URL path (the game title)
function extractTitleFromUrl($url) {
    $parts = parse_url($url);
    $path = rtrim($parts['path'], '/');
    $segments = explode('/', $path);
    return end($segments);
}

// Function to decode Unicode escape sequences in price
function decodeUnicode($string) {
    return preg_replace_callback('/\\\u([a-fA-F0-9]{4})/', function ($matches) {
        return mb_convert_encoding(pack('H*', $matches[1]), 'UTF-8', 'UCS-2BE');
    }, $string);
}

// Function to fetch Steam Deck compatibility data
function fetchSteamDeckCompatibility($appId) {
    $urlDeck = "https://store.steampowered.com/saleaction/ajaxgetdeckappcompatibilityreport?nAppID={$appId}";
    
    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"
        ]
    ]);
    
    $deckJson = @file_get_contents($urlDeck, false, $context);

    if ($deckJson) {
        $deckData = json_decode($deckJson, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            $deckCompatibility = 'Not Available';
            $deckResult = '';

            if (isset($deckData['results']['resolved_items'][0])) {
                $resolvedItem = $deckData['results']['resolved_items'][0];
                $deckCompatibility = $resolvedItem['loc_token'] ?? 'Not Available';
            }

            return [
                'deck_compat' => $deckCompatibility,
                'deck_result' => $deckResult
            ];
        }
    }

    return [
        'deck_compat' => 'Not Available',
        'deck_result' => 'No Result Data'
    ];
}

// Function to format bytes into human-readable format (MB/GB)
function formatFileSize($bytes) {
    if (!is_numeric($bytes) || $bytes <= 0) return 'Size Not Available';
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 1) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 1) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 1) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}

// IMPROVED filesize detection that properly extracts storage from system requirements
function fetchFileSize($appId) {
    $context = stream_context_create([
        'http' => [
            'timeout' => 15,
            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"
        ]
    ]);
    
    // Method 1: SteamDB API (most reliable)
    $steamDbUrl = "https://steamdb.info/api/GetAppSize/?appid={$appId}";
    $steamDbResponse = @file_get_contents($steamDbUrl, false, $context);
    
    if ($steamDbResponse !== false) {
        $steamDbData = json_decode($steamDbResponse, true);
        if (isset($steamDbData['success']) && $steamDbData['success'] && isset($steamDbData['data']['size'])) {
            $size = $steamDbData['data']['size'];
            if ($size > 0) {
                return formatFileSize($size);
            }
        }
    }
    
    // Method 2: Steam API with proper storage extraction from system requirements
    $apiUrl = "https://store.steampowered.com/api/appdetails?appids={$appId}";
    $response = @file_get_contents($apiUrl, false, $context);
    
    if ($response !== false) {
        $data = json_decode($response, true);
        
        if (isset($data[$appId]['success']) && $data[$appId]['success'] && isset($data[$appId]['data'])) {
            $gameData = $data[$appId]['data'];
            
            // Check for direct size fields first
            $sizeFields = ['package_size', 'install_size', 'size_on_disk', 'content_size'];
            foreach ($sizeFields as $field) {
                if (isset($gameData[$field]) && $gameData[$field] > 0) {
                    return formatFileSize($gameData[$field]);
                }
            }
            
            // NEW: Extract storage from system requirements HTML
            $storageSize = extractStorageFromRequirements($gameData);
            if ($storageSize !== null) {
                return $storageSize;
            }
        }
    }
    
    return 'Size Not Available';
}

// NEW FUNCTION: Extract storage size from system requirements HTML
function extractStorageFromRequirements($gameData) {
    // Check both minimum and recommended requirements
    $requirementSections = [];
    
    if (isset($gameData['pc_requirements']['minimum'])) {
        $requirementSections[] = $gameData['pc_requirements']['minimum'];
    }
    if (isset($gameData['pc_requirements']['recommended'])) {
        $requirementSections[] = $gameData['pc_requirements']['recommended'];
    }
    
    foreach ($requirementSections as $requirements) {
        // Look for storage patterns in multiple languages
        $storagePatterns = [
            // German: "Speicherplatz: 50 GB verfügbarer Speicherplatz"
            '/Speicherplatz:.*?(\d+(?:\.\d+)?)\s*GB/i',
            '/Speicherplatz.*?(\d+(?:\.\d+)?)\s*GB/i',
            
            // English: "Storage: 50 GB available space"
            '/Storage:.*?(\d+(?:\.\d+)?)\s*GB/i',
            '/Storage.*?(\d+(?:\.\d+)?)\s*GB/i',
            
            // Space in multiple languages
            '/Space:.*?(\d+(?:\.\d+)?)\s*GB/i',
            '/space.*?(\d+(?:\.\d+)?)\s*GB/i',
            '/speicherplatz.*?(\d+(?:\.\d+)?)\s*GB/i',
            
            // Generic GB patterns that likely indicate storage
            '/(\d+(?:\.\d+)?)\s*GB.*storage/i',
            '/(\d+(?:\.\d+)?)\s*GB.*space/i',
            '/(\d+(?:\.\d+)?)\s*GB.*speicherplatz/i',
            
            // HDD/SSD requirements
            '/(\d+(?:\.\d+)?)\s*GB.*HDD/i',
            '/(\d+(?:\.\d+)?)\s*GB.*SSD/i',
        ];
        
        foreach ($storagePatterns as $pattern) {
            if (preg_match($pattern, $requirements, $matches)) {
                $sizeGB = floatval($matches[1]);
                if ($sizeGB > 0) {
                    return number_format($sizeGB, 1) . ' GB';
                }
            }
        }
        
        // Also check for MB patterns (convert to GB if large enough)
        $mbPatterns = [
            '/(\d+)\s*MB.*storage/i',
            '/(\d+)\s*MB.*space/i',
            '/Storage:.*?(\d+)\s*MB/i',
        ];
        
        foreach ($mbPatterns as $pattern) {
            if (preg_match($pattern, $requirements, $matches)) {
                $sizeMB = intval($matches[1]);
                if ($sizeMB > 1000) { // Convert to GB if over 1GB
                    return number_format($sizeMB / 1024, 1) . ' GB';
                } elseif ($sizeMB > 0) {
                    return number_format($sizeMB, 1) . ' MB';
                }
            }
        }
    }
    
    return null;
}

// Function to get price using Steam API and filesize using reliable sources
function fetchGameDetailsFromSteamApi($appId, $apiKey, $cc = 'USD', $lang = 'en') {
    $url = "https://store.steampowered.com/api/appdetails?appids={$appId}&cc={$cc}&l={$lang}";
    $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);
    
    $price = 'Price Not Available';
    $filesize = fetchFileSize($appId); // Get filesize from reliable source

    if ($response !== false) {
        $data = json_decode($response, true);

        if (isset($data[$appId]['success']) && $data[$appId]['success'] && isset($data[$appId]['data'])) {
            $gameData = $data[$appId]['data'];

            // Get price
            if (isset($gameData['price_overview'])) {
                $price = decodeUnicode($gameData['price_overview']['final_formatted']);
            } elseif (isset($gameData['is_free']) && $gameData['is_free']) {
                $price = 'Free';
            }
        }
    }

    return [
        'price' => $price,
        'filesize' => $filesize
    ];
}

// Function to check if the URL already exists in the JSON data
function isDuplicate($url, $data) {
    foreach ($data as $item) {
        if ($item['url'] === $url) {
            return true;
        }
    }
    return false;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['url'])) {
    $url = trim($_POST['url']);
    
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        $title = extractTitleFromUrl($url);

        // Extract the app ID from the URL
        preg_match('/\/app\/(\d+)\//', $url, $matches);
        $appId = $matches[1] ?? null;

        if ($appId) {
            $apiKey = isset($_GET['api_key']) ? $_GET['api_key'] : DEFAULT_STEAM_API_KEY;
            $cc = isset($_POST['currency']) ? $_POST['currency'] : 'USD';
            $lang = isset($_POST['language']) ? $_POST['language'] : 'en';

            // Fetch data
            $gameDetails = fetchGameDetailsFromSteamApi($appId, $apiKey, $cc, $lang);
            $deckDetails = fetchSteamDeckCompatibility($appId);

            $currentDate = date('Y-m-d H:i:s');
            $gameData = [
                'url' => $url,
                'title' => $title,
                'price' => $gameDetails['price'],
                'steamDeckCompatibility' => $deckDetails['deck_compat'],
                'filesize' => $gameDetails['filesize'],
                'deck_result' => $deckDetails['deck_result'],
                'date' => $currentDate
            ];

            $jsonFile = 'games_data.json';
            $data = file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [];

            if (!isDuplicate($url, $data)) {
                $data[] = $gameData;
                file_put_contents($jsonFile, json_encode($data, JSON_PRETTY_PRINT));
                echo "<div class='success'><p>Data for <strong>{$title}</strong> has been added to the JSON file.</p>";
                echo "<p>Price: <strong>{$gameDetails['price']}</strong> | Size: <strong>{$gameDetails['filesize']}</strong> | Deck Compatibility: <strong>{$deckDetails['deck_compat']}</strong></p></div>";
            } else {
                echo "<div class='warning'><p>Data for <strong>{$title}</strong> already exists. No duplicate added.</p></div>";
            }
        } else {
            echo "<div class='error'><p>Could not extract App ID from the URL.</p></div>";
        }
    } else {
        echo "<div class='error'><p>Invalid URL. Please enter a valid URL.</p></div>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Steam Game Logger - Fixed Storage Detection</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
        form { margin: 20px 0; padding: 20px; border: 1px solid #ddd; background: #f9f9f9; border-radius: 5px; }
        label { display: inline-block; width: 150px; margin-right: 10px; font-weight: bold; }
        input[type="text"] { padding: 8px; margin: 5px 0; border: 1px solid #ccc; border-radius: 3px; }
        button { padding: 10px 20px; background: #007cba; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 16px; }
        button:hover { background: #005a87; }
        .info { background: #e7f3ff; padding: 15px; margin: 15px 0; border-left: 4px solid #007cba; border-radius: 3px; }
        .success { background: #e7ffe7; padding: 15px; margin: 15px 0; border-left: 4px solid #00ba07; border-radius: 3px; }
        .warning { background: #fffae7; padding: 15px; margin: 15px 0; border-left: 4px solid #baa300; border-radius: 3px; }
        .error { background: #ffe7e7; padding: 15px; margin: 15px 0; border-left: 4px solid #ba0000; border-radius: 3px; }
    </style>
</head>
<body>
    <h1>Steam Game Logger - Fixed Storage Detection</h1>
    
    <div class="info">
        <strong>Now properly extracts storage size from system requirements</strong><br>
        • Detects "Speicherplatz: 50 GB" (German for storage)<br>
        • Also works with English "Storage: 50 GB"<br>
        • Handles multiple languages and formats<br>
        • Silent Hill 2 should now show: <strong>50.0 GB</strong><br>
        <em>Test URL: https://store.steampowered.com/app/2124490/SILENT_HILL_2/</em>
    </div>
    
    <form method="POST">
        <div>
            <label for="currency">Currency Code:</label>
            <input type="text" name="currency" id="currency" value="EUR" style="width: 100px;">
            <small>(e.g., USD, EUR, GBP)</small>
        </div>
        <div>
            <label for="language">Language:</label>
            <input type="text" name="language" id="language" value="en" style="width: 100px;">
            <small>(e.g., en, fr, de)</small>
        </div>
        <div>
            <label for="url">Steam Game URL:</label>
            <input type="text" name="url" id="url" placeholder="https://store.steampowered.com/app/2124490/SILENT_HILL_2/" required style="width: 500px;">
        </div>
        <div>
            <button type="submit">Add Game to List</button>
        </div>
    </form>
    
    <?php
    $jsonFile = 'games_data.json';
    if (file_exists($jsonFile)) {
        $data = json_decode(file_get_contents($jsonFile), true);
        if (!empty($data)) {
            echo "<div class='info'>";
            echo "<h3>Recent Entries:</h3>";
            $recent = array_slice($data, -3);
            foreach ($recent as $entry) {
                echo "<p><strong>{$entry['title']}</strong> - Price: {$entry['price']} - Size: {$entry['filesize']} - Deck: {$entry['steamDeckCompatibility']}</p>";
            }
            echo "</div>";
        }
    }
    ?>
</body>
</html>