<?php  

use Core\System\ThemeManager;
use Core\System\SeoManager;
use Core\App\Models\HomeSections;

$logoUrl    = ThemeManager::getSetting('site_logo', '/themes/matjari/assets/img/logo.png');
$logoAlt    = trim((string) ThemeManager::getSetting('site_name', 'Website')) ?: 'Website';
$colors     = ThemeManager::getSetting('colors', []);
$headerMenu = ThemeManager::getSetting('header_menu', []);

$hasTopBar = false;

/**
 * ==========================================================
 * LANGUAGE (Single Source of Truth)
 * ==========================================================
 * Source: settings.default_language
 */
$lang = ThemeManager::getSetting('default_language', 'ar');
$lang = strtolower(trim((string)$lang));

if ($lang === '') {
    $lang = 'ar';
}

$isRtl = !in_array($lang, ['en', 'en-us', 'en-gb'], true);
$htmlDir  = $isRtl ? 'rtl' : 'ltr';
$htmlLang = $isRtl ? 'ar'  : 'en';

// ==============================
// SEO (Centralized)
// ==============================
SeoManager::init([
    'lang' => $htmlLang,
    'dir'  => $htmlDir,
]);

$seo = SeoManager::get();

?>
<!doctype html>
<html lang="<?= htmlspecialchars($htmlLang, ENT_QUOTES, 'UTF-8') ?>" dir="<?= htmlspecialchars($htmlDir, ENT_QUOTES, 'UTF-8') ?>">
<head>
    <meta charset="utf-8">

    <!-- SEO -->
    <title><?= htmlspecialchars($seo['title'], ENT_QUOTES, 'UTF-8') ?></title>
    <meta name="description" content="<?= htmlspecialchars($seo['description'], ENT_QUOTES, 'UTF-8') ?>">
    <meta name="robots" content="<?= htmlspecialchars($seo['robots'], ENT_QUOTES, 'UTF-8') ?>">
    <?php if (!empty($seo['keywords'])): ?><meta name="keywords" content="<?= htmlspecialchars($seo['keywords'], ENT_QUOTES, 'UTF-8') ?>"><?php endif; ?>
    <?php
    $seoImage = $seo['image'] ?? '';
    $seoCanonical = \Core\System\SeoManager::absoluteUrl((string)($seo['canonical'] ?? ''));
    ?>
    <link rel="canonical" href="<?= htmlspecialchars($seoCanonical, ENT_QUOTES, 'UTF-8') ?>">

    <?php
    /*
     * hreflang — Single-language self-referencing tag only.
     * This store serves one language at a time (ar or en based on admin setting).
     * A proper multi-language alternate setup requires separate URLs per locale,
     * which is not the current architecture. We output a correct self-reference
     * so crawlers know the language of this page without false alternate signals.
     */
    if (!empty($seoCanonical)):
        $hreflangLocale = ($htmlLang === 'ar') ? 'ar' : 'en';
    ?>
    <link rel="alternate" hreflang="<?= htmlspecialchars($hreflangLocale, ENT_QUOTES, 'UTF-8') ?>" href="<?= htmlspecialchars($seoCanonical, ENT_QUOTES, 'UTF-8') ?>">
    <?php endif; ?>

    <?php
    $seoImage = $seo['image'] ?? '';
    $fbAppId = trim((string) ThemeManager::getSetting('facebook_app_id', ''));
    $ogType = ($seo['type'] ?? '') === 'product' ? 'product' : 'website';
    $ogLocale = ($htmlLang === 'ar') ? 'ar_AR' : 'en_US';
    ?>

    <!-- Open Graph -->
    <meta property="og:title" content="<?= htmlspecialchars($seo['og_title'] ?? $seo['title'], ENT_QUOTES, 'UTF-8') ?>">
    <meta property="og:description" content="<?= htmlspecialchars($seo['og_description'] ?? $seo['description'], ENT_QUOTES, 'UTF-8') ?>">
    <meta property="og:url" content="<?= htmlspecialchars($seoCanonical, ENT_QUOTES, 'UTF-8') ?>">
    <meta property="og:type" content="<?= htmlspecialchars($ogType, ENT_QUOTES, 'UTF-8') ?>">
    <meta property="og:site_name" content="<?= htmlspecialchars(ThemeManager::getSetting('site_name', ''), ENT_QUOTES, 'UTF-8') ?>">
    <meta property="og:locale" content="<?= htmlspecialchars($ogLocale, ENT_QUOTES, 'UTF-8') ?>">

    <?php if (!empty($seoImage)): ?>
    <meta property="og:image" content="<?= htmlspecialchars($seoImage, ENT_QUOTES, 'UTF-8') ?>">
    <meta property="og:image:secure_url" content="<?= htmlspecialchars($seoImage, ENT_QUOTES, 'UTF-8') ?>">
    <meta property="og:image:width" content="<?= (int)($seo['image_width'] ?? 1200) ?>">
    <meta property="og:image:height" content="<?= (int)($seo['image_height'] ?? 630) ?>">
    <?php if (!empty($seo['image_type'])): ?><meta property="og:image:type" content="<?= htmlspecialchars($seo['image_type'], ENT_QUOTES, 'UTF-8') ?>"><?php endif; ?>
    <meta property="og:image:alt" content="<?= htmlspecialchars($seo['og_title'] ?? $seo['meta_title'] ?? $seo['title'], ENT_QUOTES, 'UTF-8') ?>">
    <?php endif; ?>
    <?php if ($fbAppId !== ''): ?>
    <meta property="fb:app_id" content="<?= htmlspecialchars($fbAppId, ENT_QUOTES, 'UTF-8') ?>">
    <?php endif; ?>
    <?php if (($seo['type'] ?? '') === 'product' && !empty($seo['schema']['offers']['price'])): ?>
    <meta property="product:price:amount" content="<?= htmlspecialchars((string)$seo['schema']['offers']['price'], ENT_QUOTES, 'UTF-8') ?>">
    <meta property="product:price:currency" content="<?= htmlspecialchars((string)($seo['schema']['offers']['priceCurrency'] ?? ThemeManager::getSetting('currency', 'DZD')), ENT_QUOTES, 'UTF-8') ?>">
    <meta property="product:availability" content="<?= htmlspecialchars((string)($seo['schema']['offers']['availability'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
    <?php endif; ?>

    <!-- Twitter Card -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?= htmlspecialchars($seo['og_title'] ?? $seo['title'], ENT_QUOTES, 'UTF-8') ?>">
    <meta name="twitter:description" content="<?= htmlspecialchars($seo['og_description'] ?? $seo['description'], ENT_QUOTES, 'UTF-8') ?>">
    <meta name="twitter:url" content="<?= htmlspecialchars($seoCanonical, ENT_QUOTES, 'UTF-8') ?>">
    <?php if (!empty($seoImage)): ?>
    <meta name="twitter:image" content="<?= htmlspecialchars($seoImage, ENT_QUOTES, 'UTF-8') ?>">
    <meta name="twitter:image:alt" content="<?= htmlspecialchars($seo['meta_title'] ?? $seo['title'], ENT_QUOTES, 'UTF-8') ?>">
    <?php endif; ?>

    <link rel="stylesheet" href="/public/assets/shared/product-badges.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon"
          href="<?= htmlspecialchars(ThemeManager::getFavicon(), ENT_QUOTES, 'UTF-8') ?>">
<style>
    :root {
        --primary-color: <?= $colors['primary'] ?? '#ff5722' ?>;
        --secondary-color: <?= $colors['secondary'] ?? '#4CAF50' ?>;
        --top-bar-bg: <?= $colors['dark'] ?? ($colors['primary'] ?? '#ff5722') ?>;
        --top-bar-fc: <?= $colors['warning'] ?? ($colors['primary'] ?? '#ff5722') ?>;
    }

    .site-header {
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        position: relative;
        z-index: 100;
    }

    .header-menu-btn{
        display:none;
        background:transparent;
        border:0;
        padding:8px;
        line-height:0;
        color:inherit;
        cursor:pointer;
    }

    @media (max-width: 992px){

        .header-nav{
            display:none !important;
        }

        .header-inner{
            position: relative;
            display:flex;
            align-items:center;
            justify-content:center;
            gap:10px;
        }

        .header-logo{
            position:absolute;
            left:50%;
            transform:translateX(-50%);
            margin:0 !important;
        }

        .header-product-info{
            display:none;
        }

        .product-page .site-header.scrolled .header-product-info{
            display:flex !important;
        }

        .product-page .site-header.scrolled .header-logo{
            display:none !important;
        }

        .header-cta{
            position:absolute;
            inset-inline-start: 0;
            inset-inline-end: auto;
            display:flex !important;
            align-items:center;
            gap:8px;
        }

        .header-menu-btn{
            display:inline-flex;
            align-items:center;
            justify-content:center;
        }

        .header-search-btn{
            display:none !important;
        }

        .product-page .site-header.scrolled .header-menu-btn{
            display:none !important;
        }

        .product-page .site-header.scrolled .header-cta{
            display:none !important;
        }

        .product-page .site-header.scrolled .header-inner{
            justify-content: space-between !important;
        }

        .product-page .site-header.scrolled .header-product-info{
            width:100% !important;
            display:flex !important;
            align-items:center !important;
            justify-content: space-between !important;
            gap:10px !important;
            flex-direction: row !important;
        }

        .product-page .site-header.scrolled .header-product-right{
            flex: 1 1 auto !important;
            max-width: calc(100% - 90px) !important;
            display:flex !important;
            flex-direction: column !important;
            align-items: flex-start !important;
            justify-content: center !important;
            gap: 2px !important;
            min-width: 0 !important;
        }

        .product-page .site-header.scrolled .header-product-title-row{
            display:flex !important;
            align-items:center !important;
            justify-content:flex-start !important;
            width:100% !important;
            min-width:0 !important;
        }

        .product-page .site-header.scrolled .header-product-name{
            font-size: 15px !important;
            font-weight: 700 !important;
            line-height: 1.25 !important;
            white-space: nowrap !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
            max-width: 100% !important;
            min-width: 0 !important;
            display:block !important;
        }

        .product-page .site-header.scrolled .header-product-stars{
            display:block !important;
            margin-top: 2px !important;
            line-height: 1 !important;
        }

        .product-page .site-header.scrolled .header-product-left{
            display:flex !important;
            align-items:center !important;
            justify-content:flex-end !important;
            flex: 0 0 auto !important;
            white-space: nowrap !important;
        }

        .product-page .site-header.scrolled .header-product-price{
            font-size: 15px !important;
            font-weight: 800 !important;
            white-space: nowrap !important;
        }
    }

    @media (max-width: 768px){

        .product-page .site-header.scrolled .header-inner{
            padding-inline: 12px !important;
        }

        .product-page .site-header.scrolled .header-product-info{
            width:100% !important;
            margin:0 !important;
            justify-content:space-between !important;
            align-items:center !important;
            text-align:initial !important;
            flex-direction: row !important;
        }

        .product-page .site-header.scrolled .header-product-right{
            text-align: right !important;
            align-items: flex-start !important;
        }

        html[dir="ltr"] .product-page .site-header.scrolled .header-product-right{
            text-align: left !important;
        }

        .product-page .site-header.scrolled .header-product-left{
            justify-content: flex-end !important;
        }
    }

    .mobile-menu-overlay{
        position:fixed;
        inset:0;
        background:rgba(0,0,0,.45);
        z-index:9998;
        display:none;
    }
    .mobile-menu-overlay.is-open{ display:block; }

    .mobile-menu-panel{
        position:fixed;
        top:0;
        bottom:0;
        width:min(420px, 92vw);
        background:#fff;
        z-index:9999;
        display:none;
        overflow:auto;
        -webkit-overflow-scrolling: touch;
        box-shadow: 0 12px 30px rgba(0,0,0,.18);
        border-radius: 16px;
        margin: 10px;
    }

    .mobile-menu-panel{
        inset-inline-end: 0;
    }

    html[dir="rtl"] .mobile-menu-panel{
        right: 0 !important;
        left: auto !important;
    }

    html[dir="ltr"] .mobile-menu-panel{
        left: 0 !important;
        right: auto !important;
    }

    .mobile-menu-panel.is-open{ display:block; }

    .mobile-menu-header{
        display:flex;
        align-items:center;
        gap:10px;
        padding:14px 14px 10px 14px;
        border-bottom:1px solid #eee;
    }
    .mobile-menu-close{
        background:#f2f2f2;
        border:0;
        width:36px;
        height:36px;
        border-radius:10px;
        display:inline-flex;
        align-items:center;
        justify-content:center;
        cursor:pointer;
    }
    .mobile-menu-search{
        padding:12px 14px;
        border-bottom:1px solid #eee;
    }
    .mobile-menu-search input{
        width:100%;
        border:1px solid #e6e6e6;
        border-radius:12px;
        padding:12px 12px;
        outline:none;
    }
    .mobile-menu-links{
        padding:6px 0;
    }
    .mobile-menu-links a{
        display:block;
        padding:14px 16px;
        text-decoration:none;
        color:#222;
        border-bottom:1px solid #f0f0f0;
    }
    .mobile-menu-links a:hover{
        background:#fafafa;
    }
</style>

<?php
\Core\App\Services\ThemeAssetService::ensureFrontendCss();
$generatedThemeCssUrl = \Core\App\Services\ThemeAssetService::assetUrl();
?>
    <link rel="stylesheet" href="<?= htmlspecialchars($generatedThemeCssUrl, ENT_QUOTES, 'UTF-8') ?>">
<link rel="preload" href="/public/assets/css/app.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="/public/assets/css/app.css"></noscript>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">

	<?php
use Core\System\SchemaManager;
echo SchemaManager::render();
?>
<?php

require_once ROOT_PATH . '/core/app/Services/Ga4TrackingService.php';
require_once ROOT_PATH . '/core/app/Services/FacebookPixelTrackingService.php';
require_once ROOT_PATH . '/core/app/Services/TikTokPixelTrackingService.php';
require_once ROOT_PATH . '/core/app/Services/GtmTrackingService.php';

(new \Ga4TrackingService())->inject();
(new \FacebookPixelTrackingService())->inject();
(new \TikTokPixelTrackingService())->inject();
(new \GtmTrackingService())->inject();

?>

</head>

<body class="product-page">



<?php
// ==============================
// Global Top Bar (All Pages)
// ==============================
$sectionsModel = new HomeSections();
$sections = $sectionsModel->getAll();

foreach ($sections as $section) {
    if (
        ($section['section_type'] ?? null) === 'top_bar' &&
        (int)($section['is_enabled'] ?? 0) === 1
    ) {
        $hasTopBar = true;
        $settings = $section['settings'] ?? [];
        include dirname(__DIR__) . '/home_sections/top_bar.php';
        break;
    }
}
?>

<?php if (!$hasTopBar): ?>
    <style>
        :root { --top-bar-height: 0px; }
    </style>
<?php endif; ?>

<header class="site-header" id="siteHeader">
    <div class="container header-inner">

        <div class="header-logo">
            <a href="/">
                <img src="<?= htmlspecialchars($logoUrl, ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars($logoAlt, ENT_QUOTES, 'UTF-8') ?>" decoding="async">
            </a>
        </div>

        <!-- PRODUCT INFO (STICKY MODE ONLY) -->
<div class="header-product-info">

    <!-- RIGHT : NAME + BADGE + STARS -->
    <div class="header-product-right">

        <!-- NAME + BADGE (SAME ROW) -->
        <div class="header-product-title-row">
            <span class="header-product-name">
                <?= htmlspecialchars($seo['title'], ENT_QUOTES, 'UTF-8') ?>
            </span>

            <span class="header-product-badge">
                <?= __('product.badge', 'New') ?>
            </span>
        </div>

        <!-- STARS (VISUAL ONLY) -->
        <div class="header-product-stars"></div>

    </div>

    <!-- LEFT : PRICE -->
    <div class="header-product-left">
        <span class="header-product-price"></span>
    </div>

</div>


        <nav class="header-nav">
            <?php if (!empty($headerMenu) && is_array($headerMenu)): ?>
                <?php foreach ($headerMenu as $item): ?>
                    <?php if (empty($item['enabled'])) continue; ?>
                    <a href="<?= htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') ?>">
                        <?= __($item['label'], $item['label']) ?>
                    </a>
                <?php endforeach; ?>
            <?php endif; ?>
        </nav>

        <div class="header-cta">
            <button
                type="button"
                class="header-search-btn"
                data-toggle-search
                aria-label="<?= __('header.search', 'Search') ?>"
            >
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                    <path d="M21 21L16.65 16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    <circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="2"/>
                </svg>
            </button>

            <button type="button"
                    class="header-menu-btn"
                    id="openMobileMenu"
                    aria-label="<?= __('header.menu', 'Menu') ?>">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                    <path d="M4 7H20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    <path d="M4 12H20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    <path d="M4 17H20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                </svg>
            </button>

        </div>

    </div>
</header>

<div class="header-search-bar">
    <div class="container">
        <form action="/products" method="get">
            <input
                type="text"
                name="q"
                placeholder="<?= __('header.search_placeholder', 'Search for products...') ?>"
                aria-label="<?= __('header.search', 'Search') ?>"
            >
        </form>
    </div>
</div>

<div class="search-overlay" id="searchOverlay">
    <div class="search-overlay-inner">
        <button
            type="button"
            class="search-close-btn"
            aria-label="<?= __('actions.close', 'Close') ?>"
        >✕</button>

        <form class="search-form" action="/products" method="get">
            <input
                type="text"
                name="q"
                placeholder="<?= __('header.search_placeholder', 'Search for products...') ?>"
            >
        </form>
    </div>
</div>

<div class="mobile-menu-overlay" id="mobileMenuOverlay" aria-hidden="true"></div>

<div class="mobile-menu-panel" id="mobileMenuPanel" aria-hidden="true">
    <div class="mobile-menu-header">
        <button type="button" class="mobile-menu-close" id="closeMobileMenu" aria-label="<?= __('actions.close', 'Close') ?>">✕</button>
        <div style="flex:1; font-weight:600;">
            <?= __('header.menu', 'Menu') ?>
        </div>
    </div>

    <div class="mobile-menu-search">
        <form action="/products" method="get">
        <input type="text" name="q"
               placeholder="<?= __('header.search_placeholder', 'Search for products...') ?>"
               aria-label="<?= __('header.search', 'Search') ?>">
        </form>
    </div>

    <div class="mobile-menu-links">
        <?php if (!empty($headerMenu) && is_array($headerMenu)): ?>
            <?php foreach ($headerMenu as $item): ?>
                <?php if (empty($item['enabled'])) continue; ?>
                <a href="<?= htmlspecialchars($item['url'], ENT_QUOTES, 'UTF-8') ?>">
                    <?= __($item['label'], $item['label']) ?>
                </a>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {

    const openBtn   = document.getElementById('openMobileMenu');
    const closeBtn  = document.getElementById('closeMobileMenu');
    const overlay   = document.getElementById('mobileMenuOverlay');
    const panel     = document.getElementById('mobileMenuPanel');

    function openMenu(){
        overlay.classList.add('is-open');
        panel.classList.add('is-open');
        overlay.setAttribute('aria-hidden', 'false');
        panel.setAttribute('aria-hidden', 'false');
        document.documentElement.style.overflow = 'hidden';
    }

    function closeMenu(){
        overlay.classList.remove('is-open');
        panel.classList.remove('is-open');
        overlay.setAttribute('aria-hidden', 'true');
        panel.setAttribute('aria-hidden', 'true');
        document.documentElement.style.overflow = '';
    }

    openBtn && openBtn.addEventListener('click', openMenu);
    closeBtn && closeBtn.addEventListener('click', closeMenu);
    overlay && overlay.addEventListener('click', closeMenu);

    document.addEventListener('keydown', function(e){
        if(e.key === 'Escape'){
            closeMenu();
        }
    });

});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {

    const titleEl  = document.querySelector('.product-title');
    const priceEl  = document.querySelector('.product-price, .price-current, .price-new');
    const headerTitle = document.querySelector('.header-product-name');
    const headerPrice = document.querySelector('.header-product-price');

    if (titleEl && headerTitle) {
        headerTitle.textContent = titleEl.textContent.trim();
    }

    if (priceEl && headerPrice) {
        headerPrice.textContent = priceEl.textContent.trim();
    }

});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {

    const productBadge = document.querySelector('.product-badge');
    const headerBadge  = document.querySelector('.header-product-badge');

    if (productBadge && headerBadge) {
        headerBadge.textContent = productBadge.textContent.trim();
        headerBadge.className = 'header-product-badge';
        Array.from(productBadge.classList).forEach(function(cls){
            if (cls !== 'product-badge') headerBadge.classList.add(cls);
        });
    }

});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {

    const headerPrice = document.querySelector('.header-product-price');

    const priceNew = document.querySelector('.price-new');
    const priceCurrent = document.querySelector('.price-current');

    if (headerPrice) {
        if (priceNew) {
            headerPrice.textContent = priceNew.textContent.trim();
        } else if (priceCurrent) {
            headerPrice.textContent = priceCurrent.textContent.trim();
        }
    }

});
</script>

<main class="site-content">
