<?php
require_once __DIR__ . '/../models/Admin.php';
require_once __DIR__ . '/../models/SiteSettings.php';
require_once __DIR__ . '/../models/GameImporter.php';
require_once __DIR__ . '/../models/Game.php';
require_once __DIR__ . '/../models/Category.php';
require_once __DIR__ . '/../models/Blog.php';
require_once __DIR__ . '/../models/Page.php';
require_once __DIR__ . '/../models/Menu.php';
require_once __DIR__ . '/../models/UserManagement.php';
require_once __DIR__ . '/../models/Coins.php';
require_once __DIR__ . '/../helpers/EmailHelper.php';
require_once __DIR__ . '/../helpers/TurnstileHelper.php';
require_once __DIR__ . '/../helpers/OpenRouterHelper.php';

class AdminController {
    private $admin;
    private $siteSettings;
    private $gameImporter;
    private $game;
    private $category;
    private $blog;
    private $page;
    private $menu;
    private $userManagement;
    private $coins;
    private $turnstileHelper;
    private $openRouterHelper;

    public function __construct() {
        // Start session if not already started
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $this->admin = new Admin();
        $this->siteSettings = new SiteSettings();
        $this->gameImporter = new GameImporter();
        $this->game = new Game();
        $this->category = new Category();
        $this->blog = new Blog();
        $this->page = new Page();
        $this->menu = new Menu();
        $this->userManagement = new UserManagement();
        $this->coins = new Coins();
        $this->turnstileHelper = new TurnstileHelper();
        $this->openRouterHelper = new OpenRouterHelper();
    }

    public function loginPage() {
        // If already logged in, redirect to dashboard
        if ($this->admin->isLoggedIn()) {
            header('Location: /admin/dashboard');
            exit;
        }

        $error = '';
        $settings = $this->siteSettings->getAllSettings();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';
            $rememberMe = isset($_POST['remember_me']);
            $turnstileToken = $_POST['cf-turnstile-response'] ?? '';

            // Validate CAPTCHA if enabled
            if ($this->turnstileHelper->isEnabled() && !$this->turnstileHelper->validateResponse($turnstileToken)) {
                $error = 'CAPTCHA verification failed. Please try again.';
            } else if ($this->admin->authenticate($email, $password)) {
                $this->admin->login($rememberMe);
                header('Location: /admin/dashboard');
                exit;
            } else {
                $error = 'Invalid email or password';
            }
        }

        include __DIR__ . '/../views/admin/login.php';
    }

    public function dashboard() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();

        include __DIR__ . '/../views/admin/dashboard.php';
    }

    public function settings() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $success = false;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Update site title and description
            $this->siteSettings->setSetting('site_title', $_POST['site_title'] ?? '');
            $this->siteSettings->setSetting('site_description', $_POST['site_description'] ?? '');

            // Update SEO title templates
            $this->siteSettings->setSetting('seo_title_homepage', $_POST['seo_title_homepage'] ?? '{{site_title}} - Play Free Online Games');
            $this->siteSettings->setSetting('seo_title_page', $_POST['seo_title_page'] ?? '{{page_title}} - {{site_title}}');
            $this->siteSettings->setSetting('seo_title_category', $_POST['seo_title_category'] ?? '{{category_name}} Games - {{site_title}}');
            $this->siteSettings->setSetting('seo_title_blog', $_POST['seo_title_blog'] ?? 'Blog - {{site_title}}');
            $this->siteSettings->setSetting('seo_title_blog_post', $_POST['seo_title_blog_post'] ?? '{{post_title}} - Blog - {{site_title}}');
            $this->siteSettings->setSetting('seo_title_game', $_POST['seo_title_game'] ?? 'Play {{game_title}} - {{site_title}}');

            // Update homepage display settings
            $this->siteSettings->setSetting('homepage_display_type', $_POST['homepage_display_type'] ?? 'hero');
            
            // Update hero section
            $this->siteSettings->setSetting('hero_title', $_POST['hero_title'] ?? '');
            $this->siteSettings->setSetting('hero_description', $_POST['hero_description'] ?? '');

            // Update footer
            $this->siteSettings->setSetting('footer_description', $_POST['footer_description'] ?? '');

            // Update leaderboard settings
            $this->siteSettings->setSetting('show_leaderboard', isset($_POST['show_leaderboard']) ? '1' : '0');
            $this->siteSettings->setSetting('leaderboard_limit', $_POST['leaderboard_limit'] ?? '10');
            $this->siteSettings->setSetting('category_games_per_page', $_POST['category_games_per_page'] ?? '12');
            $this->siteSettings->setSetting('categories_per_page', $_POST['categories_per_page'] ?? '12');

            // Update email settings
            $this->siteSettings->setSetting('smtp_from_email', $_POST['smtp_from_email'] ?? '');
            $this->siteSettings->setSetting('smtp_from_name', $_POST['smtp_from_name'] ?? 'Game Portal');
            $this->siteSettings->setSetting('smtp_host', $_POST['smtp_host'] ?? '');
            $this->siteSettings->setSetting('smtp_port', $_POST['smtp_port'] ?? '');
            $this->siteSettings->setSetting('smtp_username', $_POST['smtp_username'] ?? '');

            // Only update SMTP password if provided
            if (!empty($_POST['smtp_password'])) {
                $this->siteSettings->setSetting('smtp_password', $_POST['smtp_password']);
            }

            // Update blog settings
            $this->siteSettings->setSetting('show_blog_section', isset($_POST['show_blog_section']) ? '1' : '0');
            $this->siteSettings->setSetting('blog_section_title', $_POST['blog_section_title'] ?? 'Latest Blog Posts');
            $this->siteSettings->setSetting('blog_section_description', $_POST['blog_section_description'] ?? 'Read our latest articles and stay updated with gaming news and tips.');

            // Handle Cloudflare Turnstile settings
            $this->siteSettings->setSetting('enable_turnstile', isset($_POST['enable_turnstile']) ? '1' : '0');
            $this->siteSettings->setSetting('enable_cookie_banner', isset($_POST['enable_cookie_banner']) ? '1' : '0');

            // Update Turnstile keys in .env file
            $turnstileSiteKey = $_POST['turnstile_site_key'] ?? '';
            $this->admin->updateEnvFile('TURNSTILE_SITE_KEY', $turnstileSiteKey);

            // Only update secret key if provided
            $turnstileSecretKey = $_POST['turnstile_secret_key'] ?? '';
            if (!empty($turnstileSecretKey)) {
                $this->admin->updateEnvFile('TURNSTILE_SECRET_KEY', $turnstileSecretKey);
            }

            // Update Google OAuth settings in .env file
            $googleClientId = $_POST['google_client_id'] ?? '';
            $this->admin->updateEnvFile('GOOGLE_CLIENT_ID', $googleClientId);

            // Only update client secret if provided
            $googleClientSecret = $_POST['google_client_secret'] ?? '';
            if (!empty($googleClientSecret)) {
                $this->admin->updateEnvFile('GOOGLE_CLIENT_SECRET', $googleClientSecret);
            }

            // Update OpenRouter AI settings in .env file
            $openrouterApiKey = $_POST['openrouter_api_key'] ?? '';
            $this->admin->updateEnvFile('OPENROUTER_API_KEY', $openrouterApiKey);

            $openrouterModel = $_POST['openrouter_model'] ?? 'meta-llama/llama-3.1-8b-instruct:free';
            $this->admin->updateEnvFile('OPENROUTER_MODEL', $openrouterModel);

            // Update points system settings
            $this->siteSettings->setSetting('enable_points_system', isset($_POST['enable_points_system']) ? '1' : '0');
            $this->siteSettings->setSetting('points_per_minute', $_POST['points_per_minute'] ?? '10');
            $this->siteSettings->setSetting('minimum_withdrawal', $_POST['minimum_withdrawal'] ?? '1000');
            $this->siteSettings->setSetting('withdrawal_rate', $_POST['withdrawal_rate'] ?? '100');
            $this->siteSettings->setSetting('withdrawal_methods', $_POST['withdrawal_methods'] ?? 'PayPal,Bank Transfer,Cryptocurrency');

            // Handle GamePix and ads.txt settings
            $gamepixAffiliateId = $_POST['gamepix_affiliate_id'] ?? '';
            $this->siteSettings->setSetting('gamepix_affiliate_id', $gamepixAffiliateId);
            $this->siteSettings->setSetting('gamepix_ads_txt', $_POST['gamepix_ads_txt'] ?? '');
            $this->siteSettings->setSetting('gamemonitize_ads_txt', $_POST['gamemonitize_ads_txt'] ?? '');
            $this->siteSettings->setSetting('custom_ads_txt', $_POST['custom_ads_txt'] ?? '');

            // If update_gamepix_urls is checked and we have a affiliate id, update all GamePix URLs
            if (isset($_POST['update_gamepix_urls']) && !empty($gamepixAffiliateId)) {
                $this->updateGamePixUrls($gamepixAffiliateId);
            }

            // Generate ads.txt file
            $this->generateAdsTxtFile();

            // Handle favicon upload
            if (isset($_FILES['favicon']) && $_FILES['favicon']['error'] === UPLOAD_ERR_OK) {
                $this->handleFileUpload('favicon', 'favicon', ['image/x-icon', 'image/png', 'image/jpeg', 'image/gif']);
            }

            // Handle logo upload
            if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
                $this->handleFileUpload('logo', 'logo', ['image/png', 'image/jpeg', 'image/gif']);
            }

            // Handle hero image upload
            if (isset($_FILES['hero_image']) && $_FILES['hero_image']['error'] === UPLOAD_ERR_OK) {
                $this->handleFileUpload('hero_image', 'hero_image', ['image/png', 'image/jpeg', 'image/gif']);
            }

            $success = true;
            $settings = $this->siteSettings->getAllSettings();
        }

        include __DIR__ . '/../views/admin/settings.php';
    }

    public function pointsSystem() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $success = false;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Update points system settings
            $this->siteSettings->setSetting('enable_points_system', isset($_POST['enable_points_system']) ? '1' : '0');
            $this->siteSettings->setSetting('points_per_minute', $_POST['points_per_minute'] ?? '10');
            $this->siteSettings->setSetting('minimum_withdrawal', $_POST['minimum_withdrawal'] ?? '1000');
            $this->siteSettings->setSetting('withdrawal_rate', $_POST['withdrawal_rate'] ?? '100');
            $this->siteSettings->setSetting('withdrawal_methods', $_POST['withdrawal_methods'] ?? 'PayPal,Bank Transfer,Cryptocurrency');

            $success = true;
            $settings = $this->siteSettings->getAllSettings(); // Refresh settings
        }

        // Get statistics if points system is enabled
        $stats = [];
        if (($settings['enable_points_system'] ?? '0') == '1') {
            $stats = $this->getPointsSystemStats();
        }

        include __DIR__ . '/../views/admin/points-system.php';
    }

    public function resetPointsSystemStats() {
        $this->checkAuth();
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            try {
                // Store the reset timestamp in site settings
                $resetTimestamp = date('Y-m-d H:i:s');
                $this->siteSettings->setSetting('points_stats_reset_date', $resetTimestamp);
                
                // Return success response
                header('Content-Type: application/json');
                echo json_encode(['success' => true, 'message' => 'Points system statistics display has been reset successfully.']);
                exit;
            } catch (Exception $e) {
                error_log("Error resetting points system stats: " . $e->getMessage());
                header('Content-Type: application/json');
                echo json_encode(['success' => false, 'message' => 'Failed to reset statistics display.']);
                exit;
            }
        }
        
        // If not POST, redirect back to points system page
        header('Location: /admin/points-system');
        exit;
    }

    public function withdrawalRequests() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $status = $_GET['status'] ?? null;
        $search = $_GET['search'] ?? null;
        $page = max(1, intval($_GET['page'] ?? 1));
        $limit = 20;
        $offset = ($page - 1) * $limit;
        
        $result = $this->coins->getWithdrawalRequests($status, $search, $limit, $offset);
        $withdrawalRequests = $result['data'];
        $totalRequests = $result['total'];
        $totalPages = ceil($totalRequests / $limit);
        
        // Pagination data for the view
        $pagination = [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total' => $totalRequests,
            'start' => min($offset + 1, $totalRequests),
            'end' => min($offset + $limit, $totalRequests)
        ];

        include __DIR__ . '/../views/admin/withdrawal-requests.php';
    }

    public function updateWithdrawalStatus() {
        $this->checkAuth();

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

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            return;
        }

        $input = json_decode(file_get_contents('php://input'), true);
        $requestId = $input['request_id'] ?? null;
        $status = $input['status'] ?? null;
        $adminNotes = $input['admin_notes'] ?? '';

        if (!$requestId || !$status || !in_array($status, ['approved', 'rejected'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
            return;
        }

        $result = $this->coins->updateWithdrawalStatus($requestId, $status, $adminNotes);

        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Withdrawal request updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update withdrawal request']);
        }
    }

    public function deleteWithdrawalRequest() {
        $this->checkAuth();

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

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            return;
        }

        $input = json_decode(file_get_contents('php://input'), true);
        $requestId = $input['request_id'] ?? null;

        if (!$requestId) {
            echo json_encode(['success' => false, 'message' => 'Invalid request ID']);
            return;
        }

        $result = $this->coins->deleteWithdrawalRequest($requestId);

        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Withdrawal request deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete withdrawal request']);
        }
    }

    public function withdrawalRequestDetails($requestId) {
        $this->checkAuth();

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

        // Get withdrawal request details
        $result = $this->coins->getWithdrawalRequests();
        $requests = $result['data'] ?? [];
        $request = null;
        
        foreach ($requests as $req) {
            if ($req['id'] == $requestId) {
                $request = $req;
                break;
            }
        }

        if (!$request) {
            echo json_encode(['success' => false, 'message' => 'Withdrawal request not found']);
            return;
        }

        $settings = $this->siteSettings->getAllSettings();
        $usdValue = $request['amount'] / ($settings['withdrawal_rate'] ?? 100);

        $html = '<div class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-400">User</label>
                    <p class="text-white">' . htmlspecialchars($request['username']) . '</p>
                    <p class="text-sm text-gray-400">' . htmlspecialchars($request['email']) . '</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-400">Amount</label>
                    <p class="text-white">' . number_format($request['amount']) . ' points</p>
                    <p class="text-sm text-green-400">$' . number_format($usdValue, 2) . ' USD</p>
                </div>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-400">Payment Method</label>
                <p class="text-white">' . htmlspecialchars($request['payment_method']) . '</p>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-400">Payment Details</label>
                <p class="text-white">' . htmlspecialchars($request['payment_details']) . '</p>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-400">Status</label>
                <span class="status-badge status-' . $request['status'] . '">' . ucfirst($request['status']) . '</span>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-400">Request Date</label>
                <p class="text-white">' . date('M j, Y g:i A', strtotime($request['created_at'])) . '</p>
            </div>';

        if (!empty($request['admin_notes'])) {
            $html .= '<div>
                <label class="block text-sm font-medium text-gray-400">Admin Notes</label>
                <p class="text-white">' . htmlspecialchars($request['admin_notes']) . '</p>
            </div>';
        }

        $html .= '</div>';

        echo json_encode(['success' => true, 'html' => $html]);
    }

    private function getPointsSystemStats() {
        try {
            $database = new Database();
            $db = $database->getConnection();
            $dbType = $_ENV['DB_TYPE'] ?? 'sqlite';

            // Check if tables exist before querying
            $tablesExist = true;
            
            if ($dbType === 'mysql') {
                $stmt = $db->query("SHOW TABLES LIKE 'user_coins'");
                if ($stmt->rowCount() === 0) $tablesExist = false;
                
                $stmt = $db->query("SHOW TABLES LIKE 'withdrawal_requests'");
                if ($stmt->rowCount() === 0) $tablesExist = false;
            } else {
                $stmt = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='user_coins'");
                if (!$stmt->fetchColumn()) $tablesExist = false;
                
                $stmt = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='withdrawal_requests'");
                if (!$stmt->fetchColumn()) $tablesExist = false;
            }

            if (!$tablesExist) {
                return [
                    'total_points_earned' => 0,
                    'users_with_points' => 0,
                    'pending_withdrawals' => 0,
                    'total_withdrawn' => 0
                ];
            }

            // Get the reset timestamp if it exists
            $resetDate = $this->siteSettings->getSetting('points_stats_reset_date');
            
            // Total points earned (from coin transactions since reset)
            if ($resetDate) {
                // Check if coin_transactions table exists
                if ($dbType === 'mysql') {
                    $stmt = $db->query("SHOW TABLES LIKE 'coin_transactions'");
                    $transactionsTableExists = $stmt->rowCount() > 0;
                } else {
                    $stmt = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='coin_transactions'");
                    $transactionsTableExists = (bool)$stmt->fetchColumn();
                }
                
                if ($transactionsTableExists) {
                    $stmt = $db->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM coin_transactions WHERE type IN ('game_reward', 'admin_award') AND created_at >= :reset_date");
                    $stmt->bindParam(':reset_date', $resetDate);
                    $stmt->execute();
                    $totalPointsEarned = $stmt->fetchColumn();
                } else {
                    // Fallback to user_coins if transactions table doesn't exist
                    $stmt = $db->query("SELECT COALESCE(SUM(total_earned), 0) as total FROM user_coins");
                    $totalPointsEarned = $stmt->fetchColumn();
                }
            } else {
                $stmt = $db->query("SELECT COALESCE(SUM(total_earned), 0) as total FROM user_coins");
                $totalPointsEarned = $stmt->fetchColumn();
            }

            // Users with points (current active users)
            $stmt = $db->query("SELECT COUNT(*) FROM user_coins WHERE balance > 0");
            $usersWithPoints = $stmt->fetchColumn();

            // Pending withdrawals (since reset date)
            if ($resetDate) {
                $stmt = $db->prepare("SELECT COUNT(*) FROM withdrawal_requests WHERE status = 'pending' AND created_at >= :reset_date");
                $stmt->bindParam(':reset_date', $resetDate);
                $stmt->execute();
                $pendingWithdrawals = $stmt->fetchColumn();
            } else {
                $stmt = $db->query("SELECT COUNT(*) FROM withdrawal_requests WHERE status = 'pending'");
                $pendingWithdrawals = $stmt->fetchColumn();
            }

            // Total withdrawn (approved requests since reset)
            if ($resetDate) {
                $stmt = $db->prepare("SELECT COALESCE(SUM(amount), 0) FROM withdrawal_requests WHERE status = 'approved' AND created_at >= :reset_date");
                $stmt->bindParam(':reset_date', $resetDate);
                $stmt->execute();
                $totalWithdrawn = $stmt->fetchColumn();
            } else {
                $stmt = $db->query("SELECT COALESCE(SUM(amount), 0) FROM withdrawal_requests WHERE status = 'approved'");
                $totalWithdrawn = $stmt->fetchColumn();
            }

            return [
                'total_points_earned' => $totalPointsEarned,
                'users_with_points' => $usersWithPoints,
                'pending_withdrawals' => $pendingWithdrawals,
                'total_withdrawn' => $totalWithdrawn,
                'reset_date' => $resetDate
            ];
        } catch (Exception $e) {
            error_log("Error getting points system stats: " . $e->getMessage());
            return [
                'total_points_earned' => 0,
                'users_with_points' => 0,
                'pending_withdrawals' => 0,
                'total_withdrawn' => 0,
                'reset_date' => null
            ];
        }
    }

    public function logout() {
        $this->admin->logout();
        header('Location: /admin/login');
        exit;
    }

    private function checkAuth() {
        if (!$this->admin->isLoggedIn()) {
            header('Location: /admin/login');
            exit;
        }
    }

    private function handleFileUpload($fileKey, $settingKey, $allowedTypes = []) {
        $uploadDir = __DIR__ . '/../public/images/';
        $fileName = basename($_FILES[$fileKey]['name']);
        $fileType = $_FILES[$fileKey]['type'];
        $uploadPath = $uploadDir . $fileName;

        // Check file type
        if (!empty($allowedTypes) && !in_array($fileType, $allowedTypes)) {
            return [
                'success' => false,
                'error' => 'Invalid file type. Allowed types: ' . implode(', ', $allowedTypes),
                'path' => ''
            ];
        }

        // Create directory if it doesn't exist
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        if (move_uploaded_file($_FILES[$fileKey]['tmp_name'], $uploadPath)) {
            $relativePath = '/public/images/' . $fileName;
            $this->siteSettings->setSetting($settingKey . '_path', $relativePath);
            return [
                'success' => true,
                'error' => '',
                'path' => $relativePath
            ];
        }

        return [
            'success' => false,
            'error' => 'Failed to upload file',
            'path' => ''
        ];
    }

    public function importGames() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $importResults = null;

        // Get game statistics
        $stats = $this->gameImporter->getGameStats();
        $totalGames = $stats['totalGames'];
        $gamemonetizeGames = $stats['gamemonetizeGames'];
        $gamepixGames = $stats['gamepixGames'];
        $gamezopGames = $stats['gamezopGames'];
        $totalCategories = $stats['totalCategories'];

        // Handle import request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $source = $_POST['source'] ?? 'all';
            $isAjax = isset($_POST['ajax']) && $_POST['ajax'] === 'true';
            $importResults = [];

            // If AJAX request, return JSON response
            if ($isAjax) {
                // Import games based on source
                if ($source === 'all' || $source === 'gamemonetize') {
                    $importResults['gamemonetize'] = $this->gameImporter->importGameMonetize();
                }

                if ($source === 'all' || $source === 'gamepix') {
                    $importResults['gamepix'] = $this->gameImporter->importGamePix();
                }

                if ($source === 'all' || $source === 'gamezop') {
                    $gamezopPropertyId = $_POST['gamezopPropertyId'] ?? '';
                    $importResults['gamezop'] = $this->gameImporter->importGamezop($gamezopPropertyId);
                }

                // Handle manual game import
                if ($source === 'manual') {
                    // Process thumbnail upload
                    $thumbnailPath = '';
                    if (isset($_FILES['thumbnailFile']) && $_FILES['thumbnailFile']['error'] === UPLOAD_ERR_OK) {
                        $uploadDir = __DIR__ . '/../public/images/games/';

                        // Create directory if it doesn't exist
                        if (!file_exists($uploadDir)) {
                            mkdir($uploadDir, 0755, true);
                        }

                        $fileName = time() . '_' . basename($_FILES['thumbnailFile']['name']);
                        $uploadPath = $uploadDir . $fileName;

                        if (move_uploaded_file($_FILES['thumbnailFile']['tmp_name'], $uploadPath)) {
                            $thumbnailPath = '/public/images/games/' . $fileName;
                        }
                    }

                    // Import the manual game
                    $importResults['manual'] = $this->gameImporter->importManualGame($_POST, $thumbnailPath);
                }

                // Update statistics after import
                $stats = $this->gameImporter->getGameStats();

                // Return JSON response
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => true,
                    'results' => $importResults,
                    'stats' => $stats
                ]);
                exit;
            } else {
                // Regular form submission
                if ($source === 'all' || $source === 'gamemonetize') {
                    $importResults['gamemonetize'] = $this->gameImporter->importGameMonetize();
                }

                if ($source === 'all' || $source === 'gamepix') {
                    $importResults['gamepix'] = $this->gameImporter->importGamePix();
                }

                if ($source === 'all' || $source === 'gamezop') {
                    $gamezopPropertyId = $_POST['gamezopPropertyId'] ?? '';
                    $importResults['gamezop'] = $this->gameImporter->importGamezop($gamezopPropertyId);
                }

                // Handle manual game import
                if ($source === 'manual') {
                    // Process thumbnail upload
                    $thumbnailPath = '';
                    if (isset($_FILES['thumbnailFile']) && $_FILES['thumbnailFile']['error'] === UPLOAD_ERR_OK) {
                        $uploadDir = __DIR__ . '/../public/images/games/';

                        // Create directory if it doesn't exist
                        if (!file_exists($uploadDir)) {
                            mkdir($uploadDir, 0755, true);
                        }

                        $fileName = time() . '_' . basename($_FILES['thumbnailFile']['name']);
                        $uploadPath = $uploadDir . $fileName;

                        if (move_uploaded_file($_FILES['thumbnailFile']['tmp_name'], $uploadPath)) {
                            $thumbnailPath = '/public/images/games/' . $fileName;
                        }
                    }

                    // Import the manual game
                    $importResults['manual'] = $this->gameImporter->importManualGame($_POST, $thumbnailPath);
                }

                // Update statistics after import
                $stats = $this->gameImporter->getGameStats();
                $totalGames = $stats['totalGames'];
                $gamemonetizeGames = $stats['gamemonetizeGames'];
                $gamepixGames = $stats['gamepixGames'];
                $gamezopGames = $stats['gamezopGames'];
                $totalCategories = $stats['totalCategories'];
            }
        }

        include __DIR__ . '/../views/admin/import-games.php';
    }

    /**
     * Stream import games progress
     */
    public function importGamesStream() {
        $this->checkAuth();

        // Set error handling to prevent HTML error output
        ini_set('display_errors', 0);

        try {
            // Set headers for SSE
            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');
            header('Connection: keep-alive');
            header('X-Accel-Buffering: no'); // Disable Nginx buffering

            // Disable output buffering
            if (ob_get_level()) {
                ob_end_clean();
            }

            // Get source parameter
            $source = $_GET['source'] ?? 'all';

            // Get gamepixPage parameter with default of 1
            $gamepixPage = isset($_GET['gamepixPage']) ? (int)$_GET['gamepixPage'] : 1;
            // Ensure it's at least 1
            $gamepixPage = max(1, $gamepixPage);

            // Store results
            $importResults = [];

            // Send initial message
            echo "data: " . json_encode([
                'type' => 'log',
                'source' => 'system',
                'message' => 'Starting import process...'
            ]) . "\n\n";
            flush();

            // Create callback function for progress updates
            $progressCallback = function($data) {
                echo "data: " . json_encode($data) . "\n\n";
                flush();
            };

            // Import games based on source
            if ($source === 'all' || $source === 'gamemonetize') {
                try {
                    $importResults['gamemonetize'] = $this->gameImporter->importGameMonetize($progressCallback);
                } catch (Exception $e) {
                    // Log error and continue
                    error_log('Error in GameMonetize import: ' . $e->getMessage());
                    echo "data: " . json_encode([
                        'type' => 'log',
                        'source' => 'gamemonetize',
                        'message' => '<span class="text-red-500">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'
                    ]) . "\n\n";
                    flush();

                    $importResults['gamemonetize'] = [
                        'success' => false,
                        'count' => 0,
                        'message' => $e->getMessage()
                    ];
                }
            }

            if ($source === 'all' || $source === 'gamepix') {
                try {
                    $importResults['gamepix'] = $this->gameImporter->importGamePix($gamepixPage, $progressCallback);
                } catch (Exception $e) {
                    // Log error and continue
                    error_log('Error in GamePix import: ' . $e->getMessage());
                    echo "data: " . json_encode([
                        'type' => 'log',
                        'source' => 'gamepix',
                        'message' => '<span class="text-red-500">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'
                    ]) . "\n\n";
                    flush();

                    $importResults['gamepix'] = [
                        'success' => false,
                        'count' => 0,
                        'message' => $e->getMessage()
                    ];
                }
            }

            if ($source === 'all' || $source === 'gamezop') {
                try {
                    $gamezopPropertyId = isset($_GET['gamezopPropertyId']) ? $_GET['gamezopPropertyId'] : '';
                    $importResults['gamezop'] = $this->gameImporter->importGamezop($gamezopPropertyId, $progressCallback);
                } catch (Exception $e) {
                    // Log error and continue
                    error_log('Error in Gamezop import: ' . $e->getMessage());
                    echo "data: " . json_encode([
                        'type' => 'log',
                        'source' => 'gamezop',
                        'message' => '<span class="text-red-500">Error: ' . htmlspecialchars($e->getMessage()) . '</span>'
                    ]) . "\n\n";
                    flush();

                    $importResults['gamezop'] = [
                        'success' => false,
                        'count' => 0,
                        'message' => $e->getMessage()
                    ];
                }
            }

            // Update statistics after import
            $stats = $this->gameImporter->getGameStats();

            // Send completion event
            echo "data: " . json_encode([
                'type' => 'complete',
                'results' => $importResults,
                'stats' => $stats
            ]) . "\n\n";

            // Store results in session for status endpoint
            $_SESSION['import_results'] = [
                'results' => $importResults,
                'stats' => $stats
            ];
        } catch (Exception $e) {
            // Log the error
            error_log('Error in import stream: ' . $e->getMessage());

            // Send error event
            echo "data: " . json_encode([
                'type' => 'error',
                'message' => 'Server error: ' . $e->getMessage()
            ]) . "\n\n";
        }

        exit;
    }

    /**
     * Get import games status
     */
    public function importGamesStatus() {
        $this->checkAuth();

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

        if (isset($_SESSION['import_results'])) {
            echo json_encode($_SESSION['import_results']);
        } else {
            echo json_encode(['success' => false, 'message' => 'No import results available']);
        }

        exit;
    }

    /**
     * Games management page
     */
    public function games() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $limit = 20;
        $offset = ($page - 1) * $limit;
        $search = isset($_GET['search']) ? $_GET['search'] : '';

        // Get games with pagination
        $games = $this->game->getGamesForAdmin($limit, $offset, $search);
        $totalGames = $this->game->getTotalGamesForAdmin($search);
        $totalPages = ceil($totalGames / $limit);

        // Get all categories for the dropdown
        $categories = $this->category->getAllCategoriesForAdmin();

        // Handle success/error messages
        $success = isset($_GET['success']) ? $_GET['success'] : '';
        $error = isset($_GET['error']) ? $_GET['error'] : '';

        include __DIR__ . '/../views/admin/games.php';
    }

    /**
     * Delete a game
     */
    public function deleteGame() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['game_id'])) {
            $gameId = (int)$_POST['game_id'];

            if ($this->game->deleteGame($gameId)) {
                header('Location: /admin/games?success=Game+deleted+successfully');
                exit;
            } else {
                header('Location: /admin/games?error=Failed+to+delete+game');
                exit;
            }
        }

        header('Location: /admin/games');
        exit;
    }

    /**
     * Delete all games from a specific source
     */
    public function deleteGamesBySource() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['source'])) {
            $source = $_POST['source'];
            $validSources = ['gamemonetize', 'gamepix', 'gamezop', 'manual', 'all'];

            if (!in_array($source, $validSources)) {
                header('Location: /admin/import-games?error=Invalid+source');
                exit;
            }

            if ($source === 'all') {
                // Delete all games from all sources
                if ($this->game->deleteAllGames()) {
                    // Update statistics after deletion
                    $stats = $this->gameImporter->getGameStats();
                    $_SESSION['import_results'] = ['stats' => $stats];

                    header('Location: /admin/import-games?success=All+games+deleted+successfully');
                    exit;
                } else {
                    header('Location: /admin/import-games?error=Failed+to+delete+all+games');
                    exit;
                }
            } else {
                // Delete games from a specific source
                if ($this->game->deleteGamesBySource($source)) {
                    // Update statistics after deletion
                    $stats = $this->gameImporter->getGameStats();
                    $_SESSION['import_results'] = ['stats' => $stats];

                    header('Location: /admin/import-games?success=All+games+from+' . urlencode($source) . '+deleted+successfully');
                    exit;
                } else {
                    header('Location: /admin/import-games?error=Failed+to+delete+games+from+' . urlencode($source));
                    exit;
                }
            }
        }

        header('Location: /admin/import-games');
        exit;
    }

    public function editGameForm($id) {
        $this->checkAuth();
        $game = $this->game->getGameById($id);
        $categories = $this->category->getAllCategoriesSimple(); // Fetch categories for the dropdown

        if (!$game) {
            // Handle game not found, maybe redirect with an error
            header('Location: /admin/games?error=Game not found');
            exit;
        }

        $settings = $this->siteSettings->getAllSettings(); // Load site settings
        include __DIR__ . '/../views/admin/edit-game.php';
    }

    public function updateGame() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $gameData = [
                'id' => $_POST['id'] ?? null,
                'title' => $_POST['title'] ?? '',
                'description' => $_POST['description'] ?? '',
                'thumbnail' => $_POST['thumbnail'] ?? '',
                'category_id' => !empty($_POST['category_id']) ? $_POST['category_id'] : null
            ];

            if (empty($gameData['id'])) {
                header('Location: /admin/games?error=Invalid game ID');
                exit;
            }

            // Basic validation (can be expanded)
            if (empty($gameData['title']) || empty($gameData['thumbnail'])) {
                $game = $this->game->getGameById($gameData['id']); // Reload original game data
                $categories = $this->category->getAllCategoriesSimple();
                $error = 'Title, URL, and Thumbnail URL are required.';
                // Pass existing data back to the form
                $game['title'] = $gameData['title'];
                $game['description'] = $gameData['description'];
                $game['thumbnail'] = $gameData['thumbnail'];
                $game['category_id'] = $gameData['category_id'];
                include __DIR__ . '/../views/admin/edit-game.php';
                exit;
            }

            $result = $this->game->updateGame($gameData);

            if ($result) {
                header('Location: /admin/games/edit/' . $gameData['id'] . '?success=Game updated successfully');
            } else {
                // Pass existing data back to the form in case of error
                $game = $gameData; // Use submitted data to show what user entered
                $game['id'] = $_POST['id']; // Ensure ID is preserved
                $categories = $this->category->getAllCategoriesSimple();
                $error = 'Failed to update game. Please try again.';
                include __DIR__ . '/../views/admin/edit-game.php';
            }
            exit;
        } else {
            // Redirect if not a POST request
            header('Location: /admin/games');
            exit;
        }
    }

    /**
     * Update game category
     */
    public function updateGameCategory() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['game_id']) && isset($_POST['category_id'])) {
            $gameId = (int)$_POST['game_id'];
            $categoryId = (int)$_POST['category_id'];

            if ($this->game->updateGameCategory($gameId, $categoryId)) {
                header('Location: /admin/games?success=Game+category+updated+successfully');
                exit;
            } else {
                header('Location: /admin/games?error=Failed+to+update+game+category');
                exit;
            }
        }

        header('Location: /admin/games');
        exit;
    }

    /**
     * Update game featured status
     */
    public function updateGameFeatured() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['game_id']) && isset($_POST['featured'])) {
            $gameId = (int)$_POST['game_id'];
            $featured = (int)$_POST['featured'];

            if ($this->game->updateGameFeatured($gameId, $featured)) {
                header('Location: /admin/games?success=Game+featured+status+updated+successfully');
                exit;
            } else {
                header('Location: /admin/games?error=Failed+to+update+game+featured+status');
                exit;
            }
        }

        header('Location: /admin/games');
        exit;
    }

    /**
     * Categories management page
     */
    public function categories() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();

        // Pagination parameters
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $limit = 10; // Number of categories per page
        $offset = ($page - 1) * $limit;

        // Get categories with pagination
        $categories = $this->category->getAllCategoriesForAdmin($limit, $offset);
        $totalCategories = $this->category->getTotalCategories();
        $totalPages = ceil($totalCategories / $limit);

        // Handle success/error messages
        $success = isset($_GET['success']) ? $_GET['success'] : '';
        $error = isset($_GET['error']) ? $_GET['error'] : '';

        include __DIR__ . '/../views/admin/categories.php';
    }

    /**
     * Add a new category
     */
    public function addCategory() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $name = $_POST['name'] ?? '';
            $slug = $_POST['slug'] ?? '';
            $sort_order = !empty($_POST['sort_order']) ? (int)$_POST['sort_order'] : null;

            if (empty($name)) {
                header('Location: /admin/categories?error=Category+name+is+required');
                exit;
            }

            if ($this->category->addCategory($name, $slug, $sort_order)) {
                header('Location: /admin/categories?success=Category+added+successfully');
                exit;
            } else {
                header('Location: /admin/categories?error=Failed+to+add+category');
                exit;
            }
        }

        header('Location: /admin/categories');
        exit;
    }

    /**
     * Edit a category
     */
    public function editCategory() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $id = (int)$_POST['id'] ?? 0;
            $name = $_POST['name'] ?? '';
            $slug = $_POST['slug'] ?? '';
            $sort_order = !empty($_POST['sort_order']) ? (int)$_POST['sort_order'] : null;

            if (empty($name)) {
                header('Location: /admin/categories?error=Category+name+is+required');
                exit;
            }

            if ($this->category->updateCategory($id, $name, $slug, $sort_order)) {
                header('Location: /admin/categories?success=Category+updated+successfully');
                exit;
            } else {
                header('Location: /admin/categories?error=Failed+to+update+category');
                exit;
            }
        }

        header('Location: /admin/categories');
        exit;
    }

    /**
     * Delete a category
     */
    public function deleteCategory() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['category_id'])) {
            $categoryId = (int)$_POST['category_id'];

            if ($this->category->deleteCategory($categoryId)) {
                header('Location: /admin/categories?success=Category+deleted+successfully');
                exit;
            } else {
                header('Location: /admin/categories?error=Failed+to+delete+category');
                exit;
            }
        }

        header('Location: /admin/categories');
        exit;
    }

    /**
     * Update category sort order
     */
    public function updateCategorySortOrder() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $sortOrdersJson = $_POST['sort_orders'] ?? '';
            $sortOrders = json_decode($sortOrdersJson, true) ?? [];
            
            if (!empty($sortOrders)) {
                if ($this->category->updateMultipleSortOrders($sortOrders)) {
                    echo json_encode(['success' => true, 'message' => 'Sort order updated successfully']);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to update sort order']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'No sort order data provided']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
        }
        exit;
    }

    /**
     * Admin credentials page
     */
    public function credentials() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $success = false;
        $error = '';

        // Get current admin email
        $currentEmail = $this->admin->getEmail();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';
            $confirmPassword = $_POST['confirm_password'] ?? '';

            // Validate inputs
            if (empty($email)) {
                $error = 'Email is required';
            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $error = 'Invalid email format';
            } elseif (empty($password)) {
                $error = 'Password is required';
            } elseif (strlen($password) < 8) {
                $error = 'Password must be at least 8 characters long';
            } elseif ($password !== $confirmPassword) {
                $error = 'Passwords do not match';
            } else {
                // Update credentials
                if ($this->admin->updateCredentials($email, $password)) {
                    $success = true;
                    $currentEmail = $email;
                } else {
                    $error = 'Failed to update credentials';
                }
            }
        }

        include __DIR__ . '/../views/admin/credentials.php';
    }

    public function blogPosts() {
        $this->checkAuth();

        $posts = $this->blog->getAllPosts(null, 0, 'published');
        $settings = $this->siteSettings->getAllSettings();

        ob_start();
        include __DIR__ . '/../views/admin/blog-posts.php';
        $content = ob_get_clean();

        $pageTitle = 'Blog Posts';
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function addBlogPost() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $success = false;
        $error = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = $_POST['title'] ?? '';
            $content = $_POST['content'] ?? '';
            $metaDescription = $_POST['meta_description'] ?? '';
            $tags = $_POST['tags'] ?? '';

            // Handle featured image upload
            $featuredImage = '';
            if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = $this->handleFileUpload('featured_image', 'blog_featured_image', ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
                if ($uploadResult['success']) {
                    $featuredImage = $uploadResult['path'];
                } else {
                    $error = $uploadResult['error'];
                }
            }

            if (empty($error)) {
                if ($this->blog->createPost($title, $content, $metaDescription, $featuredImage, $tags)) {
                    $success = true;
                    header('Location: /admin/blog-posts');
                    exit;
                } else {
                    $error = 'Failed to create blog post';
                }
            }
        }

        ob_start();
        include __DIR__ . '/../views/admin/blog-post-form.php';
        $content = ob_get_clean();

        $pageTitle = 'Add Blog Post';
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function editBlogPost($id = null) {
        $this->checkAuth();

        if ($id === null && isset($_GET['id'])) {
            $id = $_GET['id'];
        }

        $post = $this->blog->getPostById($id);
        if (!$post || !is_array($post)) {
            header('Location: /admin/blog-posts');
            exit;
        }

        $settings = $this->siteSettings->getAllSettings();
        $success = false;
        $error = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = $_POST['title'] ?? '';
            $content = $_POST['content'] ?? '';
            $metaDescription = $_POST['meta_description'] ?? '';
            $tags = $_POST['tags'] ?? '';

            // Handle featured image upload
            $featuredImage = isset($post['featured_image']) ? $post['featured_image'] : '';
            if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = $this->handleFileUpload('featured_image', 'blog_featured_image', ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
                if ($uploadResult['success']) {
                    $featuredImage = $uploadResult['path'];
                } else {
                    $error = $uploadResult['error'];
                }
            }

            if (empty($error)) {
                if ($this->blog->updatePost($id, $title, $content, $metaDescription, $featuredImage, $tags)) {
                    $success = true;
                    // Refresh post data
                    $refreshedPost = $this->blog->getPostById($id);
                    if (is_array($refreshedPost)) {
                        $post = $refreshedPost;
                    }
                    // If refreshedPost is not an array, we keep the existing $post
                } else {
                    $error = 'Failed to update blog post';
                }
            }
        }

        ob_start();
        include __DIR__ . '/../views/admin/blog-post-form.php';
        $content = ob_get_clean();

        $pageTitle = 'Edit Blog Post';
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function deleteBlogPost() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
            $id = $_POST['id'];

            if ($this->blog->deletePost($id)) {
                header('Location: /admin/blog-posts');
                exit;
            }
        }

        header('Location: /admin/blog-posts');
        exit;
    }

    public function codeAndAds() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $success = false;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Update code injection settings
            $this->siteSettings->setSetting('head_code', $_POST['head_code'] ?? '');
            $this->siteSettings->setSetting('body_start_code', $_POST['body_start_code'] ?? '');
            $this->siteSettings->setSetting('body_end_code', $_POST['body_end_code'] ?? '');

            // Update ad settings
            $this->siteSettings->setSetting('enable_ads', isset($_POST['enable_ads']) ? '1' : '0');
            $this->siteSettings->setSetting('header_ad', $_POST['header_ad'] ?? '');
            $this->siteSettings->setSetting('footer_ad', $_POST['footer_ad'] ?? '');
            $this->siteSettings->setSetting('sidebar_ad', $_POST['sidebar_ad'] ?? '');
            $this->siteSettings->setSetting('between_content_ad', $_POST['between_content_ad'] ?? '');
            $this->siteSettings->setSetting('game_page_ad', $_POST['game_page_ad'] ?? '');
            $this->siteSettings->setSetting('category_page_ad', $_POST['category_page_ad'] ?? '');
            $this->siteSettings->setSetting('blog_page_ad', $_POST['blog_page_ad'] ?? '');
            $this->siteSettings->setSetting('blog_post_ad', $_POST['blog_post_ad'] ?? '');
            $this->siteSettings->setSetting('search_page_ad', $_POST['search_page_ad'] ?? '');

            $success = true;
            $settings = $this->siteSettings->getAllSettings();
        }

        include __DIR__ . '/../views/admin/code-and-ads.php';
    }

    // Page Management Methods

    public function pages() {
        $this->checkAuth();

        $pages = $this->page->getAllPages(null, 0, 'published');
        $settings = $this->siteSettings->getAllSettings();

        ob_start();
        include __DIR__ . '/../views/admin/pages.php';
        $content = ob_get_clean();

        $pageTitle = 'Pages';
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function addPage() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $success = false;
        $error = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = $_POST['title'] ?? '';
            $content = $_POST['content'] ?? '';
            $metaDescription = $_POST['meta_description'] ?? '';

            // Handle featured image upload
            $featuredImage = '';
            if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = $this->handleFileUpload('featured_image', 'page_featured_image', ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
                if ($uploadResult['success']) {
                    $featuredImage = $uploadResult['path'];
                } else {
                    $error = $uploadResult['error'];
                }
            }

            if (empty($error)) {
                if ($this->page->createPage($title, $content, $metaDescription, $featuredImage)) {
                    $success = true;
                    header('Location: /admin/pages');
                    exit;
                } else {
                    $error = 'Failed to create page';
                }
            }
        }

        ob_start();
        include __DIR__ . '/../views/admin/page-form.php';
        $content = ob_get_clean();

        $pageTitle = 'Add Page';
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function editPage($id = null) {
        $this->checkAuth();

        if ($id === null && isset($_GET['id'])) {
            $id = $_GET['id'];
        }

        $page = $this->page->getPageById($id);
        if (!$page || !is_array($page)) {
            header('Location: /admin/pages');
            exit;
        }

        $settings = $this->siteSettings->getAllSettings();
        $success = false;
        $error = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = $_POST['title'] ?? '';
            $content = $_POST['content'] ?? '';
            $metaDescription = $_POST['meta_description'] ?? '';

            // Handle featured image upload
            $featuredImage = isset($page['featured_image']) ? $page['featured_image'] : '';
            if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
                $uploadResult = $this->handleFileUpload('featured_image', 'page_featured_image', ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
                if ($uploadResult['success']) {
                    $featuredImage = $uploadResult['path'];
                } else {
                    $error = $uploadResult['error'];
                }
            }

            if (empty($error)) {
                if ($this->page->updatePage($id, $title, $content, $metaDescription, $featuredImage)) {
                    $success = true;
                    // Refresh page data
                    $refreshedPage = $this->page->getPageById($id);
                    if (is_array($refreshedPage)) {
                        $page = $refreshedPage;
                    }
                } else {
                    $error = 'Failed to update page';
                }
            }
        }

        ob_start();
        include __DIR__ . '/../views/admin/page-form.php';
        $content = ob_get_clean();

        $pageTitle = 'Edit Page';
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function deletePage() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
            $id = $_POST['id'];

            if ($this->page->deletePage($id)) {
                header('Location: /admin/pages');
                exit;
            }
        }

        header('Location: /admin/pages');
        exit;
    }

    // Menu Management Methods

    public function menus() {
        $this->checkAuth();

        $menus = $this->menu->getAllMenus();
        $settings = $this->siteSettings->getAllSettings();

        ob_start();
        include __DIR__ . '/../views/admin/menus.php';
        $content = ob_get_clean();

        $pageTitle = 'Menus';
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function addMenu() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $success = false;
        $error = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $name = $_POST['name'] ?? '';
            $location = $_POST['location'] ?? null;

            if (empty($name)) {
                $error = 'Menu name is required';
            } else {
                $menuId = $this->menu->createMenu($name, $location);

                if ($menuId) {
                    header('Location: /admin/menus/edit?id=' . $menuId);
                    exit;
                } else {
                    $error = 'Failed to create menu';
                }
            }
        }

        ob_start();
        include __DIR__ . '/../views/admin/menu-form.php';
        $content = ob_get_clean();

        $pageTitle = 'Add Menu';
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function editMenu($id = null) {
        $this->checkAuth();

        if ($id === null && isset($_GET['id'])) {
            $id = $_GET['id'];
        }

        $menuData = $this->menu->getMenuById($id);
        if (!$menuData || !is_array($menuData)) {
            header('Location: /admin/menus');
            exit;
        }

        $menuItems = $this->menu->getMenuItems($id);
        $pages = $this->page->getAllPages();
        $settings = $this->siteSettings->getAllSettings();
        $success = false;
        $error = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (isset($_POST['action'])) {
                switch ($_POST['action']) {
                    case 'update_menu':
                        $name = $_POST['name'] ?? '';
                        $location = $_POST['location'] ?? null;

                        if (empty($name)) {
                            $error = 'Menu name is required';
                        } else {
                            if ($this->menu->updateMenu($id, $name, $location)) {
                                $success = true;
                                $menuData = $this->menu->getMenuById($id);
                            } else {
                                $error = 'Failed to update menu';
                            }
                        }
                        break;

                    case 'add_item':
                        $type = $_POST['item_type'] ?? 'custom';
                        $title = $_POST['item_title'] ?? '';
                        $url = $_POST['item_url'] ?? '';
                        $target = $_POST['item_target'] ?? '_self';
                        $icon = $_POST['item_icon'] ?? null;
                        $objectId = null;

                        // If it's a page link, get the URL from the page
                        if ($type === 'page' && isset($_POST['page_id'])) {
                            $pageId = $_POST['page_id'];
                            $pageData = $this->page->getPageById($pageId);
                            if ($pageData) {
                                $title = $title ?: $pageData['title'];
                                $url = '/page/' . $pageData['slug'];
                                $objectId = $pageId;
                            }
                        }

                        if (empty($title) || empty($url)) {
                            $error = 'Title and URL are required';
                        } else {
                            // Get the highest order position
                            $items = $this->menu->getAllMenuItemsFlat($id);
                            $orderPosition = 0;
                            if (!empty($items)) {
                                $orderPosition = max(array_column($items, 'order_position')) + 1;
                            }

                            if ($this->menu->addMenuItem($id, $title, $url, 0, $target, $orderPosition, $type, $objectId, $icon)) {
                                $success = true;
                                $menuItems = $this->menu->getMenuItems($id);
                            } else {
                                $error = 'Failed to add menu item';
                            }
                        }
                        break;

                    case 'update_items_order':
                        if (isset($_POST['items_order']) && is_array($_POST['items_order'])) {
                            $itemsOrder = $_POST['items_order'];
                            $formattedItems = [];

                            foreach ($itemsOrder as $index => $item) {
                                $formattedItems[] = [
                                    'id' => $item['id'],
                                    'parent_id' => $item['parent_id'] ?? 0,
                                    'order_position' => $index
                                ];
                            }

                            if ($this->menu->updateMenuItemsOrder($formattedItems)) {
                                $success = true;
                                $menuItems = $this->menu->getMenuItems($id);
                            } else {
                                $error = 'Failed to update menu items order';
                            }
                        }
                        break;
                }
            }
        }

        ob_start();
        include __DIR__ . '/../views/admin/menu-edit.php';
        $content = ob_get_clean();

        $pageTitle = 'Edit Menu: ' . htmlspecialchars($menuData['name']);
        include __DIR__ . '/../views/admin/layout.php';
    }

    public function deleteMenu() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
            $id = $_POST['id'];

            if ($this->menu->deleteMenu($id)) {
                header('Location: /admin/menus');
                exit;
            }
        }

        header('Location: /admin/menus');
        exit;
    }

    public function deleteMenuItem() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id']) && isset($_POST['menu_id'])) {
            $id = $_POST['id'];
            $menuId = $_POST['menu_id'];

            if ($this->menu->deleteMenuItem($id)) {
                header('Location: /admin/menus/edit?id=' . $menuId);
                exit;
            }
        }

        if (isset($_POST['menu_id'])) {
            header('Location: /admin/menus/edit?id=' . $_POST['menu_id']);
        } else {
            header('Location: /admin/menus');
        }
        exit;
    }

    public function editMenuItem() {
        $this->checkAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
            $id = $_POST['id'];
            $title = $_POST['title'] ?? '';
            $url = $_POST['url'] ?? '';
            $target = $_POST['target'] ?? '_self';
            $icon = $_POST['icon'] ?? null;

            $menuItem = $this->menu->getMenuItem($id);
            if ($menuItem) {
                if (empty($title) || empty($url)) {
                    echo json_encode(['success' => false, 'message' => 'Title and URL are required']);
                    exit;
                }

                if ($this->menu->updateMenuItem(
                    $id,
                    $title,
                    $url,
                    $menuItem['parent_id'],
                    $target,
                    $menuItem['order_position'],
                    $menuItem['type'],
                    $menuItem['object_id'],
                    $icon
                )) {
                    echo json_encode(['success' => true]);
                    exit;
                }
            }
        }

        echo json_encode(['success' => false, 'message' => 'Failed to update menu item']);
        exit;
    }

    /**
     * Update all GamePix game URLs with the new affiliate ID
     */
    private function updateGamePixUrls($affiliateId) {
        // Get all GamePix games
        $games = $this->game->getGamesBySource('gamepix');

        foreach ($games as $game) {
            // Parse the current embed code
            $embedCode = $game['embed_code'];

            // Update the URL in the embed code with the new affiliate ID
            $updatedEmbedCode = preg_replace(
                '/src="https:\/\/play\.gamepix\.com\/[^\/]+\/embed\?sid=[^"]*"/',
                'src="https://play.gamepix.com/' . $game['slug'] . '/embed?sid=' . $affiliateId . '"',
                $embedCode
            );

            // Update the game with the new embed code
            $this->game->updateGameEmbed($game['id'], $updatedEmbedCode);
        }
    }

    /**
     * Get the base URL of the application
     */
    public function getBaseUrl() {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'];
        return $protocol . '://' . $host;
    }

    private function generateAdsTxtFile() {
        $content = "";

        // Add GamePix ads.txt content
        $gamepixAdsTxt = $this->siteSettings->getSetting('gamepix_ads_txt', '');
        if (!empty($gamepixAdsTxt)) {
            $content .= "# GamePix Ads.txt\n" . $gamepixAdsTxt . "\n\n";
        }

        // Add GameMonitize ads.txt content
        $gamemonitizeAdsTxt = $this->siteSettings->getSetting('gamemonitize_ads_txt', '');
        if (!empty($gamemonitizeAdsTxt)) {
            $content .= "# GameMonitize Ads.txt\n" . $gamemonitizeAdsTxt . "\n\n";
        }

        // Add custom ads.txt content
        $customAdsTxt = $this->siteSettings->getSetting('custom_ads_txt', '');
        if (!empty($customAdsTxt)) {
            $content .= "# Custom Ads.txt\n" . $customAdsTxt . "\n";
        }

        // Write to ads.txt file
        file_put_contents(__DIR__ . '/../ads.txt', $content);
    }

    /**
     * Users management page
     */
    public function users() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $search = isset($_GET['search']) ? $_GET['search'] : '';

        $result = $this->userManagement->getAllUsers($page, 20, $search);
        $users = $result['users'];
        $totalUsers = $result['total'];
        $totalPages = $result['pages'];
        $currentPage = $result['current_page'];

        $userStats = $this->userManagement->getUserStats();

        $pageTitle = 'User Management';
        include __DIR__ . '/../views/admin/users.php';
    }

    /**
     * Edit user page
     */
    public function editUser() {
        $this->checkAuth();

        $settings = $this->siteSettings->getAllSettings();
        $success = false;
        $error = '';

        $userId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

        if ($userId === 0) {
            header('Location: /admin/users');
            exit;
        }

        $user = $this->userManagement->getUserById($userId);

        if (!$user) {
            header('Location: /admin/users');
            exit;
        }

        // Get user coins data if points system is enabled
        $userCoins = null;
        if (($settings['enable_points_system'] ?? '0') == '1') {
            $userCoins = $this->coins->getUserBalance($userId);
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $action = isset($_POST['action']) ? $_POST['action'] : '';

            if ($action === 'update_user') {
                $userData = [
                    'username' => $_POST['username'] ?? '',
                    'email' => $_POST['email'] ?? '',
                    'name' => $_POST['name'] ?? '',
                    'role' => $_POST['role'] ?? 'user',
                    'is_active' => isset($_POST['is_active']) ? 1 : 0,
                    'email_verified' => isset($_POST['email_verified']) ? 1 : 0
                ];

                $result = $this->userManagement->updateUser($userId, $userData);

                if ($result) {
                    $success = true;
                    $user = $this->userManagement->getUserById($userId); // Refresh user data
                } else {
                    $error = 'Failed to update user';
                }
            } elseif ($action === 'update_password') {
                $password = $_POST['password'] ?? '';
                $confirmPassword = $_POST['confirm_password'] ?? '';

                if (empty($password)) {
                    $error = 'Password cannot be empty';
                } elseif ($password !== $confirmPassword) {
                    $error = 'Passwords do not match';
                } else {
                    $result = $this->userManagement->updateUserPassword($userId, $password);

                    if ($result) {
                        $success = true;
                    } else {
                        $error = 'Failed to update password';
                    }
                }
            } elseif ($action === 'update_points' && ($settings['enable_points_system'] ?? '0') == '1') {
                $newBalance = isset($_POST['points_balance']) ? (int)$_POST['points_balance'] : 0;
                
                if ($newBalance < 0) {
                    $error = 'Points balance cannot be negative';
                } else {
                    $result = $this->coins->updateUserBalance($userId, $newBalance, 'Admin balance adjustment');
                    
                    if ($result) {
                        $success = true;
                        // Refresh user coins data
                        $userCoins = $this->coins->getUserBalance($userId);
                    } else {
                        $error = 'Failed to update points balance';
                    }
                }
            }
        }

        $pageTitle = 'Edit User';
        include __DIR__ . '/../views/admin/edit-user.php';
    }

    /**
     * Delete user
     */
    public function deleteUser() {
        $this->checkAuth();

        $userId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

        if ($userId === 0) {
            header('Location: /admin/users');
            exit;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $result = $this->userManagement->deleteUser($userId);

            if ($result) {
                $_SESSION['admin_success'] = 'User deleted successfully';
            } else {
                $_SESSION['admin_error'] = 'Failed to delete user. Admin users cannot be deleted.';
            }
        }

        header('Location: /admin/users');
        exit;
    }

    /**
     * Test SMTP connection
     */
    public function testSmtp() {
        $this->checkAuth();

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

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            exit;
        }

        try {
            $emailHelper = new EmailHelper();

            // Get SMTP settings from POST data
            $smtpSettings = [
                'host' => $_POST['smtp_host'] ?? '',
                'port' => $_POST['smtp_port'] ?? '',
                'username' => $_POST['smtp_username'] ?? '',
                'password' => $_POST['smtp_password'] ?? '',
                'from_email' => $_POST['smtp_from_email'] ?? '',
                'from_name' => $_POST['smtp_from_name'] ?? ''
            ];

            // Test SMTP connection
            $result = $emailHelper->testSmtpConnection($smtpSettings);

            echo json_encode($result);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }

        exit;
    }

    /**
     * Load available models from OpenRouter
     */
    public function openRouterModels() {
        $this->checkAuth();

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

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            exit;
        }

        try {
            $apiKey = $_POST['api_key'] ?? '';
            
            if (empty($apiKey)) {
                echo json_encode(['success' => false, 'message' => 'API key is required']);
                exit;
            }

            // Temporarily set the API key for this request
            $_ENV['OPENROUTER_API_KEY'] = $apiKey;
            $openRouterHelper = new OpenRouterHelper();
            
            $models = $openRouterHelper->getModels();
            
            if (empty($models)) {
                echo json_encode(['success' => false, 'message' => 'No models found or invalid API key']);
                exit;
            }

            echo json_encode(['success' => true, 'models' => $models]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }

        exit;
    }

    /**
     * Generate game description using OpenRouter AI
     */
    public function generateGameDescription() {
        $this->checkAuth();

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

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'Invalid request method']);
            exit;
        }

        try {
            $gameTitle = $_POST['game_title'] ?? '';
            $categoryId = $_POST['category_id'] ?? null;
            $gameId = $_POST['game_id'] ?? null;
            
            if (empty($gameTitle)) {
                echo json_encode(['success' => false, 'message' => 'Game title is required']);
                exit;
            }

            // Get category name if provided
            $categoryName = null;
            if (!empty($categoryId)) {
                $category = $this->category->getCategoryById($categoryId);
                $categoryName = $category['name'] ?? null;
            }

            // Get existing description if game ID is provided
            $existingDescription = null;
            if (!empty($gameId)) {
                $game = $this->game->getGameById($gameId);
                $existingDescription = $game['description'] ?? null;
            }

            $description = $this->openRouterHelper->generateGameDescription($gameTitle, $categoryName, $existingDescription);
            
            echo json_encode(['success' => true, 'description' => $description]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }

        exit;
    }
}