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

class GameImporter {
    private $db;

    public function __construct() {
        try {
            $database = new Database();
            $this->db = $database->getConnection();

            // Set PDO to throw exceptions on error
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            // Check and update table structure if needed
            $this->checkAndUpdateTableStructure();
        } catch (Exception $e) {
            error_log('Database connection error: ' . $e->getMessage());
            throw new Exception('Failed to connect to the database: ' . $e->getMessage());
        }
    }

    /**
     * Check and update the games table structure if needed
     */
    private function checkAndUpdateTableStructure() {
        try {
            // Check database type
            $dbType = $_ENV['DB_TYPE'] ?? 'sqlite';

            if ($dbType === 'mysql') {
                // MySQL syntax for checking columns
                $stmt = $this->db->prepare("SHOW COLUMNS FROM games LIKE 'updated_at'");
                $stmt->execute();
                $hasUpdatedAt = $stmt->rowCount() > 0;

                // Add updated_at column if it doesn't exist
                if (!$hasUpdatedAt) {
                    $this->db->exec("ALTER TABLE games ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
                }
            } else {
                // SQLite syntax for checking columns
                $stmt = $this->db->prepare("PRAGMA table_info(games)");
                $stmt->execute();
                $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);

                $hasUpdatedAt = false;
                foreach ($columns as $column) {
                    if ($column['name'] === 'updated_at') {
                        $hasUpdatedAt = true;
                        break;
                    }
                }

                // Add updated_at column if it doesn't exist
                if (!$hasUpdatedAt) {
                    $this->db->exec("ALTER TABLE games ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
                }
            }
        } catch (PDOException $e) {
            error_log('Error checking table structure: ' . $e->getMessage());
        }
    }

    /**
     * Import games from GameMonetize RSS feed with streaming updates
     *
     * @param callable|null $progressCallback Callback function for progress updates
     * @return array Import results
     */
    public function importGameMonetize($progressCallback = null) {
        $result = [
            'success' => false,
            'count' => 0,
            'message' => ''
        ];

        $url = 'https://rss.gamemonetize.com/rssfeed.php?format=json&category=All&type=html5&popularity=newest&company=All&amount=All';

        try {
            // Log start of import
            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamemonetize',
                    'message' => 'Fetching games from GameMonetize... (Only new games will be imported)'
                ]);
            }

            $response = file_get_contents($url);

            if ($response) {
                $games = json_decode($response, true);

                if (!$games || !is_array($games)) {
                    $result['message'] = 'Invalid response from GameMonetize';
                    return $result;
                }

                $totalGames = count($games);

                // Log total games found
                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamemonetize',
                        'message' => "Found $totalGames games to process"
                    ]);
                }

                $importCount = 0;
                $source = 'gamemonetize';
                $processedCount = 0;

                foreach ($games as $gameData) {
                    $processedCount++;

                    // Send progress update every 10 games or for the first/last game
                    if ($progressCallback && ($processedCount % 10 === 0 || $processedCount === 1 || $processedCount === $totalGames)) {
                        $progressCallback([
                            'type' => 'progress',
                            'source' => 'gamemonetize',
                            'count' => $importCount,
                            'total' => $totalGames,
                            'processed' => $processedCount,
                            'message' => "Processing game $processedCount of $totalGames..."
                        ]);
                    }

                    try {
                        // Find or create category
                        $categoryId = null;
                        if (!empty($gameData['category'])) {
                            $categoryId = $this->findOrCreateCategory($gameData['category']);
                        }

                        // Update or insert game
                        $gameId = $this->updateOrInsertGame($gameData, $source, $categoryId);

                        if ($gameId === null) {
                            // Game was skipped (already exists)
                            if ($progressCallback) {
                                $progressCallback([
                                    'type' => 'log',
                                    'source' => 'gamemonetize',
                                    'message' => '<span class="text-blue-500">Skipped existing game: ' . htmlspecialchars($gameData['title']) . '</span>'
                                ]);
                            }
                        } else if ($gameId) {
                            $importCount++;

                            // Log newly imported game
                            if ($progressCallback) {
                                $progressCallback([
                                    'type' => 'log',
                                    'source' => 'gamemonetize',
                                    'message' => "Imported new game: " . $gameData['title']
                                ]);
                            }
                        }
                    } catch (PDOException $e) {
                        // Log the error but continue with other games
                        error_log('Error importing game from GameMonetize: ' . $e->getMessage());

                        if ($progressCallback) {
                            $errorMessage = $e->getMessage();
                            // Check for integrity constraint violation
                            if (strpos($errorMessage, 'UNIQUE constraint failed') !== false) {
                                $errorMessage = 'Game already exists with the same source and ID. Skipping duplicate.';
                            }

                            $progressCallback([
                                'type' => 'log',
                                'source' => 'gamemonetize',
                                'message' => '<span class="text-yellow-500">Warning: ' . htmlspecialchars($errorMessage) . '</span>'
                            ]);
                        }

                        continue;
                    }
                }

                // Log completion
                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamemonetize',
                        'message' => '<span class="text-green-500">Completed GameMonetize import. Added ' . $importCount . ' new games.</span>'
                    ]);
                }

                $result['success'] = true;
                $result['count'] = $importCount;
                $result['message'] = "Found $importCount new games from GameMonetize";
            } else {
                $result['message'] = 'Failed to fetch games from GameMonetize';

                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamemonetize',
                        'message' => '<span class="text-red-500">Failed to fetch games from GameMonetize</span>'
                    ]);
                }
            }
        } catch (Exception $e) {
            $result['message'] = 'Error importing games from GameMonetize: ' . $e->getMessage();

            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamemonetize',
                    'message' => '<span class="text-red-500">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'
                ]);
            }
        }

        return $result;
    }

    /**
     * Import games from GamePix RSS feed with streaming updates
     *
     * @param int $pageNumber Page number to import (default: 1)
     * @param callable|null $progressCallback Callback function for progress updates
     * @return array Import results
     */
    public function importGamePix($pageNumber = 1, $progressCallback = null) {
        $result = [
            'success' => false,
            'count' => 0,
            'message' => ''
        ];

        $baseUrl = 'https://feeds.gamepix.com/v2/json';
        $source = 'gamepix';
        $totalImported = 0;

        try {
            // Log start of import
            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamepix',
                    'message' => 'Starting GamePix import process for page ' . $pageNumber . '... (Only new games will be imported)'
                ]);
            }

            $url = $baseUrl . '?page=' . $pageNumber . '&pagination=96';

            // Log fetching page
            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamepix',
                    'message' => "Fetching page $pageNumber..."
                ]);
            }

            $response = file_get_contents($url);

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

                $games = $data['items'] ?? [];
                $totalGames = count($games);

                // Log total games found on this page
                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamepix',
                        'message' => "Found $totalGames games on page $pageNumber"
                    ]);
                }

                $importCount = 0;
                $processedCount = 0;

                foreach ($games as $gameData) {
                    $processedCount++;

                    // Send progress update every 10 games or for the first/last game
                    if ($progressCallback && ($processedCount % 10 === 0 || $processedCount === 1 || $processedCount === $totalGames)) {
                        $progressCallback([
                            'type' => 'progress',
                            'source' => 'gamepix',
                            'count' => $importCount,
                            'total' => $totalGames,
                            'processed' => $processedCount,
                            'page' => $pageNumber,
                            'message' => "Page $pageNumber: Processing game $processedCount of $totalGames..."
                        ]);
                    }

                    try {
                        // Find or create category
                        $categoryId = null;
                        if (!empty($gameData['category'])) {
                            $categoryId = $this->findOrCreateCategory($gameData['category']);
                        }

                        // Update or insert game
                        $gameId = $this->updateOrInsertGame($gameData, $source, $categoryId);

                        if ($gameId === null) {
                            // Game was skipped (already exists)
                            if ($progressCallback) {
                                $progressCallback([
                                    'type' => 'log',
                                    'source' => 'gamepix',
                                    'message' => '<span class="text-blue-500">Skipped existing game: ' . htmlspecialchars($gameData['title']) . '</span>'
                                ]);
                            }
                        } else if ($gameId) {
                            $importCount++;

                            // Log newly imported game
                            if ($progressCallback) {
                                $progressCallback([
                                    'type' => 'log',
                                    'source' => 'gamepix',
                                    'message' => "Imported new game: " . $gameData['title']
                                ]);
                            }
                        }
                    } catch (PDOException $e) {
                        // Log the error but continue with other games
                        error_log('Error importing game from GamePix: ' . $e->getMessage());

                        if ($progressCallback) {
                            $errorMessage = $e->getMessage();
                            // Check for integrity constraint violation
                            if (strpos($errorMessage, 'UNIQUE constraint failed') !== false) {
                                $errorMessage = 'Game already exists with the same source and ID. Skipping duplicate.';
                            }

                            $progressCallback([
                                'type' => 'log',
                                'source' => 'gamepix',
                                'message' => '<span class="text-yellow-500">Warning: ' . htmlspecialchars($errorMessage) . '</span>'
                            ]);
                        }

                        continue;
                    }
                }

                $totalImported += $importCount;

                // Log page completion
                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamepix',
                        'message' => "Completed page $pageNumber. Added $importCount new games."
                    ]);
                }
            } else {
                $result['message'] = 'Failed to fetch games from GamePix';

                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamepix',
                        'message' => '<span class="text-red-500">Failed to fetch games from GamePix</span>'
                    ]);
                }

                return $result;
            }

            // Log completion
            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamepix',
                    'message' => '<span class="text-green-500">Completed GamePix import. Added ' . $totalImported . ' new games from page ' . $pageNumber . '.</span>'
                ]);
            }

            $result['success'] = true;
            $result['count'] = $totalImported;
            $result['message'] = "Found $totalImported new games from GamePix (page $pageNumber)";
        } catch (Exception $e) {
            $result['message'] = 'Error importing games from GamePix: ' . $e->getMessage();

            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamepix',
                    'message' => '<span class="text-red-500">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'
                ]);
            }
        }

        return $result;
    }

    /**
     * Get game statistics
     *
     * @return array Game statistics
     */
    /**
     * Import games from Gamezop API with streaming updates
     *
     * @param string $propertyId Gamezop Property ID
     * @param callable|null $progressCallback Callback function for progress updates
     * @return array Import results
     */
    public function importGamezop($propertyId = '', $progressCallback = null) {
        $result = [
            'success' => false,
            'count' => 0,
            'message' => ''
        ];

        if (empty($propertyId)) {
            $result['message'] = 'Gamezop Property ID is required';

            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamezop',
                    'message' => '<span class="text-red-500">Error: Gamezop Property ID is required</span>'
                ]);
            }

            return $result;
        }

        $url = 'https://pub.gamezop.com/v3/games?id=' . urlencode($propertyId) . '&lang=en';
        $source = 'gamezop';

        try {
            // Log start of import
            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamezop',
                    'message' => 'Fetching games from Gamezop... (Only new games will be imported)'
                ]);
            }

            // Use cURL to fetch data with proper headers
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Accept: application/json',
                'User-Agent: Mozilla/5.0 (compatible; WebAI/1.0)'
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode !== 200) {
                $result['message'] = 'Failed to fetch games from Gamezop. HTTP Code: ' . $httpCode;

                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamezop',
                        'message' => '<span class="text-red-500">Failed to fetch games from Gamezop. HTTP Code: ' . $httpCode . '</span>'
                    ]);
                }

                return $result;
            }

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

                if (!isset($data['games']) || !is_array($data['games'])) {
                    $result['message'] = 'Invalid response from Gamezop';

                    if ($progressCallback) {
                        $progressCallback([
                            'type' => 'log',
                            'source' => 'gamezop',
                            'message' => '<span class="text-red-500">Invalid response from Gamezop</span>'
                        ]);
                    }

                    return $result;
                }

                $games = $data['games'];
                $totalGames = count($games);

                // Log total games found
                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamezop',
                        'message' => "Found $totalGames games to process"
                    ]);
                }

                $importCount = 0;
                $processedCount = 0;

                foreach ($games as $game) {
                    $processedCount++;

                    // Send progress update every 10 games or for the first/last game
                    if ($progressCallback && ($processedCount % 10 === 0 || $processedCount === 1 || $processedCount === $totalGames)) {
                        $progressCallback([
                            'type' => 'progress',
                            'source' => 'gamezop',
                            'count' => $importCount,
                            'total' => $totalGames,
                            'processed' => $processedCount,
                            'message' => "Processing game $processedCount of $totalGames..."
                        ]);
                    }

                    try {
                        // Prepare game data for insertion
                        $gameData = [
                            'id' => $game['code'],
                            'title' => $game['name']['en'],
                            'description' => $game['description']['en'],
                            'url' => $game['url'],
                            'thumb' => $game['assets']['thumb'],
                            'category' => !empty($game['categories']['en'][0]) ? $game['categories']['en'][0] : null
                        ];

                        // Find or create category
                        $categoryId = null;
                        if (!empty($gameData['category'])) {
                            $categoryId = $this->findOrCreateCategory($gameData['category']);
                        }

                        // Update or insert game
                        $gameId = $this->updateOrInsertGame($gameData, $source, $categoryId);

                        if ($gameId === null) {
                            // Game was skipped (already exists)
                            if ($progressCallback) {
                                $progressCallback([
                                    'type' => 'log',
                                    'source' => 'gamezop',
                                    'message' => '<span class="text-blue-500">Skipped existing game: ' . htmlspecialchars($gameData['title']) . '</span>'
                                ]);
                            }
                        } else if ($gameId) {
                            $importCount++;

                            // Log newly imported game
                            if ($progressCallback) {
                                $progressCallback([
                                    'type' => 'log',
                                    'source' => 'gamezop',
                                    'message' => "Imported new game: " . $gameData['title']
                                ]);
                            }
                        }
                    } catch (PDOException $e) {
                        // Log the error but continue with other games
                        error_log('Error importing game from Gamezop: ' . $e->getMessage());

                        if ($progressCallback) {
                            $errorMessage = $e->getMessage();
                            // Check for integrity constraint violation
                            if (strpos($errorMessage, 'UNIQUE constraint failed') !== false) {
                                $errorMessage = 'Game already exists with the same source and ID. Skipping duplicate.';
                            }

                            $progressCallback([
                                'type' => 'log',
                                'source' => 'gamezop',
                                'message' => '<span class="text-yellow-500">Warning: ' . htmlspecialchars($errorMessage) . '</span>'
                            ]);
                        }

                        continue;
                    }
                }

                // Log completion
                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamezop',
                        'message' => '<span class="text-green-500">Completed Gamezop import. Added ' . $importCount . ' new games.</span>'
                    ]);
                }

                $result['success'] = true;
                $result['count'] = $importCount;
                $result['message'] = "Found $importCount new games from Gamezop";
            } else {
                $result['message'] = 'Failed to fetch games from Gamezop';

                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'gamezop',
                        'message' => '<span class="text-red-500">Failed to fetch games from Gamezop</span>'
                    ]);
                }
            }
        } catch (Exception $e) {
            $result['message'] = 'Error importing games from Gamezop: ' . $e->getMessage();

            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'gamezop',
                    'message' => '<span class="text-red-500">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'
                ]);
            }
        }

        return $result;
    }

    public function getGameStats() {
        $stats = [
            'totalGames' => 0,
            'gamemonetizeGames' => 0,
            'gamepixGames' => 0,
            'gamezopGames' => 0,
            'totalCategories' => 0
        ];

        try {
            // Get total games
            $stmt = $this->db->prepare('SELECT COUNT(*) FROM games');
            $stmt->execute();
            $stats['totalGames'] = $stmt->fetchColumn();

            // Get GameMonetize games
            $stmt = $this->db->prepare('SELECT COUNT(*) FROM games WHERE source = :source');
            $stmt->bindValue(':source', 'gamemonetize');
            $stmt->execute();
            $stats['gamemonetizeGames'] = $stmt->fetchColumn();

            // Get GamePix games
            $stmt = $this->db->prepare('SELECT COUNT(*) FROM games WHERE source = :source');
            $stmt->bindValue(':source', 'gamepix');
            $stmt->execute();
            $stats['gamepixGames'] = $stmt->fetchColumn();

            // Get Gamezop games
            $stmt = $this->db->prepare('SELECT COUNT(*) FROM games WHERE source = :source');
            $stmt->bindValue(':source', 'gamezop');
            $stmt->execute();
            $stats['gamezopGames'] = $stmt->fetchColumn();

            // Get total categories
            $stmt = $this->db->prepare('SELECT COUNT(*) FROM categories');
            $stmt->execute();
            $stats['totalCategories'] = $stmt->fetchColumn();
        } catch (Exception $e) {
            // Silently fail and return zeros
        }

        return $stats;
    }

    /**
     * Find or create a category and return its ID
     *
     * @param string $categoryName Category name
     * @return int|null Category ID
     */
    private function findOrCreateCategory($categoryName) {
        $categoryName = trim($categoryName);
        if (empty($categoryName)) {
            return null;
        }

        try {
            // Check if category exists by name
            $stmt = $this->db->prepare('SELECT id FROM categories WHERE name = :name');
            $stmt->bindParam(':name', $categoryName);
            $stmt->execute();
            $category = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($category) {
                return $category['id'];
            }

            // Generate the slug
            $baseSlug = $this->slugify($categoryName);
            $slug = $baseSlug;

            // Check if slug exists
            $stmt = $this->db->prepare('SELECT COUNT(*) FROM categories WHERE slug = :slug');
            $stmt->bindParam(':slug', $slug);
            $stmt->execute();
            $count = $stmt->fetchColumn();

            // If slug exists, append a number to make it unique
            $counter = 1;
            while ($count > 0) {
                $slug = $baseSlug . '-' . $counter;
                $stmt->bindParam(':slug', $slug);
                $stmt->execute();
                $count = $stmt->fetchColumn();
                $counter++;
            }

            // Create new category with unique slug
            $stmt = $this->db->prepare('INSERT INTO categories (name, slug) VALUES (:name, :slug)');
            $stmt->bindParam(':name', $categoryName);
            $stmt->bindParam(':slug', $slug);
            $stmt->execute();

            return $this->db->lastInsertId();
        } catch (PDOException $e) {
            error_log('Error creating category: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Convert text to a URL-friendly slug
     *
     * @param string $text Text to slugify
     * @return string Slugified text
     */
    private function slugify($text) {
        // Replace non letter or digits by -
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);

        // Transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // Remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        // Trim
        $text = trim($text, '-');

        // Remove duplicate -
        $text = preg_replace('~-+~', '-', $text);

        // Lowercase
        $text = strtolower($text);

        if (empty($text)) {
            return 'n-a';
        }

        return $text;
    }

    /**
     * Insert a new game if it doesn't exist, skip if it already exists
     *
     * @param array $gameData Game data
     * @param string $source Game source
     * @param int|null $categoryId Category ID
     * @return int|bool Game ID or false on failure, null if skipped
     */
    /**
     * Import a manual game
     *
     * @param array $gameData Game data
     * @param string $thumbnailPath Path to the thumbnail image
     * @param callable|null $progressCallback Callback function for progress updates
     * @return array Import results
     */
    public function importManualGame($gameData, $thumbnailPath = '', $progressCallback = null) {
        $result = [
            'success' => false,
            'count' => 0,
            'message' => ''
        ];

        try {
            // Log start of import
            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'manual',
                    'message' => 'Processing manual game import...'
                ]);
            }

            // Validate required fields
            if (empty($gameData['gameTitle']) || empty($gameData['gameUrl'])) {
                $result['message'] = 'Game title and URL are required';

                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'manual',
                        'message' => '<span class="text-red-500">Error: Game title and URL are required</span>'
                    ]);
                }

                return $result;
            }

            // Generate a unique ID for the manual game
            $externalId = 'manual_' . time() . '_' . substr(md5($gameData['gameTitle']), 0, 8);

            // Prepare game data for insertion
            $manualGameData = [
                'id' => $externalId,
                'title' => $gameData['gameTitle'],
                'description' => $gameData['gameDescription'] ?? '',
                'url' => $gameData['gameUrl'],
                'thumb' => $thumbnailPath
            ];

            // Process categories
            $categoryId = null;
            if (!empty($gameData['gameCategories'])) {
                try {
                    $categories = explode(',', $gameData['gameCategories']);
                    if (!empty($categories[0])) {
                        $categoryName = trim($categories[0]);
                        $categoryId = $this->findOrCreateCategory($categoryName);

                        if ($categoryId === null) {
                            // Log warning but continue with import
                            if ($progressCallback) {
                                $progressCallback([
                                    'type' => 'log',
                                    'source' => 'manual',
                                    'message' => '<span class="text-yellow-500">Warning: Could not create primary category "' . htmlspecialchars($categoryName) . '". Game will be imported without a category.</span>'
                                ]);
                            }
                        }

                        // Create additional categories if provided
                        for ($i = 1; $i < count($categories); $i++) {
                            $additionalCategory = trim($categories[$i]);
                            if (!empty($additionalCategory)) {
                                $this->findOrCreateCategory($additionalCategory);
                                // We don't need to check the result for additional categories
                            }
                        }
                    }
                } catch (Exception $e) {
                    // Log warning but continue with import
                    error_log('Error processing categories: ' . $e->getMessage());
                    if ($progressCallback) {
                        $progressCallback([
                            'type' => 'log',
                            'source' => 'manual',
                            'message' => '<span class="text-yellow-500">Warning: Error processing categories. Game will be imported without a category.</span>'
                        ]);
                    }
                }
            }

            // Insert the game
            $gameId = $this->updateOrInsertGame($manualGameData, 'manual', $categoryId);

            if ($gameId) {
                $result['success'] = true;
                $result['count'] = 1;
                $result['message'] = 'Game imported successfully';

                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'manual',
                        'message' => '<span class="text-green-500">Game imported successfully: ' . htmlspecialchars($manualGameData['title']) . '</span>'
                    ]);
                }
            } else {
                $result['message'] = 'Failed to import game';

                if ($progressCallback) {
                    $progressCallback([
                        'type' => 'log',
                        'source' => 'manual',
                        'message' => '<span class="text-red-500">Failed to import game</span>'
                    ]);
                }
            }
        } catch (Exception $e) {
            $result['message'] = 'Error importing manual game: ' . $e->getMessage();

            if ($progressCallback) {
                $progressCallback([
                    'type' => 'log',
                    'source' => 'manual',
                    'message' => '<span class="text-red-500">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'
                ]);
            }
        }

        return $result;
    }

    private function updateOrInsertGame($gameData, $source, $categoryId = null) {
        try {
            // Check if game already exists
            $stmt = $this->db->prepare('SELECT id FROM games WHERE external_id = :external_id AND source = :source');
            $stmt->bindValue(':external_id', $gameData['id'], PDO::PARAM_STR);
            $stmt->bindValue(':source', $source, PDO::PARAM_STR);
            $stmt->execute();
            $existingGame = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($existingGame) {
                // Game already exists, skip it
                return null;
            } else {
                // Insert new game
                $title = $gameData['title'];
                $description = $gameData['description'] ?? '';
                $thumbnail = isset($gameData['thumb']) ? $gameData['thumb'] : (isset($gameData['banner_image']) ? $gameData['banner_image'] : (isset($gameData['image']) ? $gameData['image'] : ''));

                // Create embed code - for Gamezop, we'll modify the URL in the game view to add user ID
                $gameUrl = $gameData['url'];
                $embedCode = '<iframe src="' . $gameUrl . '" width="100%" height="100%" frameborder="0" allowfullscreen></iframe>';
                $slug = $this->slugify($gameData['title']);

                $stmt = $this->db->prepare('
                    INSERT INTO games (
                        title, description, thumbnail, embed_code, source, external_id, category_id, slug
                    ) VALUES (
                        :title, :description, :thumbnail, :embed_code, :source, :external_id, :category_id, :slug
                    )
                ');

                $stmt->bindValue(':title', $title, PDO::PARAM_STR);
                $stmt->bindValue(':description', $description, PDO::PARAM_STR);
                $stmt->bindValue(':thumbnail', $thumbnail, PDO::PARAM_STR);
                $stmt->bindValue(':embed_code', $embedCode, PDO::PARAM_STR);
                $stmt->bindValue(':source', $source, PDO::PARAM_STR);
                $stmt->bindValue(':external_id', $gameData['id'], PDO::PARAM_STR);
                $stmt->bindValue(':category_id', $categoryId, $categoryId ? PDO::PARAM_INT : PDO::PARAM_NULL);
                $stmt->bindValue(':slug', $slug, PDO::PARAM_STR);

                $stmt->execute();
                return $this->db->lastInsertId();
            }
        } catch (PDOException $e) {
            error_log('Error inserting game: ' . $e->getMessage());
            return false;
        }
    }
}