<?php
$pageTitle = 'Import Games';
ob_start();
?>

<div class="admin-card">
    <h2 class="text-xl font-semibold mb-4">Import Games</h2>
    <p class="text-gray-300 mb-6">Check for new games from GameMonetize, GamePix, and Gamezop. Only new games will be imported, existing games will be preserved.</p>

    <!-- Game Statistics Card -->
    <div class="bg-gradient-to-r from-dark to-card-bg p-5 rounded-xl border border-primary/20 mb-6">
        <div class="flex items-center mb-4">
            <i class="fas fa-chart-bar text-primary text-xl mr-3"></i>
            <h3 class="text-lg font-medium text-white">Game Statistics</h3>
        </div>

        <?php if (!empty($_GET['success'])): ?>
            <div class="bg-green-800 text-white p-4 rounded-md mb-4">
                <i class="fas fa-check-circle mr-2"></i> <?= htmlspecialchars($_GET['success']) ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($_GET['error'])): ?>
            <div class="bg-red-800 text-white p-4 rounded-md mb-4">
                <i class="fas fa-exclamation-circle mr-2"></i> <?= htmlspecialchars($_GET['error']) ?>
            </div>
        <?php endif; ?>

        <div id="gameStats" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">Total Games</div>
                <div class="text-2xl font-bold"><?= $totalGames ?></div>
            </div>
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">GameMonetize</div>
                <div class="text-2xl font-bold"><?= $gamemonetizeGames ?></div>
            </div>
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">GamePix</div>
                <div class="text-2xl font-bold"><?= $gamepixGames ?></div>
            </div>
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">Gamezop</div>
                <div class="text-2xl font-bold"><?= $gamezopGames ?></div>
            </div>
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">Categories</div>
                <div class="text-2xl font-bold"><?= $totalCategories ?></div>
            </div>
        </div>
    </div>

    <!-- Import Results Area (Updated via AJAX) -->
    <div id="importResults" class="bg-dark p-4 rounded-md border border-gray-800 mb-6 <?= isset($importResults) ? '' : 'hidden' ?>">
        <h3 class="text-lg font-medium mb-2 text-primary">Import Results</h3>
        <div id="importResultsContent">
            <?php if (isset($importResults)): ?>
                <?php if (isset($importResults['gamemonetize'])): ?>
                    <div class="mb-4">
                        <h4 class="text-white font-medium mb-1">GameMonetize</h4>
                        <p class="text-gray-300">
                            <?php if ($importResults['gamemonetize']['success']): ?>
                                <i class="fas fa-check-circle text-green-500 mr-2"></i>
                                <?= $importResults['gamemonetize']['message'] ?>
                            <?php else: ?>
                                <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                                Error: <?= $importResults['gamemonetize']['message'] ?>
                            <?php endif; ?>
                        </p>
                    </div>
                <?php endif; ?>

                <?php if (isset($importResults['gamepix'])): ?>
                    <div>
                        <h4 class="text-white font-medium mb-1">GamePix</h4>
                        <p class="text-gray-300">
                            <?php if ($importResults['gamepix']['success']): ?>
                                <i class="fas fa-check-circle text-green-500 mr-2"></i>
                                <?= $importResults['gamepix']['message'] ?>
                            <?php else: ?>
                                <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                                Error: <?= $importResults['gamepix']['message'] ?>
                            <?php endif; ?>
                        </p>
                    </div>
                <?php endif; ?>

                <?php if (isset($importResults['gamezop'])): ?>
                    <div>
                        <h4 class="text-white font-medium mb-1">Gamezop</h4>
                        <p class="text-gray-300">
                            <?php if ($importResults['gamezop']['success']): ?>
                                <i class="fas fa-check-circle text-green-500 mr-2"></i>
                                <?= $importResults['gamezop']['message'] ?>
                            <?php else: ?>
                                <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                                Error: <?= $importResults['gamezop']['message'] ?>
                            <?php endif; ?>
                        </p>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Live Log Area -->
    <div id="liveLogContainer" class="bg-dark p-4 rounded-md border border-gray-800 mb-6 hidden">
        <h3 class="text-lg font-medium mb-2 text-primary">Import Progress</h3>
        <div id="liveLog" class="bg-darker p-3 rounded-md border border-gray-700 h-48 overflow-y-auto font-mono text-sm text-gray-300">
            <!-- Live logs will be inserted here -->
        </div>
    </div>

    <div class="dashboard-grid">
        <div class="bg-dark p-4 rounded-md border border-gray-800">
            <h3 class="text-lg font-medium mb-2 text-primary">GameMonetize</h3>
            <p class="text-gray-300 mb-4">Check for new games from GameMonetize RSS feed.</p>

            <div class="flex flex-col space-y-2">
                <button type="button" class="admin-button check-games-btn" data-source="gamemonetize">
                    <i class="fas fa-search mr-2"></i> Check for New Games
                </button>

                <?php if ($gamemonetizeGames > 0): ?>
                <form action="/admin/games/delete-by-source" method="POST" onsubmit="return confirm('Are you sure you want to delete ALL GameMonetize games? This action cannot be undone.')">
                    <input type="hidden" name="source" value="gamemonetize">
                    <button type="submit" class="w-full bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium">
                        <i class="fas fa-trash mr-2"></i> Delete All Games
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="bg-dark p-4 rounded-md border border-gray-800">
            <h3 class="text-lg font-medium mb-2 text-primary">GamePix</h3>
            <p class="text-gray-300 mb-4">Check for new games from GamePix RSS feed.</p>

            <div class="mb-4">
                <label for="gamepixPage" class="block text-gray-300 mb-1">Page Number</label>
                <div class="flex">
                    <input type="number" id="gamepixPage" name="gamepixPage" value="1" min="1"
                           class="w-24 bg-darker border border-gray-700 rounded-md px-3 py-2 text-gray-300 focus:outline-none focus:border-primary">
                </div>
                <p class="text-sm text-gray-400 mt-1">Select the page number to import from</p>
            </div>

            <div class="flex flex-col space-y-2">
                <button type="button" class="admin-button check-games-btn" data-source="gamepix">
                    <i class="fas fa-search mr-2"></i> Check for New Games
                </button>

                <?php if ($gamepixGames > 0): ?>
                <form action="/admin/games/delete-by-source" method="POST" onsubmit="return confirm('Are you sure you want to delete ALL GamePix games? This action cannot be undone.')">
                    <input type="hidden" name="source" value="gamepix">
                    <button type="submit" class="w-full bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium">
                        <i class="fas fa-trash mr-2"></i> Delete All Games
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="bg-dark p-4 rounded-md border border-gray-800">
            <h3 class="text-lg font-medium mb-2 text-primary">Gamezop</h3>
            <p class="text-gray-300 mb-4">Check for new games from Gamezop API.</p>
            <div class="bg-blue-900/30 border border-blue-700/50 rounded-md p-3 mb-4">
                <p class="text-sm text-blue-300"><i class="fas fa-info-circle mr-2"></i> <strong>Game Progress Saving:</strong> Gamezop games now support progress saving for logged-in users. Players can continue their games from where they left off, even when returning on different devices.</p>
            </div>

            <div class="mb-4">
                <label for="gamezopPropertyId" class="block text-gray-300 mb-1">Property ID</label>
                <div class="flex">
                    <input type="text" id="gamezopPropertyId" name="gamezopPropertyId" placeholder="Your Gamezop Property ID"
                           class="w-full bg-darker border border-gray-700 rounded-md px-3 py-2 text-gray-300 focus:outline-none focus:border-primary">
                </div>
                <p class="text-sm text-gray-400 mt-1">Enter your Gamezop Property ID from the Gamezop Publisher Dashboard</p>
            </div>

            <div class="flex flex-col space-y-2">
                <button type="button" class="admin-button check-games-btn" data-source="gamezop">
                    <i class="fas fa-search mr-2"></i> Check for New Games
                </button>

                <?php if ($gamezopGames > 0): ?>
                <form action="/admin/games/delete-by-source" method="POST" onsubmit="return confirm('Are you sure you want to delete ALL Gamezop games? This action cannot be undone.')">
                    <input type="hidden" name="source" value="gamezop">
                    <button type="submit" class="w-full bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium">
                        <i class="fas fa-trash mr-2"></i> Delete All Games
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="bg-dark p-4 rounded-md border border-gray-800">
            <h3 class="text-lg font-medium mb-2 text-primary">Check All Sources</h3>
            <p class="text-gray-300 mb-4">Check for new games from all available sources.</p>

            <div class="flex flex-col space-y-2">
                <button type="button" class="admin-button check-games-btn" data-source="all">
                    <i class="fas fa-search mr-2"></i> Check All Sources
                </button>

                <?php if ($totalGames > 0): ?>
                <form action="/admin/games/delete-by-source" method="POST" onsubmit="return confirm('Are you sure you want to delete ALL GAMES from ALL SOURCES? This action cannot be undone.')">
                    <input type="hidden" name="source" value="all">
                    <button type="submit" class="w-full bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium">
                        <i class="fas fa-trash mr-2"></i> Delete All Games
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="bg-dark p-4 rounded-md border border-gray-800">
            <h3 class="text-lg font-medium mb-2 text-primary">Manual Import</h3>
            <p class="text-gray-300 mb-4">Manually import a game by providing the required information.</p>

            <form id="manualImportForm" class="space-y-4">
                <div>
                    <label for="gameTitle" class="block text-gray-300 mb-1">Game Title</label>
                    <input type="text" id="gameTitle" name="gameTitle" required
                           class="w-full bg-darker border border-gray-700 rounded-md px-3 py-2 text-gray-300 focus:outline-none focus:border-primary">
                </div>
                <div>
                    <label for="gameUrl" class="block text-gray-300 mb-1">Game URL</label>
                    <input type="url" id="gameUrl" name="gameUrl" required
                           class="w-full bg-darker border border-gray-700 rounded-md px-3 py-2 text-gray-300 focus:outline-none focus:border-primary">
                </div>
                <div>
                    <label for="thumbnailFile" class="block text-gray-300 mb-1">Thumbnail Image</label>
                    <div class="space-y-2">
                        <div class="flex items-center space-x-2">
                            <label class="admin-button cursor-pointer">
                                <i class="fas fa-upload mr-2"></i> Choose Image
                                <input type="file" id="thumbnailFile" name="thumbnailFile" accept="image/*" required
                                    class="hidden" onchange="previewThumbnail(this)">
                            </label>
                            <span id="selectedFileName" class="text-gray-400 text-sm"></span>
                        </div>
                        <div id="thumbnailPreview" class="hidden">
                            <img src="" alt="Thumbnail Preview" class="max-w-[200px] max-h-[200px] rounded-md border border-gray-700">
                        </div>
                    </div>
                </div>
                <div>
                    <label for="gameDescription" class="block text-gray-300 mb-1">Description</label>
                    <textarea id="gameDescription" name="gameDescription" rows="3" required
                            class="w-full bg-darker border border-gray-700 rounded-md px-3 py-2 text-gray-300 focus:outline-none focus:border-primary"></textarea>
                </div>
                <div>
                    <label for="gameCategories" class="block text-gray-300 mb-1">Categories (comma-separated)</label>
                    <input type="text" id="gameCategories" name="gameCategories" required
                           class="w-full bg-darker border border-gray-700 rounded-md px-3 py-2 text-gray-300 focus:outline-none focus:border-primary"
                           placeholder="action, adventure, puzzle">
                </div>
                <button type="submit" class="admin-button">
                    <i class="fas fa-plus mr-2"></i> Import Game
                </button>
            </form>
        </div>


    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Get all check games buttons
    const checkButtons = document.querySelectorAll('.check-games-btn');

    // Add click event listener to each button
    checkButtons.forEach(button => {
        button.addEventListener('click', function() {
            const source = this.getAttribute('data-source');
            checkForNewGames(source, this);
        });
    });

    // Function to check for new games via AJAX
    function checkForNewGames(source, button) {
        // Disable all buttons during import
        checkButtons.forEach(btn => {
            btn.disabled = true;
            btn.classList.add('opacity-50');
        });

        // Change button text to show loading
        const originalText = button.innerHTML;
        button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Checking...';

        // Show live log container
        const liveLogContainer = document.getElementById('liveLogContainer');
        const liveLog = document.getElementById('liveLog');
        liveLogContainer.classList.remove('hidden');
        liveLog.innerHTML = '<div>Starting import process for ' + source + '...</div>';

        // Create FormData object
        const formData = new FormData();
        formData.append('source', source);
        formData.append('ajax', 'true');

        // Add page number for GamePix import
        if (source === 'gamepix' || source === 'all') {
            const gamepixPage = document.getElementById('gamepixPage').value || 1;
            formData.append('gamepixPage', gamepixPage);
        }

        // Add property ID for Gamezop import
        if (source === 'gamezop' || source === 'all') {
            const gamezopPropertyId = document.getElementById('gamezopPropertyId').value || '';
            formData.append('gamezopPropertyId', gamezopPropertyId);
        }

        // Create EventSource for live updates
        let eventSourceUrl = '/admin/import-games-stream?source=' + source;

        // Add page parameter for GamePix
        if (source === 'gamepix' || source === 'all') {
            const gamepixPage = document.getElementById('gamepixPage').value || 1;
            eventSourceUrl += '&gamepixPage=' + gamepixPage;
        }

        // Add property ID for Gamezop
        if (source === 'gamezop' || source === 'all') {
            const gamezopPropertyId = document.getElementById('gamezopPropertyId').value || '';
            eventSourceUrl += '&gamezopPropertyId=' + encodeURIComponent(gamezopPropertyId);
        }

        const eventSource = new EventSource(eventSourceUrl);

        // Handle messages from the server
        eventSource.onmessage = function(event) {
            try {
                const data = JSON.parse(event.data);

                if (data.type === 'log') {
                    // Add log message
                    const logEntry = document.createElement('div');
                    logEntry.innerHTML = data.message;
                    liveLog.appendChild(logEntry);
                    liveLog.scrollTop = liveLog.scrollHeight;
                } else if (data.type === 'progress') {
                    // Update progress
                    updateProgress(data);
                } else if (data.type === 'complete') {
                    // Import complete, update results
                    eventSource.close();
                    completeImport(data);
                } else if (data.type === 'error') {
                    // Handle error
                    const errorEntry = document.createElement('div');
                    errorEntry.innerHTML = '<span class="text-red-500">' + data.message + '</span>';
                    liveLog.appendChild(errorEntry);
                    liveLog.scrollTop = liveLog.scrollHeight;
                }
            } catch (error) {
                console.error('Error parsing JSON:', error, event.data);

                // Add error message to log
                const errorEntry = document.createElement('div');
                errorEntry.innerHTML = '<span class="text-red-500">Error parsing server response. Check the browser console for details.</span>';
                liveLog.appendChild(errorEntry);
                liveLog.scrollTop = liveLog.scrollHeight;

                // Close the event source
                eventSource.close();

                // Re-enable buttons
                checkButtons.forEach(btn => {
                    btn.disabled = false;
                    btn.classList.remove('opacity-50');
                });
                button.innerHTML = originalText;
            }
        };

        // Handle errors
        eventSource.onerror = function() {
            eventSource.close();

            // Add error message to log
            const errorEntry = document.createElement('div');
            errorEntry.innerHTML = '<span class="text-red-500">Error: Connection lost. Please check the server logs.</span>';
            liveLog.appendChild(errorEntry);

            // Re-enable buttons
            checkButtons.forEach(btn => {
                btn.disabled = false;
                btn.classList.remove('opacity-50');
            });
            button.innerHTML = originalText;

            // Fetch final results
            fetchResults();
        };

        // Fallback to traditional AJAX if EventSource is not supported or fails
        setTimeout(function() {
            if (eventSource.readyState !== 1) { // Not connected
                eventSource.close();

                // Use traditional AJAX instead
                fetch('/admin/import-games', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    completeImport(data);
                })
                .catch(error => {
                    console.error('Error:', error);

                    // Add error message to log
                    const errorEntry = document.createElement('div');
                    errorEntry.innerHTML = '<span class="text-red-500">Error: ' + error.message + '</span>';
                    liveLog.appendChild(errorEntry);

                    // Re-enable buttons
                    checkButtons.forEach(btn => {
                        btn.disabled = false;
                        btn.classList.remove('opacity-50');
                    });
                    button.innerHTML = originalText;
                });
            }
        }, 3000); // Wait 3 seconds before falling back
    }

    // Function to update progress
    function updateProgress(data) {
        const liveLog = document.getElementById('liveLog');

        if (data.source && data.count) {
            const progressEntry = document.createElement('div');
            progressEntry.innerHTML = '<span class="text-primary">' + data.source + ':</span> ' + data.message;
            liveLog.appendChild(progressEntry);
            liveLog.scrollTop = liveLog.scrollHeight;
        }
    }

    // Function to complete import
    function completeImport(data) {
        // Update results area
        const importResults = document.getElementById('importResults');
        const importResultsContent = document.getElementById('importResultsContent');

        importResults.classList.remove('hidden');

        let resultsHtml = '';

        if (data.results.gamemonetize) {
            resultsHtml += '<div class="mb-4">';
            resultsHtml += '<h4 class="text-white font-medium mb-1">GameMonetize</h4>';
            resultsHtml += '<p class="text-gray-300">';

            if (data.results.gamemonetize.success) {
                resultsHtml += '<i class="fas fa-check-circle text-green-500 mr-2"></i>';
                resultsHtml += data.results.gamemonetize.message;
            } else {
                resultsHtml += '<i class="fas fa-exclamation-circle text-red-500 mr-2"></i>';
                resultsHtml += 'Error: ' + data.results.gamemonetize.message;
            }

            resultsHtml += '</p></div>';
        }

        if (data.results.gamepix) {
            resultsHtml += '<div class="mb-4">';
            resultsHtml += '<h4 class="text-white font-medium mb-1">GamePix</h4>';
            resultsHtml += '<p class="text-gray-300">';

            if (data.results.gamepix.success) {
                resultsHtml += '<i class="fas fa-check-circle text-green-500 mr-2"></i>';
                resultsHtml += data.results.gamepix.message;
            } else {
                resultsHtml += '<i class="fas fa-exclamation-circle text-red-500 mr-2"></i>';
                resultsHtml += 'Error: ' + data.results.gamepix.message;
            }

            resultsHtml += '</p></div>';
        }

        if (data.results.gamezop) {
            resultsHtml += '<div>';
            resultsHtml += '<h4 class="text-white font-medium mb-1">Gamezop</h4>';
            resultsHtml += '<p class="text-gray-300">';

            if (data.results.gamezop.success) {
                resultsHtml += '<i class="fas fa-check-circle text-green-500 mr-2"></i>';
                resultsHtml += data.results.gamezop.message;
            } else {
                resultsHtml += '<i class="fas fa-exclamation-circle text-red-500 mr-2"></i>';
                resultsHtml += 'Error: ' + data.results.gamezop.message;
            }

            resultsHtml += '</p></div>';
        }

        importResultsContent.innerHTML = resultsHtml;

        // Add completion message to log
        const liveLog = document.getElementById('liveLog');
        const completionEntry = document.createElement('div');
        completionEntry.innerHTML = '<span class="text-green-500">Import process completed!</span>';
        liveLog.appendChild(completionEntry);
        liveLog.scrollTop = liveLog.scrollHeight;

        // Update game statistics
        updateGameStats(data.stats);

        // Re-enable buttons
        const checkButtons = document.querySelectorAll('.check-games-btn');
        checkButtons.forEach(btn => {
            btn.disabled = false;
            btn.classList.remove('opacity-50');

            // Reset button text
            if (btn.getAttribute('data-source') === 'gamemonetize') {
                btn.innerHTML = '<i class="fas fa-search mr-2"></i> Check for New Games';
            } else if (btn.getAttribute('data-source') === 'gamepix') {
                btn.innerHTML = '<i class="fas fa-search mr-2"></i> Check for New Games';
            } else {
                btn.innerHTML = '<i class="fas fa-search mr-2"></i> Check All Sources';
            }
        });
    }

    // Function to update game statistics
    function updateGameStats(stats) {
        if (!stats) return;

        const gameStats = document.getElementById('gameStats');

        gameStats.innerHTML = `
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">Total Games</div>
                <div class="text-2xl font-bold">${stats.totalGames}</div>
            </div>
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">GameMonetize</div>
                <div class="text-2xl font-bold">${stats.gamemonetizeGames}</div>
            </div>
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">GamePix</div>
                <div class="text-2xl font-bold">${stats.gamepixGames}</div>
            </div>
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">Gamezop</div>
                <div class="text-2xl font-bold">${stats.gamezopGames}</div>
            </div>
            <div class="bg-dark p-3 rounded-lg border border-gray-800">
                <div class="text-primary text-sm mb-1">Categories</div>
                <div class="text-2xl font-bold">${stats.totalCategories}</div>
            </div>
        `;

        // Update the visibility of delete buttons based on game counts
        const gamemonetizeDeleteForm = document.querySelector('form[action="/admin/games/delete-by-source"] input[value="gamemonetize"]')?.closest('form');
        const gamepixDeleteForm = document.querySelector('form[action="/admin/games/delete-by-source"] input[value="gamepix"]')?.closest('form');
        const gamezopDeleteForm = document.querySelector('form[action="/admin/games/delete-by-source"] input[value="gamezop"]')?.closest('form');
        const allGamesDeleteForm = document.querySelector('form[action="/admin/games/delete-by-source"] input[value="all"]')?.closest('form');

        if (gamemonetizeDeleteForm) {
            gamemonetizeDeleteForm.style.display = stats.gamemonetizeGames > 0 ? 'block' : 'none';
        }

        if (gamepixDeleteForm) {
            gamepixDeleteForm.style.display = stats.gamepixGames > 0 ? 'block' : 'none';
        }

        if (gamezopDeleteForm) {
            gamezopDeleteForm.style.display = stats.gamezopGames > 0 ? 'block' : 'none';
        }

        if (allGamesDeleteForm) {
            allGamesDeleteForm.style.display = stats.totalGames > 0 ? 'block' : 'none';
        }

        // Ensure proper spacing in the flex containers
        document.querySelectorAll('.flex.flex-col.space-y-2').forEach(container => {
            // If the container has only one visible child, remove the spacing
            const visibleChildren = Array.from(container.children).filter(child =>
                child.style.display !== 'none' && getComputedStyle(child).display !== 'none'
            );

            if (visibleChildren.length <= 1) {
                container.classList.remove('space-y-2');
            } else {
                container.classList.add('space-y-2');
            }
        });
    }

    // Function to fetch final results
    function fetchResults() {
        fetch('/admin/import-games-status')
        .then(response => response.json())
        .then(data => {
            if (data.results) {
                completeImport(data);
            }
        })
        .catch(error => {
            console.error('Error fetching results:', error);
        });
    }

    // Handle manual game import form submission
    const manualImportForm = document.getElementById('manualImportForm');
    if (manualImportForm) {
        // Add thumbnail preview function
        window.previewThumbnail = function(input) {
            const preview = document.getElementById('thumbnailPreview');
            const fileNameSpan = document.getElementById('selectedFileName');
            const previewImg = preview.querySelector('img');

            if (input.files && input.files[0]) {
                const file = input.files[0];

                // Update file name display
                fileNameSpan.textContent = file.name;

                // Show preview
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    preview.classList.remove('hidden');
                };
                reader.readAsDataURL(file);
            } else {
                // Clear preview
                preview.classList.add('hidden');
                previewImg.src = '';
                fileNameSpan.textContent = '';
            }
        };

        manualImportForm.addEventListener('submit', function(e) {
            e.preventDefault();

            // Show live log container
            const liveLogContainer = document.getElementById('liveLogContainer');
            const liveLog = document.getElementById('liveLog');
            liveLogContainer.classList.remove('hidden');
            liveLog.innerHTML = '<div>Processing manual game import...</div>';

            // Disable the submit button
            const submitButton = this.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;
            submitButton.disabled = true;
            submitButton.classList.add('opacity-50');
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Importing...';

            // Create FormData object
            const formData = new FormData(this);
            formData.append('source', 'manual');
            formData.append('ajax', 'true');

            // Send the request
            fetch('/admin/import-games', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                // Add success message to log
                const successEntry = document.createElement('div');

                if (data.results && data.results.manual && data.results.manual.success) {
                    successEntry.innerHTML = '<span class="text-green-500">Game imported successfully!</span>';
                    liveLog.appendChild(successEntry);

                    // Update results area
                    const importResults = document.getElementById('importResults');
                    const importResultsContent = document.getElementById('importResultsContent');
                    importResults.classList.remove('hidden');
                    importResultsContent.innerHTML = `
                        <div>
                            <h4 class="text-white font-medium mb-1">Manual Import</h4>
                            <p class="text-gray-300">
                                <i class="fas fa-check-circle text-green-500 mr-2"></i>
                                ${data.results.manual.message || 'Game imported successfully'}
                            </p>
                        </div>
                    `;

                    // Reset the form and thumbnail preview
                    manualImportForm.reset();
                    const thumbnailPreview = document.getElementById('thumbnailPreview');
                    thumbnailPreview.classList.add('hidden');
                    document.getElementById('selectedFileName').textContent = '';

                    // Update game statistics
                    if (data.stats) {
                        updateGameStats(data.stats);
                    }
                } else {
                    // Handle error case
                    const errorMessage = (data.results && data.results.manual) ?
                        data.results.manual.message : 'Failed to import game';

                    successEntry.innerHTML = `<span class="text-red-500">Error: ${errorMessage}</span>`;
                    liveLog.appendChild(successEntry);
                }

                liveLog.scrollTop = liveLog.scrollHeight;
            })
            .catch(error => {
                console.error('Error:', error);

                // Add error message to log
                const errorEntry = document.createElement('div');
                errorEntry.innerHTML = '<span class="text-red-500">Error: ' + (error.message || 'Failed to import game') + '</span>';
                liveLog.appendChild(errorEntry);
            })
            .finally(() => {
                // Re-enable the submit button
                submitButton.disabled = false;
                submitButton.classList.remove('opacity-50');
                submitButton.innerHTML = originalText;
            });
        });
    }
});
</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
?>