<!DOCTYPE html>
<html lang="en" dir="<?php echo $langDir; ?>" <?php echo (isset($fullHeight)) ? ' class="uk-height-1-1"' : NULL ?>>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php if(isset($settings['st_google_site_verification']) && !empty($settings['st_google_site_verification'])): ?>
<meta name="google-site-verification" content="<?php echo htmlspecialchars($settings['st_google_site_verification']); ?>" />
<?php endif; ?>
<?php if(isset($settings['st_google_adsense_id']) && !empty($settings['st_google_adsense_id'])): ?>
<meta name="google-adsense-account" content="<?php echo htmlspecialchars($settings['st_google_adsense_id']); ?>">
<?php endif; ?>
<link rel="shortcut icon" href="<?php echo $urlPath->image($theme['th_favicon']); ?>?v=<?php echo time(); ?>">
<link rel="icon" type="image/png" sizes="192x192" href="<?php echo $urlPath->image($theme['th_favicon']); ?>?v=<?php echo time(); ?>">
<link rel="icon" type="image/png" sizes="32x32" href="<?php echo $urlPath->image($theme['th_favicon']); ?>?v=<?php echo time(); ?>">
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo $urlPath->image($theme['th_favicon']); ?>?v=<?php echo time(); ?>">
<link rel="apple-touch-icon" sizes="180x180" href="<?php echo $urlPath->image($theme['th_favicon']); ?>?v=<?php echo time(); ?>">

<?php if(isset($titleSeoHeader) && !empty($titleSeoHeader)): ?>
<title><?php echo echoOutput($titleSeoHeader); ?></title>
<?php endif; ?>
<?php if(isset($descriptionSeoHeader) && !empty($descriptionSeoHeader)): ?>
<meta name="description" content="<?php echo echoOutput($descriptionSeoHeader); ?>">
<?php endif; ?>

<!-- Canonical URL -->
<link rel="canonical" href="<?php echo isset($canonicalUrl) ? $canonicalUrl : 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>" />

<!-- Pagination Meta Tags -->
<?php if(isset($_GET['page']) && $_GET['page'] > 1): ?>
<meta name="robots" content="noindex, follow" />
<?php endif; ?>

<!-- Open Graph Meta Tags -->
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Alonedeals" />
<meta property="og:title" content="<?php echo isset($titleSeoHeader) ? echoOutput($titleSeoHeader) : 'Alonedeals - Best Coupons & Deals'; ?>" />
<meta property="og:description" content="<?php echo isset($descriptionSeoHeader) ? echoOutput($descriptionSeoHeader) : 'Find the best coupons, deals, and cashback offers from top brands.'; ?>" />
<meta property="og:url" content="<?php echo isset($canonicalUrl) ? $canonicalUrl : 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>" />
<?php if(isset($itemDetails) && !empty($itemDetails)): ?>
<?php if(!empty($itemDetails['store_image'])): ?>
<meta property="og:image" content="<?php echo $urlPath->image($itemDetails['store_image']); ?>" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<?php elseif(!empty($itemDetails['category_image'])): ?>
<meta property="og:image" content="<?php echo getImageUrl($itemDetails['category_image_cdn_url'], $itemDetails['category_use_cdn'], $itemDetails['category_image']); ?>" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<?php endif; ?>
<?php endif; ?>

<!-- Twitter Card Meta Tags -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="<?php echo isset($titleSeoHeader) ? echoOutput($titleSeoHeader) : 'Alonedeals - Best Coupons & Deals'; ?>" />
<meta name="twitter:description" content="<?php echo isset($descriptionSeoHeader) ? echoOutput($descriptionSeoHeader) : 'Find the best coupons, deals, and cashback offers from top brands.'; ?>" />
<?php if(isset($itemDetails) && !empty($itemDetails)): ?>
<?php if(!empty($itemDetails['store_image'])): ?>
<meta name="twitter:image" content="<?php echo $urlPath->image($itemDetails['store_image']); ?>" />
<?php elseif(!empty($itemDetails['category_image'])): ?>
<meta name="twitter:image" content="<?php echo getImageUrl($itemDetails['category_image_cdn_url'], $itemDetails['category_use_cdn'], $itemDetails['category_image']); ?>" />
<?php endif; ?>
<?php endif; ?>
<?php if(!empty($settings['st_twitter'])): ?>
<meta name="twitter:site" content="<?php echo htmlspecialchars($settings['st_twitter']); ?>" />
<?php endif; ?>

<!-- Performance Optimization: Preconnect to external domains -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preconnect" href="https://www.google-analytics.com">
<link rel="preconnect" href="https://www.googletagmanager.com">
<link rel="dns-prefetch" href="https://fonts.googleapis.com">
<link rel="dns-prefetch" href="https://fonts.gstatic.com">
<link rel="dns-prefetch" href="https://www.google-analytics.com">
<link rel="dns-prefetch" href="https://www.googletagmanager.com">

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

<!-- Centralized CSS -->
<?php include __DIR__ . '/includes/header-css.php'; ?>

<!-- Related Content Widget CSS -->
<link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/related-content-widget.css">

<?php if ($langDir == 'rtl'): ?>
<script type="text/javascript"> window.FontAwesomeConfig = { autoReplaceSvg: false }</script>
<link rel="stylesheet" href="<?php echo $urlPath->assets_css('uikit-rtl.css'); ?>">
<link rel="stylesheet" href="<?php echo $urlPath->assets_css('theme-rtl.css'); ?>">
<?php endif;?>

<!-- Centralized JS -->
<?php include __DIR__ . '/includes/header-js.php'; ?>

<?php if (!empty($settings['st_recaptchakey'])): ?>
<script async src="https://www.google.com/recaptcha/api.js"></script>
<?php endif; ?>

<!-- Push Notification Configuration -->
<?php
// Get push notification settings
$push_settings_query = $connect->query("SELECT * FROM push_notification_settings WHERE id = 1");
$push_notification_config = $push_settings_query->fetch(PDO::FETCH_ASSOC);
if ($push_notification_config && $push_notification_config['notification_enabled']):
?>
<script>
window.PUSH_NOTIFICATION_CONFIG = {
    enabled: true,
    appId: '<?php echo htmlspecialchars($push_notification_config['onesignal_app_id']); ?>',
    safariWebId: '<?php echo htmlspecialchars($push_notification_config['onesignal_safari_web_id'] ?? ''); ?>'
};
</script>
<?php endif; ?>

<!-- Firebase SDK -->
<?php if(isset($settings['firebase_enabled']) && $settings['firebase_enabled'] == 1): ?>
<?php
// Get Firebase configuration from database
$firebaseConfigQuery = $connect->query("SELECT * FROM firebase_config WHERE id = 1");
$firebaseConfig = $firebaseConfigQuery->fetch(PDO::FETCH_ASSOC);
?>
<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-auth-compat.js"></script>
<script src="<?php echo $urlPath->assets_js('firebase-auth.js'); ?>"></script>
<?php if($firebaseConfig && $firebaseConfig['config_enabled']): ?>
<script>
// Initialize Firebase with configuration
const firebaseConfig = {
    apiKey: "<?php echo htmlspecialchars($firebaseConfig['config_api_key'] ?? ''); ?>",
    authDomain: "<?php echo htmlspecialchars($firebaseConfig['config_auth_domain'] ?? ''); ?>",
    projectId: "<?php echo htmlspecialchars($firebaseConfig['config_project_id'] ?? ''); ?>",
    storageBucket: "<?php echo htmlspecialchars($firebaseConfig['config_storage_bucket'] ?? ''); ?>",
    messagingSenderId: "<?php echo htmlspecialchars($firebaseConfig['config_messaging_sender_id'] ?? ''); ?>",
    appId: "<?php echo htmlspecialchars($firebaseConfig['config_app_id'] ?? ''); ?>"
    <?php if(!empty($firebaseConfig['config_measurement_id'])): ?>
    ,measurementId: "<?php echo htmlspecialchars($firebaseConfig['config_measurement_id']); ?>"
    <?php endif; ?>
};

// Initialize Firebase
if (typeof firebase !== 'undefined' && firebaseConfig.apiKey) {
    try {
        firebase.initializeApp(firebaseConfig);
        console.log('Firebase initialized successfully');
    } catch (error) {
        console.error('Firebase initialization error:', error);
    }
}
</script>
<?php endif; ?>
<script src="<?php echo $urlPath->assets_js('auth-handler.js'); ?>"></script>
<?php endif; ?>

<?php if(isset($settings['st_google_tag_manager_id']) && !empty($settings['st_google_tag_manager_id'])): ?>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','<?php echo htmlspecialchars($settings['st_google_tag_manager_id']); ?>');</script>
<!-- End Google Tag Manager -->
<?php endif; ?>

<?php if(isset($settings['st_google_analytics_id']) && !empty($settings['st_google_analytics_id'])): ?>
<!-- Google Analytics 4 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo htmlspecialchars($settings['st_google_analytics_id']); ?>"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '<?php echo htmlspecialchars($settings['st_google_analytics_id']); ?>');
</script>
<!-- End Google Analytics 4 -->
<?php endif; ?>

<?php if(isset($settings['st_google_adsense_id']) && !empty($settings['st_google_adsense_id'])): ?>
<!-- Google AdSense -->
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=<?php echo htmlspecialchars($settings['st_google_adsense_id']); ?>"
     crossorigin="anonymous"></script>
<!-- End Google AdSense -->
<?php endif; ?>

<?php if(isset($settings['st_facebook_pixel_id']) && !empty($settings['st_facebook_pixel_id'])): ?>
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '<?php echo htmlspecialchars($settings['st_facebook_pixel_id']); ?>');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=<?php echo htmlspecialchars($settings['st_facebook_pixel_id']); ?>&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->
<?php endif; ?>

<!-- Organization Schema -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Organization",
  "name": "Alonedeals",
  "url": "<?php echo SITE_URL; ?>",
  "logo": "<?php echo $urlPath->image($theme['th_logo']); ?>",
  "description": "Find the best coupons, deals, and cashback offers from top brands. Save money on every purchase with verified promo codes.",
  "sameAs": [
    <?php 
    $social_links = [];
    if (!empty($settings['st_facebook'])) $social_links[] = '"' . $settings['st_facebook'] . '"';
    if (!empty($settings['st_twitter'])) $social_links[] = '"' . $settings['st_twitter'] . '"';
    if (!empty($settings['st_instagram'])) $social_links[] = '"' . $settings['st_instagram'] . '"';
    if (!empty($settings['st_youtube'])) $social_links[] = '"' . $settings['st_youtube'] . '"';
    echo implode(',', $social_links);
    ?>
  ]
}
</script>

<!-- WebSite Schema -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "WebSite",
  "name": "Alonedeals",
  "url": "<?php echo SITE_URL; ?>",
  "potentialAction": {
    "@type": "SearchAction",
    "target": "<?php echo SITE_URL; ?>/search?query={search_term_string}",
    "query-input": "required name=search_term_string"
  }
}
</script>

<script type="text/javascript">
/* Global js vars */
var SITEURL = "<?php echo SITE_URL; ?>";
var IMAGES_FOLDER = "<?php echo $urlPath->image(); ?>";
</script>
<?php if(isset($settings['st_analytics']) && !empty($settings['st_analytics'])): ?>
<?php echo $settings['st_analytics']; ?>
<?php endif; ?>

</head> 
<body <?php echo (isset($fullHeight)) ? 'class="uk-height-1-1"' : NULL ?>>

<?php if(isset($settings['st_google_tag_manager_id']) && !empty($settings['st_google_tag_manager_id'])): ?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=<?php echo htmlspecialchars($settings['st_google_tag_manager_id']); ?>"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php endif; ?>

<div id="preloader">
<div class="spinner">
<div class="modern-spinner">
<div class="spinner-circle"></div>
<div class="spinner-circle"></div>
<div class="spinner-circle"></div>
</div>
</div>
</div>

<!-- Fallback preloader removal (doesn't require jQuery) -->
<script>
(function() {
    'use strict';
    
    // Remove preloader when page loads
    function removePreloader() {
        var preloader = document.getElementById('preloader');
        if (preloader) {
            preloader.style.opacity = '0';
            preloader.style.transition = 'opacity 0.5s';
            setTimeout(function() {
                preloader.style.display = 'none';
            }, 500);
        }
    }
    
    // Try to remove on load
    if (document.readyState === 'complete') {
        removePreloader();
    } else {
        window.addEventListener('load', removePreloader);
    }
    
    // Emergency fallback - remove after 5 seconds no matter what
    setTimeout(function() {
        var preloader = document.getElementById('preloader');
        if (preloader && preloader.style.display !== 'none') {
            preloader.style.display = 'none';
        }
    }, 5000);
})();
</script>

<?php if($maintenanceMode == 1 && isAdmin()): ?>
<div class="tas-alert-danger uk-margin-remove" uk-alert>
    <a class="uk-alert-close" uk-close></a>
    <p><i class="fas fa-exclamation-triangle uk-margin-small-right"></i> <?php echo echoOutput($translation['tr_maintenancetitle']); ?></p>
</div>
<?php endif; ?>

<?php require './sections/sidemenu.php'; ?>


<?php if(getCodeParams()): ?>
<?php include './single-modal.php'; ?>
<?php endif; ?>