<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <?php
    // Load site settings
    require_once __DIR__ . '/../../models/SiteSettings.php';
    $siteSettings = new SiteSettings();

    // If settings are not passed from controller, load them here
    if (!isset($settings)) {
        $settings = $siteSettings->getAllSettings();
    }

    // Load menu system
    require_once __DIR__ . '/../../models/Menu.php';
    $menuModel = new Menu();

    // Set variables for commonly used settings
    $siteTitle = $settings['site_title'] ?? 'Moowin Casino';
    $siteDescription = $settings['site_description'] ?? 'Play the best free online games on our gaming portal. New games added daily!';
    $faviconPath = $settings['favicon_path'] ?? '/public/images/favicon.ico';
    $logoPath = $settings['logo_path'] ?? '/public/images/logo.png';
    $heroTitle = $settings['hero_title'] ?? 'Welcome to Our Gaming Portal';
    $heroDescription = $settings['hero_description'] ?? 'Discover the best free online games and enjoy hours of entertainment.';
    $heroImagePath = $settings['hero_image_path'] ?? '/public/images/hero-default.jpg';
    $footerDescription = $settings['footer_description'] ?? 'The best place to play free online games. New games added daily!';

    // Load popular categories if not already defined
    if (!isset($popularCategories) || !is_array($popularCategories)) {
        require_once __DIR__ . '/../../models/Category.php';
        $categoryModel = new Category();
        $popularCategories = $categoryModel->getPopularCategories(5);
    }

    // Determine page type and set title accordingly
    $pageType = 'homepage'; // Default
    $titleReplacements = ['site_title' => $siteTitle];

    // Get current URL path
    $currentPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    if ($currentPath === '/') {
        // Homepage
        $titleTemplate = $settings['seo_title_homepage'] ?? '{{site_title}} - Play Free Online Games';
    } elseif (isset($pageType) && $pageType === 'page' && isset($pageTitle)) {
        // Custom page
        $titleTemplate = $settings['seo_title_page'] ?? '{{page_title}} - {{site_title}}';
        $titleReplacements['page_title'] = $pageTitle;
    } elseif (strpos($currentPath, '/category/') === 0 && isset($categoryName)) {
        // Category page
        $titleTemplate = $settings['seo_title_category'] ?? '{{category_name}} Games - {{site_title}}';
        $titleReplacements['category_name'] = $categoryName;
    } elseif ($currentPath === '/blog') {
        // Blog index page
        $titleTemplate = $settings['seo_title_blog'] ?? 'Blog - {{site_title}}';
    } elseif (strpos($currentPath, '/blog/') === 0 && isset($postTitle)) {
        // Blog post page
        $titleTemplate = $settings['seo_title_blog_post'] ?? '{{post_title}} - Blog - {{site_title}}';
        $titleReplacements['post_title'] = $postTitle;
    } elseif (strpos($currentPath, '/game/') === 0 && isset($gameTitle)) {
        // Game page
        $titleTemplate = $settings['seo_title_game'] ?? 'Play {{game_title}} - {{site_title}}';
        $titleReplacements['game_title'] = $gameTitle;
    } else {
        // Other pages - use page template if pageTitle is set
        if (isset($pageTitle)) {
            $titleTemplate = $settings['seo_title_page'] ?? '{{page_title}} - {{site_title}}';
            $titleReplacements['page_title'] = $pageTitle;
        } else {
            // Fallback to homepage template
            $titleTemplate = $settings['seo_title_homepage'] ?? '{{site_title}} - Play Free Online Games';
        }
    }

    // Process the title template
    $finalTitle = $siteSettings->processTitleTemplate($titleTemplate, $titleReplacements);
    ?>
    <title><?= htmlspecialchars($finalTitle) ?></title>
    <meta name="description" content="<?= isset($pageDescription) ? htmlspecialchars($pageDescription) : htmlspecialchars($siteDescription) ?>">

    <?php if ($faviconPath): ?>
    <link rel="icon" href="<?= htmlspecialchars($faviconPath) ?>" type="image/x-icon">
    <?php endif; ?>

    <!-- Locally built Tailwind CSS -->
    <link rel="stylesheet" href="/public/css/styles.css">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700&display=swap" rel="stylesheet">

    <!-- Dropdown Menu CSS -->
    <link rel="stylesheet" href="/public/css/dropdown.css">

    <!-- Favorite Badge CSS -->
    <link rel="stylesheet" href="/public/css/favorite-badge.css">

    <!-- Mobile Navigation CSS -->
    <link rel="stylesheet" href="/public/css/mobile-nav.css">

    <!-- Custom CSS -->
    <?php if (isset($customCss) && is_array($customCss)): ?>
        <?php foreach ($customCss as $cssFile): ?>
            <link rel="stylesheet" href="<?= htmlspecialchars($cssFile) ?>">
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- View Transitions API Support -->
    <style>
        @view-transition {
            navigation: auto;
        }

        /* Custom animations for view transitions */
        ::view-transition-group(root) {
            animation-duration: 0.5s;
        }

        ::view-transition-old(root) {
            animation: 0.5s cubic-bezier(0.4, 0, 0.2, 1) both fade-out;
        }

        ::view-transition-new(root) {
            animation: 0.5s cubic-bezier(0.4, 0, 0.2, 1) both fade-in;
        }

        @keyframes fade-in {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes fade-out {
            from { opacity: 1; }
            to { opacity: 0; }
        }
    </style>

    <!-- Custom Head Code -->
    <?php if (isset($settings['head_code']) && !empty($settings['head_code'])): ?>
        <?= $settings['head_code'] ?>
    <?php endif; ?>
</head>
<body class="bg-darker text-white min-h-screen flex flex-col">
    <!-- Body Start Code -->
    <?php if (isset($settings['body_start_code']) && !empty($settings['body_start_code'])): ?>
        <?= $settings['body_start_code'] ?>
    <?php endif; ?>

    <!-- Header Ad -->
    <?php if (isset($settings['enable_ads']) && $settings['enable_ads'] == '1' && isset($settings['header_ad']) && !empty($settings['header_ad'])): ?>
    <div class="ad-container header-ad">
        <?= $settings['header_ad'] ?>
    </div>
    <?php endif; ?>

    <main class="flex-grow">
    <div class="flex min-h-screen">
        <!-- Sidebar -->
        <aside class="hidden lg:block w-64 bg-sidebar-bg border-r border-gray-800 fixed h-full">
            <div class="p-4">
                <a href="/" class="flex items-center justify-center mb-8">
                    <img src="<?= htmlspecialchars($logoPath) ?>" alt="<?= htmlspecialchars($siteTitle) ?>" class="h-12" onerror="this.src='https://placehold.co/200x80/0F172A/2C7BE5?text=<?= urlencode($siteTitle) ?>&font=Manrope'">
                </a>

                <nav class="space-y-1">
                    <?php
                    // Display header menu if available
                    $headerMenu = $menuModel->getMenuByLocation('header');
                    if ($headerMenu) {
                        $headerMenuItems = $menuModel->getMenuItems($headerMenu['id']);
                        if (!empty($headerMenuItems)) {
                            foreach ($headerMenuItems as $item) {
                                $isActive = $_SERVER['REQUEST_URI'] === $item['url'] || strpos($_SERVER['REQUEST_URI'], $item['url']) === 0;
                                echo '<a href="' . htmlspecialchars($item['url']) . '" class="sidebar-link ' . ($isActive ? 'active' : '') . '"';
                                if ($item['target'] === '_blank') {
                                    echo ' target="_blank"';
                                }
                                echo '>';
                                if (!empty($item['icon'])) {
                                    echo '<i class="' . htmlspecialchars($item['icon']) . ' text-xl"></i>';
                                } else {
                                    echo '<i class="fas fa-link text-xl"></i>';
                                }
                                echo '<span>' . htmlspecialchars($item['title']) . '</span>';
                                echo '</a>';
                            }
                        }
                    } else {
                        // Show default menu items only if no custom menu is set
                        ?>
                        <a href="/" class="sidebar-link <?= $_SERVER['REQUEST_URI'] === '/' ? 'active' : '' ?>">
                            <i class="fas fa-home text-xl"></i>
                            <span>Home Page</span>
                        </a>
                        <a href="/categories" class="sidebar-link <?= strpos($_SERVER['REQUEST_URI'], '/category') === 0 ? 'active' : '' ?>">
                            <i class="fas fa-th-large text-xl"></i>
                            <span>Categories</span>
                        </a>
                        <a href="/blog" class="sidebar-link <?= strpos($_SERVER['REQUEST_URI'], '/blog') === 0 ? 'active' : '' ?>">
                            <i class="fas fa-newspaper text-xl"></i>
                            <span>Blog</span>
                        </a>
                    <?php } ?>
                </nav>

                <div class="mt-8 pt-6 border-t border-gray-800">
                    <?php if (isset($_SESSION['user_id'])): ?>
                    <h3 class="text-gray-400 uppercase text-xs font-semibold mb-3 px-4">My Account</h3>
                    <nav class="space-y-1">
                        <a href="/profile" class="sidebar-link">
                            <i class="fas fa-user text-xl"></i>
                            <span>My Profile</span>
                        </a>
                        <?php if (($settings['enable_points_system'] ?? '0') == '1'): ?>
                        <a href="/coins" class="sidebar-link">
                            <i class="fas fa-coins text-xl"></i>
                            <span>My Coins</span>
                        </a>
                        <?php endif; ?>
                        <a href="/logout" class="sidebar-link">
                            <i class="fas fa-sign-out-alt text-xl"></i>
                            <span>Logout</span>
                        </a>
                    </nav>
                    <?php else: ?>
                    <h3 class="text-gray-400 uppercase text-xs font-semibold mb-3 px-4">Account</h3>
                    <nav class="space-y-1">
                        <a href="/login" class="sidebar-link">
                            <i class="fas fa-sign-in-alt text-xl"></i>
                            <span>Login</span>
                        </a>
                        <a href="/register" class="sidebar-link">
                            <i class="fas fa-user-plus text-xl"></i>
                            <span>Register</span>
                        </a>
                    </nav>
                    <?php endif; ?>
                </div>

                <div class="mt-8 pt-6 border-t border-gray-800">
                    <h3 class="text-gray-400 uppercase text-xs font-semibold mb-3 px-4">Popular Categories</h3>
                    <nav class="space-y-1">
                        <?php
                        // Check if $popularCategories is defined
                        if (isset($popularCategories) && is_array($popularCategories)):
                            foreach (array_slice($popularCategories, 0, 5) as $category):
                        ?>
                        <a href="/category/<?= $category['slug'] ?>" class="sidebar-link">
                            <i class="fas fa-gamepad text-xl"></i>
                            <span><?= htmlspecialchars($category['name']) ?></span>
                        </a>
                        <?php
                            endforeach;
                        else:
                        ?>
                        <div class="px-4 text-gray-500">No popular games available</div>
                        <?php endif; ?>
                    </nav>
                </div>
            </div>
        </aside>

        <!-- Main Content -->
        <div class="lg:ml-64 flex-1">
            <!-- Top Navigation -->
            <header class="bg-dark border-b border-gray-800 sticky top-0 z-50">
                <div class="container mx-auto px-4 py-3">
                    <!-- Top Row: Logo and User Actions -->
                    <div class="flex justify-between items-center">
                        <!-- Mobile Logo -->
                        <a href="/" class="lg:hidden text-2xl font-bold text-white flex items-center">
                            <img src="<?= htmlspecialchars($logoPath) ?>" alt="<?= htmlspecialchars($siteTitle) ?>" class="h-10" onerror="this.src='https://placehold.co/40x40/0F172A/2C7BE5?text=<?= urlencode(substr($siteTitle, 0, 2)) ?>&font=Manrope'">
                        </a>

                        <!-- Desktop Search Bar -->
                        <div class="hidden md:block flex-1 max-w-xl mx-4">
                            <form action="/search" method="GET" class="search-bar">
                                <input type="text" name="q" placeholder="Search games..."
                                       value="<?= isset($_GET['q']) ? htmlspecialchars($_GET['q']) : '' ?>">
                                <button type="submit">
                                    <i class="fas fa-search"></i>
                                </button>
                            </form>
                        </div>

                        <!-- User Actions -->
                        <div class="flex items-center gap-4">
                            <?php if (isset($_SESSION['user_id'])): ?>
                            <!-- Coins Display -->
                            <?php if (($settings['enable_points_system'] ?? '0') == '1'): ?>
                            <?php
                            // Load user's current coin balance
                            require_once __DIR__ . '/../../models/Coins.php';
                            $coinsModel = new Coins();
                            $userBalance = $coinsModel->getUserBalance($_SESSION['user_id']);
                            $currentBalance = $userBalance['balance'] ?? 0;
                            ?>
                            <div class="flex items-center text-yellow-400 mr-2">
                                <i class="fas fa-coins mr-1"></i>
                                <span class="coin-balance text-sm md:text-base"><?= number_format($currentBalance) ?></span>
                            </div>
                            <?php endif; ?>
                            
                            <!-- User Dropdown -->
                            <div class="relative" id="userDropdown">
                                <button class="nav-link flex items-center">
                                    <span class="hidden md:inline-block mr-2"><?= htmlspecialchars($_SESSION['username']) ?></span>
                                    <i class="fas fa-user-circle text-xl"></i>
                                </button>
                                <div class="dropdown-menu hidden absolute right-0">
                                    <a href="/profile" class="dropdown-item">
                                        <i class="fas fa-user"></i> My Profile
                                    </a>
                                    <?php if (($settings['enable_points_system'] ?? '0') == '1'): ?>
                                    <a href="/coins" class="dropdown-item">
                                        <i class="fas fa-coins"></i> My Coins
                                    </a>
                                    <?php endif; ?>
                                    <a href="/logout" class="dropdown-item border-t border-gray-800">
                                        <i class="fas fa-sign-out-alt"></i> Logout
                                    </a>
                                </div>
                            </div>
                            <?php else: ?>
                            <!-- Login/Register -->
                            <div class="hidden md:flex items-center gap-2">
                                <a href="/login" class="nav-link">
                                    <i class="fas fa-sign-in-alt mr-1"></i> Login
                                </a>
                                <a href="/register" class="btn-primary py-1 px-3 text-sm">
                                    Register
                                </a>
                            </div>
                            <a href="/login" class="md:hidden nav-link">
                                <i class="fas fa-sign-in-alt"></i>
                            </a>
                            <?php endif; ?>

                            <!-- Mobile Menu Button -->
                            <button id="mobileMenuBtn" class="lg:hidden nav-link">
                                <i class="fas fa-bars"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Mobile Search (Always visible on mobile) -->
                    <div class="mt-3 md:hidden">
                        <form action="/search" method="GET" class="search-bar">
                            <input type="text" name="q" placeholder="Search games..."
                                   value="<?= isset($_GET['q']) ? htmlspecialchars($_GET['q']) : '' ?>">
                            <button type="submit">
                                <i class="fas fa-search"></i>
                            </button>
                        </form>
                    </div>

                </div>
            </header>

            <!-- Mobile Sidebar (Hidden by default) -->
            <div id="mobileSidebar" class="lg:hidden fixed inset-0 bg-darker bg-opacity-90 z-50 hidden">
                <div class="bg-sidebar-bg h-full w-64 shadow-lg overflow-y-auto">
                    <div class="p-4">
                        <div class="flex items-center justify-between mb-6">
                            <a href="/" class="text-2xl font-bold text-white">
                                <img src="<?= htmlspecialchars($logoPath) ?>" alt="<?= htmlspecialchars($siteTitle) ?>" class="h-10" onerror="this.src='https://placehold.co/200x80/0F172A/2C7BE5?text=<?= urlencode($siteTitle) ?>&font=Manrope'">
                            </a>
                            <button id="closeMobileMenu" class="text-gray-400 hover:text-white">
                                <i class="fas fa-times text-xl"></i>
                            </button>
                        </div>

                        <nav class="space-y-1">
                            <?php
                            // Display header menu if available
                            if ($headerMenu && !empty($headerMenuItems)) {
                                foreach ($headerMenuItems as $item) {
                                    $isActive = $_SERVER['REQUEST_URI'] === $item['url'] || strpos($_SERVER['REQUEST_URI'], $item['url']) === 0;
                                    echo '<a href="' . htmlspecialchars($item['url']) . '" class="sidebar-link ' . ($isActive ? 'active' : '') . '"';
                                    if ($item['target'] === '_blank') {
                                        echo ' target="_blank"';
                                    }
                                    echo '>';
                                    if (!empty($item['icon'])) {
                                        echo '<i class="' . htmlspecialchars($item['icon']) . ' text-xl"></i>';
                                    } else {
                                        echo '<i class="fas fa-link text-xl"></i>';
                                    }
                                    echo '<span>' . htmlspecialchars($item['title']) . '</span>';
                                    echo '</a>';
                                }
                            } else {
                                // Show default menu items only if no custom menu is set
                                ?>
                                <a href="/" class="sidebar-link <?= $_SERVER['REQUEST_URI'] === '/' ? 'active' : '' ?>">
                                    <i class="fas fa-home text-xl"></i>
                                    <span>Home Page</span>
                                </a>
                                <a href="/categories" class="sidebar-link <?= strpos($_SERVER['REQUEST_URI'], '/category') === 0 ? 'active' : '' ?>">
                                    <i class="fas fa-th-large text-xl"></i>
                                    <span>Categories</span>
                                </a>
                                <a href="/blog" class="sidebar-link <?= strpos($_SERVER['REQUEST_URI'], '/blog') === 0 ? 'active' : '' ?>">
                                    <i class="fas fa-newspaper text-xl"></i>
                                    <span>Blog</span>
                                </a>
                            <?php } ?>
                        </nav>

                        <div class="mt-6 pt-6 border-t border-gray-800">
                            <h3 class="text-gray-400 uppercase text-xs font-semibold mb-3 px-4">Popular Games</h3>
                            <nav class="space-y-1">
                                <?php
                                // Check if $popularCategories is defined
                                if (isset($popularCategories) && is_array($popularCategories)):
                                    foreach (array_slice($popularCategories, 0, 5) as $category):
                                ?>
                                <a href="/category/<?= $category['slug'] ?>" class="sidebar-link">
                                    <i class="fas fa-gamepad text-xl"></i>
                                    <span><?= htmlspecialchars($category['name']) ?></span>
                                </a>
                                <?php
                                    endforeach;
                                else:
                                ?>
                                <div class="px-4 text-gray-500">No popular games available</div>
                                <?php endif; ?>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>

            <main class="flex-1">
                <!-- Mobile Bottom Navigation Bar -->
                <nav class="mobile-bottom-nav">
                    <?php
                    // Determine active page
                    $currentPath = $_SERVER['REQUEST_URI'];
                    $isHome = $currentPath === '/';
                    $isCategories = strpos($currentPath, '/category') === 0 || $currentPath === '/categories';
                    $isProfile = isset($_SESSION['user_id']) && (strpos($currentPath, '/profile') === 0);
                    $isMenu = false; // Will be toggled by JS when menu is open
                    ?>

                    <a href="/" class="mobile-nav-item <?= $isHome ? 'active' : '' ?>">
                        <i class="fas fa-home"></i>
                        <span>Home</span>
                    </a>

                    <a href="/categories" class="mobile-nav-item <?= $isCategories ? 'active' : '' ?>">
                        <i class="fas fa-th-large"></i>
                        <span>Categories</span>
                    </a>

                    <?php if (isset($_SESSION['user_id'])): ?>
                    <?php if (($settings['enable_points_system'] ?? '0') == '1'): ?>
                    <a href="/coins" class="mobile-nav-item <?= strpos($currentPath, '/coins') === 0 ? 'active' : '' ?>">
                        <i class="fas fa-coins"></i>
                        <span>Coins</span>
                    </a>
                    <?php else: ?>
                    <a href="/profile" class="mobile-nav-item <?= $isProfile ? 'active' : '' ?>">
                        <i class="fas fa-user"></i>
                        <span>Profile</span>
                    </a>
                    <?php endif; ?>
                    <?php else: ?>
                    <a href="/login" class="mobile-nav-item">
                        <i class="fas fa-sign-in-alt"></i>
                        <span>Login</span>
                    </a>
                    <?php endif; ?>

                    <button id="mobileNavMenuBtn" class="mobile-nav-item <?= $isMenu ? 'active' : '' ?>">
                        <i class="fas fa-bars"></i>
                        <span>Menu</span>
                    </button>
                </nav>

    <!-- JavaScript includes -->
    <script>
        // Prevent multiple declarations
        if (typeof window.headerScriptsLoaded === 'undefined') {
            window.headerScriptsLoaded = true;
            
            // Mobile sidebar functionality
            const mobileSidebar = document.getElementById('mobileSidebar');
            const closeMobileMenu = document.getElementById('closeMobileMenu');
            const mobileNavMenuBtn = document.getElementById('mobileNavMenuBtn');
            const mobileMenuBtn = document.getElementById('mobileMenuBtn');

            // Function to toggle mobile sidebar
            function toggleMobileSidebar() {
                if (mobileSidebar) {
                    mobileSidebar.classList.toggle('hidden');
                    document.body.classList.toggle('overflow-hidden');

                    // Toggle active class on the bottom nav menu button
                    if (mobileNavMenuBtn) {
                        mobileNavMenuBtn.classList.toggle('active');
                    }
                }
            }

            // Bottom nav menu button
            if (mobileNavMenuBtn) {
                mobileNavMenuBtn.addEventListener('click', toggleMobileSidebar);
            }

            // Top mobile menu button
            if (mobileMenuBtn) {
                mobileMenuBtn.addEventListener('click', toggleMobileSidebar);
            }

            // Close button
            if (closeMobileMenu) {
                closeMobileMenu.addEventListener('click', () => {
                    if (mobileSidebar) {
                        mobileSidebar.classList.add('hidden');
                        document.body.classList.remove('overflow-hidden');

                        // Remove active class from bottom nav menu button
                        if (mobileNavMenuBtn) {
                            mobileNavMenuBtn.classList.remove('active');
                        }
                    }
                });
            }

            // User dropdown functionality
            const userDropdown = document.getElementById('userDropdown');
            if (userDropdown) {
                const dropdownButton = userDropdown.querySelector('button');
                const dropdownMenu = userDropdown.querySelector('.dropdown-menu');
                
                if (dropdownButton && dropdownMenu) {
                    dropdownButton.addEventListener('click', function(e) {
                        e.stopPropagation();
                        dropdownMenu.classList.toggle('hidden');
                    });

                    // Close dropdown when clicking outside
                    document.addEventListener('click', function() {
                        dropdownMenu.classList.add('hidden');
                    });
                }
            }
        }
    </script>

    <!-- Load coins system if user is logged in and points system is enabled -->
    <?php if (isset($_SESSION['user_id']) && ($settings['enable_points_system'] ?? '0') == '1'): ?>
        <script src="/public/js/coins.js"></script>
    <?php endif; ?>

    <!-- Custom JS -->
    <?php if (isset($customJs) && is_array($customJs)): ?>
        <?php foreach ($customJs as $jsFile): ?>
            <script src="<?= $jsFile ?>"></script>
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- View Transitions API Support -->
    <script src="/public/js/view-transitions.js"></script>

    <!-- Body End Code -->
    <?php if (isset($settings['body_end_code']) && !empty($settings['body_end_code'])): ?>
        <?= $settings['body_end_code'] ?>
    <?php endif; ?>
