<?php
// Load website settings and site manager with proper error handling
if (!isset($websiteSettings)) {
    require_once __DIR__ . '/database.php';
    $db = new Database();
    $websiteSettings = $db->getWebsiteSettings();
}

// Initialize multi-site system if not already loaded
if (!class_exists('SiteManager')) {
    require_once __DIR__ . '/site-manager.php';
    $siteManager = SiteManager::getInstance($db ?? new Database());
} else {
    // Use existing instance if already initialized
    $siteManager = SiteManager::getInstance();
}

// Get current site with error handling
try {
    $currentSite = getCurrentSite();
} catch (Exception $e) {
    $currentSite = [
        'site_name' => 'Default Site',
        'logo_path' => 'assets/logos/default_logo.png'
    ];
}

// Get meta tags with error handling
try {
    $siteMeta = $siteManager->getMetaTags();
} catch (Exception $e) {
    $siteMeta = [
        'title' => 'Live Draw Togel - Prediksi Terpercaya',
        'description' => 'Situs prediksi togel terpercaya dengan data result terlengkap',
        'keywords' => 'togel, live draw, prediksi'
    ];
}

// Check maintenance mode if function exists
if (function_exists('isMaintenanceMode') && isMaintenanceMode()) {
    include __DIR__ . '/../maintenance.php';
    exit;
}

// Set default current URL if not set
$currentUrl = $currentUrl ?? 'http://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . ($_SERVER['REQUEST_URI'] ?? '/');
?>
<!DOCTYPE html>
<html lang="id">
<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="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    
    <!-- SEO Meta Tags - Enhanced with Database Fields -->
    <meta name="description" content="<?php echo htmlspecialchars($websiteSettings['meta_description'] ?? ($siteMeta['description'] ?? 'Situs prediksi togel terpercaya dengan data result terlengkap')); ?>">
    <meta name="keywords" content="<?php echo htmlspecialchars($websiteSettings['meta_keywords'] ?? ($siteMeta['keywords'] ?? 'togel, live draw, prediksi')); ?>">
    <meta name="author" content="<?php echo htmlspecialchars($websiteSettings['meta_author'] ?? ($currentSite['site_name'] ?? 'Live Draw Togel')); ?>">
    <meta name="robots" content="<?php echo htmlspecialchars($websiteSettings['meta_robots'] ?? 'index, follow'); ?>">
    <?php if (!empty($websiteSettings['canonical_url'])): ?>
    <link rel="canonical" href="<?php echo htmlspecialchars($websiteSettings['canonical_url']); ?>">
    <?php endif; ?>
    
    <!-- Theme and Browser Colors -->
    <meta name="theme-color" content="<?php echo htmlspecialchars($websiteSettings['theme_color'] ?? '#1976d2'); ?>">
    <meta name="msapplication-TileColor" content="<?php echo htmlspecialchars($websiteSettings['theme_color'] ?? '#1976d2'); ?>">
    
    <!-- Open Graph Meta Tags -->
    <?php 
    $og_title = isset($websiteSettings['og_title']) && !empty($websiteSettings['og_title']) ? $websiteSettings['og_title'] : (isset($pageTitle) ? $pageTitle : 'Live Draw Togel - Prediksi Terpercaya');
    $og_description = isset($websiteSettings['og_description']) && !empty($websiteSettings['og_description']) ? $websiteSettings['og_description'] : 'Situs prediksi togel terpercaya dengan data result terlengkap';
    $og_url = isset($websiteSettings['og_url']) && !empty($websiteSettings['og_url']) ? $websiteSettings['og_url'] : $currentUrl;
    $og_image = isset($websiteSettings['og_image']) && !empty($websiteSettings['og_image']) ? $websiteSettings['og_image'] : 'assets/logos/default_logo.png';
    $og_site_name = isset($websiteSettings['site_name']) && !empty($websiteSettings['site_name']) ? $websiteSettings['site_name'] : 'Live Draw Togel';
    ?>
    <meta property="og:title" content="<?php echo htmlspecialchars($og_title); ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($og_description); ?>">
    <meta property="og:type" content="website">
    <meta property="og:url" content="<?php echo htmlspecialchars($og_url); ?>">
    <meta property="og:image" content="<?php echo htmlspecialchars($og_image); ?>">
    <meta property="og:site_name" content="<?php echo htmlspecialchars($og_site_name); ?>">
    
    <!-- Twitter Card Meta Tags -->
    <?php 
    $twitter_title = isset($websiteSettings['twitter_title']) && !empty($websiteSettings['twitter_title']) ? $websiteSettings['twitter_title'] : (isset($pageTitle) ? $pageTitle : 'Live Draw Togel - Prediksi Terpercaya');
    $twitter_description = isset($websiteSettings['twitter_description']) && !empty($websiteSettings['twitter_description']) ? $websiteSettings['twitter_description'] : 'Situs prediksi togel terpercaya dengan data result terlengkap';
    $twitter_image = isset($websiteSettings['twitter_image']) && !empty($websiteSettings['twitter_image']) ? $websiteSettings['twitter_image'] : 'assets/logos/default_logo.png';
    ?>
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?php echo htmlspecialchars($twitter_title); ?>">
    <meta name="twitter:description" content="<?php echo htmlspecialchars($twitter_description); ?>">
    <meta name="twitter:image" content="<?php echo htmlspecialchars($twitter_image); ?>">
    
    <?php 
    // Dynamic title generation with template support
    $finalTitle = $pageTitle ?? ($siteMeta['title'] ?? 'Live Draw Togel - Prediksi Terpercaya');
    if (!empty($websiteSettings['site_title_template']) && isset($pageTitle)) {
        $finalTitle = str_replace(
            ['{page_title}', '{site_name}'],
            [$pageTitle, $websiteSettings['site_name'] ?? ''],
            $websiteSettings['site_title_template']
        );
    } elseif (!isset($pageTitle) && !empty($websiteSettings['home_title'])) {
        $finalTitle = $websiteSettings['home_title'];
    }
    ?>
    <title><?php echo htmlspecialchars($finalTitle); ?></title>
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($websiteSettings['favicon_path'] ?? $siteMeta['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($websiteSettings['favicon_path'] ?? 'assets/images/apple-touch-icon.png'); ?>">
    
    <!-- Structured Data JSON-LD -->
    <?php if (!empty($websiteSettings['structured_data_json'])): ?>
    <script type="application/ld+json">
    <?php echo $websiteSettings['structured_data_json']; ?>
    </script>
    <?php else: ?>
    <!-- Default Organization Structured Data -->
    <script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "Organization",
        "name": "<?php echo htmlspecialchars($websiteSettings['site_name'] ?? 'Live Draw Togel'); ?>",
        "description": "<?php echo htmlspecialchars($websiteSettings['meta_description'] ?? 'Situs togel live draw terpercaya'); ?>",
        "url": "<?php echo htmlspecialchars($websiteSettings['og_url'] ?? (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . ($_SERVER['HTTP_HOST'] ?? '') . ($_SERVER['REQUEST_URI'] ?? '')); ?>",
        <?php if (!empty($websiteSettings['site_logo'])): ?>
        "logo": "<?php echo htmlspecialchars($websiteSettings['og_image'] ?: $websiteSettings['site_logo']); ?>",
        <?php endif; ?>
        "sameAs": [
            <?php 
            $socialLinks = [];
            $fb = $websiteSettings['facebook_link'] ?? $websiteSettings['facebook_url'] ?? '';
            $tw = $websiteSettings['twitter_link'] ?? $websiteSettings['twitter_url'] ?? '';
            $ig = $websiteSettings['instagram_link'] ?? $websiteSettings['instagram_url'] ?? '';
            if (!empty($fb)) $socialLinks[] = '"' . htmlspecialchars($fb) . '"';
            if (!empty($tw)) $socialLinks[] = '"' . htmlspecialchars($tw) . '"';
            if (!empty($ig)) $socialLinks[] = '"' . htmlspecialchars($ig) . '"';
            if (!empty($websiteSettings['telegram_link'])) $socialLinks[] = '"' . htmlspecialchars($websiteSettings['telegram_link']) . '"';
            echo implode(',', $socialLinks);
            ?>
        ]
    }
    </script>
    <?php endif; ?>
    
    <!-- External CSS Libraries -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- prediksi: stable asset version helper to improve cache lifetimes -->
    <?php
    if (!function_exists('pm_asset_version')) {
        function pm_asset_version($path) {
            $full = __DIR__ . '/../' . ltrim($path, '/');
            if (is_file($full)) {
                return filemtime($full);
            }
            return '1';
        }
    }

    // Alpine.js
    ?>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

    <!-- Preload critical CSS (preload+onload pattern) -->
    <link rel="preload" href="assets/css/tailwind-replacement.css?v=<?php echo pm_asset_version('assets/css/tailwind-replacement.css'); ?>" as="style" onload="this.rel='stylesheet'">
    <noscript><link href="assets/css/tailwind-replacement.css?v=<?php echo pm_asset_version('assets/css/tailwind-replacement.css'); ?>" rel="stylesheet"></noscript>

    <link rel="preload" href="assets/css/inatips-style.css?v=<?php echo pm_asset_version('assets/css/inatips-style.css'); ?>" as="style" onload="this.rel='stylesheet'">
    <noscript><link href="assets/css/inatips-style.css?v=<?php echo pm_asset_version('assets/css/inatips-style.css'); ?>" rel="stylesheet"></noscript>

    <link rel="preload" href="assets/css/prediksi-inatips.css?v=<?php echo pm_asset_version('assets/css/prediksi-inatips.css'); ?>" as="style" onload="this.rel='stylesheet'">
    <noscript><link href="assets/css/prediksi-inatips.css?v=<?php echo pm_asset_version('assets/css/prediksi-inatips.css'); ?>" rel="stylesheet"></noscript>
    
    <!-- Dynamic Site Theme CSS - FRONTEND ONLY -->
    <?php if (!isset($_SERVER['REQUEST_URI']) || strpos($_SERVER['REQUEST_URI'], '/admin/') === false): ?>
    <style>
    <?php echo generateThemeCSS(); ?>
    </style>
    <?php endif; ?>
    
    <!-- Banner Grid Fix CSS -->
    <style>
        /* FORCE BANNER DISPLAY - MAX PRIORITY */
        .banner-section,
        div.banner-section,
        .banner-section[class*="banner"] {
            background: #000000 !important;
            padding: 10px 0 !important;
            display: block !important;
            visibility: visible !important;
        }
        
        .banner-container,
        div.banner-container,
        .banner-container[class*="banner"] {
            max-width: 1200px !important;
            margin: 0 auto !important;
            padding: 0 15px !important;
            display: block !important;
            visibility: visible !important;
        }
        
        .banner-grid,
        div.banner-grid,
        .banner-grid[class*="banner"] {
            display: grid !important;
            grid-template-columns: repeat(3, 1fr) !important;
            gap: 10px !important;
            visibility: visible !important;
        }
        
        .banner-item,
        div.banner-item,
        .banner-item[class*="banner"] {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: relative !important;
            z-index: auto !important;
            border-radius: 6px !important;
            overflow: hidden !important;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
            transition: transform 0.3s ease !important;
            border: 1px solid rgba(255,255,255,0.05) !important;
            left: auto !important;
            right: auto !important;
            top: auto !important;
            bottom: auto !important;
            transform: none !important;
        }
        
        .banner-item:hover {
            transform: translateY(-2px) !important;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2) !important;
        }
        
        .banner-item img,
        .banner-item img[src*="banner"],
        .banner-item img[src*="slide"] {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            width: 100% !important;
            height: auto !important;
            min-height: 120px !important;
            max-height: none !important;
            object-fit: contain !important;
            object-position: center !important;
            background: #1a1a2e !important;
            transition: transform 0.3s ease !important;
            position: relative !important;
            z-index: auto !important;
            left: auto !important;
            right: auto !important;
            top: auto !important;
            bottom: auto !important;
        }
        
        .banner-item:hover img {
            transform: scale(1.02) !important;
        }
        
        .banner-item a,
        .banner-item a[href] {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            width: 100% !important;
            height: 100% !important;
        }
        
        /* Override any possible CSS that hides banners */
        [class*="banner-slide"],
        [class*="slider"],
        [class*="carousel"] .banner-item {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            position: relative !important;
        }
        
        /* MOBILE - HANYA TAMPIL 1 BANNER FULL WIDTH - OVERRIDE DESKTOP */
        @media screen and (max-width: 768px) {
            .banner-section {
                padding: 0 !important;
                margin: 0 !important;
                width: 100vw !important;
                position: relative !important;
                left: 50% !important;
                right: 50% !important;
                margin-left: -50vw !important;
                margin-right: -50vw !important;
            }
            
            .banner-container,
            div.banner-container,
            .banner-container[class*="banner"] {
                padding: 0 !important;
                margin: 0 !important;
                max-width: none !important;
                width: 100% !important;
            }
            
            .banner-grid,
            div.banner-grid,
            .banner-grid[class*="banner"] {
                display: block !important;
                position: relative !important;
                width: 100% !important;
                height: auto !important;
                min-height: 260px !important;
                overflow: hidden !important;
                grid-template-columns: none !important;
                gap: 0 !important;
                border-radius: 0 !important;
            }
            
            /* FORCE ALL BANNERS HIDDEN FIRST - VERY SPECIFIC SELECTORS */
            .banner-section .banner-container .banner-grid .banner-item,
            .banner-section .banner-container .banner-grid div.banner-item,
            .banner-section div.banner-container .banner-grid .banner-item,
            div.banner-section .banner-container .banner-grid .banner-item {
                display: none !important;
                width: 100% !important;
                height: 100% !important;
                position: absolute !important;
                top: 0 !important;
                left: 0 !important;
                right: 0 !important;
                bottom: 0 !important;
                visibility: hidden !important;
                opacity: 0 !important;
                z-index: 1 !important;
                margin: 0 !important;
                margin-bottom: 0 !important;
            }
            
            /* FORCE ONLY ACTIVE BANNER VISIBLE - VERY SPECIFIC SELECTORS */
            .banner-section .banner-container .banner-grid .banner-item:first-child,
            .banner-section .banner-container .banner-grid .banner-item.active,
            .banner-section .banner-container .banner-grid div.banner-item:first-child,
            .banner-section .banner-container .banner-grid div.banner-item.active,
            .banner-section div.banner-container .banner-grid .banner-item:first-child,
            .banner-section div.banner-container .banner-grid .banner-item.active,
            div.banner-section .banner-container .banner-grid .banner-item:first-child,
            div.banner-section .banner-container .banner-grid .banner-item.active {
                display: block !important;
                visibility: visible !important;
                opacity: 1 !important;
                z-index: 2 !important;
                position: absolute !important;
                top: 0 !important;
                left: 0 !important;
                width: 100% !important;
                height: 100% !important;
                margin: 0 !important;
                margin-bottom: 0 !important;
            }
            
            .banner-item img {
                width: 100% !important;
                height: auto !important;
                max-width: 100% !important;
                object-fit: none !important;
                object-position: center !important;
                display: block !important;
                border-radius: 0 !important;
                background: #1a1a2e !important;
            }
            
            .banner-item a {
                display: block !important;
                width: 100% !important;
                height: 100% !important;
            }
        }
        
        @media (max-width: 480px) {
            .banner-grid {
                height: auto !important;
                min-height: 240px !important;
            }
            
            .banner-item img {
                height: auto !important;
                min-height: 240px !important;
                max-height: none !important;
                object-fit: scale-down !important;
            }
        }
    </style>
    
    <!-- Page Specific CSS -->
    <?php if (isset($additionalCSS)): ?>
        <?php foreach($additionalCSS as $css): ?>
            <link href="<?php echo $css; ?>?v=<?php echo pm_asset_version($css); ?>" rel="stylesheet">
        <?php endforeach; ?>
    <?php endif; ?>
    
    <!-- Inline CSS for Critical Styles -->
    <style>
        /* Critical CSS for above-the-fold content */
        body {
            background: #000000 !important;
            color: #ffffff;
            font-family: 'Inter', 'Arial', sans-serif;
            margin: 0 !important;
            padding: 0 !important;
            overflow-x: hidden !important;
        }
        
        /* DESKTOP CONTAINER - MAX WIDTH 1200PX */
        @media (min-width: 1025px) {
            .container {
                max-width: 1200px !important;
                margin: 0 auto !important;
                padding: 0 15px !important;
                box-sizing: border-box !important;
            }
        }
        
        /* TABLET CONTAINER */
        @media (min-width: 481px) and (max-width: 1024px) {
            .container {
                max-width: 100% !important;
                margin: 0 auto !important;
                padding: 0 10px !important;
                box-sizing: border-box !important;
            }
        }
        
        /* MOBILE CONTAINER */
        @media (max-width: 480px) {
            .container {
                max-width: 100% !important;
                margin: 0 auto !important;
                padding: 0 8px !important;
                box-sizing: border-box !important;
            }
        }
        
        .loading-screen {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: #1a1a2e;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            opacity: 1;
            transition: opacity 0.3s ease;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 3px solid #34495e;
            border-top: 3px solid #ffd700;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
    
    <!-- Preload Critical Resources -->
    <link rel="preload" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" as="style">
    
    <!-- Analytics and Tracking -->
    <?php 
    // Get Google Analytics from website settings
    $googleAnalyticsCode = $websiteSettings['google_analytics'] ?? '';
    
    // Support both custom code and GA ID format
    if (!empty($googleAnalyticsCode)):
        if (strpos($googleAnalyticsCode, '<script') !== false || strpos($googleAnalyticsCode, 'gtag') !== false):
            // Custom analytics code (full script)
            echo $googleAnalyticsCode;
        else:
            // Assume it's a GA ID (like GA-XXXXX or G-XXXXX)
            $googleAnalyticsId = $googleAnalyticsCode;
            ?>
            <!-- Google Analytics -->
            <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo htmlspecialchars($googleAnalyticsId); ?>"></script>
            <script>
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '<?php echo htmlspecialchars($googleAnalyticsId); ?>');
            </script>
            <?php
        endif;
    elseif (isset($googleAnalyticsId) && !empty($googleAnalyticsId)): 
        // Fallback to old variable for backward compatibility
        ?>
        <!-- Google Analytics (Legacy) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo htmlspecialchars($googleAnalyticsId); ?>"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '<?php echo htmlspecialchars($googleAnalyticsId); ?>');
        </script>
        <?php
    endif; 
    ?>
    
    <!-- Global lazy-loading helper + placeholder CSS (native loading + IO fallback) -->
    <style>
        img.lazy-placeholder,
        img[data-src] {
            display: block !important;
            width: 100% !important;
            height: auto !important;
            min-height: 120px;
            filter: blur(10px);
            transition: filter 360ms ease, opacity 300ms ease;
            opacity: 0.95;
        }
        img.lazy-loading { filter: blur(10px); opacity: 0.95; }
        img.lazy-loaded { filter: none !important; opacity: 1 !important; transition: filter 360ms ease, opacity 300ms ease; }
    </style>
    <script>
    (function(){
        function setNativeLazy() {
            if ('loading' in HTMLImageElement.prototype) {
                document.addEventListener('DOMContentLoaded', function(){
                    document.querySelectorAll('img:not([loading])').forEach(function(img){
                        try{
                            if (!img.hasAttribute('data-no-lazy') && !img.closest('.no-lazy')){
                                var src = img.getAttribute('src') || '';
                                if (src && !src.startsWith('data:')) img.setAttribute('loading','lazy');
                            }
                        }catch(e){}
                    });
                });
                return true;
            }
            return false;
        }

        function intersectionFallback(){
            if (!('IntersectionObserver' in window)) return;
            document.addEventListener('DOMContentLoaded', function(){
                var io = new IntersectionObserver(function(entries, observer){
                    entries.forEach(function(entry){
                        if (entry.isIntersecting){
                            var img = entry.target;
                            try{ img.classList.add('lazy-loading'); img.setAttribute('aria-busy','true'); }catch(e){}
                            var dsrc = img.getAttribute('data-src');
                            if (dsrc){ img.onload = function(){ try{ img.classList.remove('lazy-loading'); img.classList.add('lazy-loaded'); img.removeAttribute('aria-busy'); }catch(e){} }; img.src = dsrc; img.removeAttribute('data-src'); }
                            var ds = img.getAttribute('data-srcset'); if (ds){ img.srcset = ds; img.removeAttribute('data-srcset'); }
                            observer.unobserve(img);
                        }
                    });
                }, {rootMargin: '200px 0px', threshold: 0.01});

                document.querySelectorAll('img[data-src], img[data-srcset]').forEach(function(img){ try{ img.classList.add('lazy-placeholder'); }catch(e){}; io.observe(img); });
            });
        }

        try{ if (!setNativeLazy()) intersectionFallback(); else intersectionFallback(); }catch(e){}
    })();
    </script>
</head>
<body>
    <!-- Loading Screen -->
    <div class="loading-screen" id="loadingScreen">
        <div class="loading-spinner"></div>
    </div>