<?php
// CRITICAL: Session already started in index.php or calling file
// Do not start session again
if (session_status() !== PHP_SESSION_ACTIVE) {
  ini_set('session.use_strict_mode', 1);
  ini_set('session.use_only_cookies', 1);
  session_start();
}

// SET DEFAULT LANGUAGE & CURRENCY ON FIRST VISIT
if (!isset($_SESSION['selected_language'])) {
  $_SESSION['selected_language'] = 'eng';  // Default: English (lowercase 3-letter code)
}
if (!isset($_SESSION['selected_currency'])) {
  $_SESSION['selected_currency'] = 'usd';  // Default: Dollar (lowercase)
}

// Set language preference - browsers will use this for translation
$language_map = ['eng' => 'en', 'ita' => 'it', 'esp' => 'es', 'ger' => 'de'];
$current_lang = $_SESSION['selected_language'] ?? 'eng';
$html_lang = $language_map[$current_lang] ?? 'en';
define('HTML_LANG', $html_lang);

// Load Translation Helper
require_once __DIR__ . '/config/translation_helper.php';

// Phase 2: SEO Helpers - Include all Phase 2 helpers
require_once __DIR__ . '/helpers/meta_tags_helper.php';
require_once __DIR__ . '/helpers/heading_helper.php';
require_once __DIR__ . '/helpers/image_alt_helper.php';
require_once __DIR__ . '/helpers/internal_linking_helper.php';
require_once __DIR__ . '/helpers/schema_helper.php';

// Phase 3: Content SEO Helpers - Include Phase 3 helpers
require_once __DIR__ . '/helpers/keyword_optimizer.php';
require_once __DIR__ . '/helpers/faq_helper.php';
require_once __DIR__ . '/helpers/content_optimizer.php';

// Include wishlist handler
require_once __DIR__ . '/wishlist_handler.php';

// Include navigation helper for featured pages menu
require_once __DIR__ . '/helpers/navigation_helper.php';

$cart_count = 0;
if (!empty($_SESSION['cart']) && is_array($_SESSION['cart'])) {
  foreach ($_SESSION['cart'] as $q) { $cart_count += (int)$q; }
}

// Get wishlist count
$userId = $_SESSION['user_id'] ?? 'guest_' . md5($_SERVER['REMOTE_ADDR']);
$wishlistItems = getWishlistItems($userId);
// Ensure wishlistItems is an array and filter out any invalid entries
if (!is_array($wishlistItems)) {
    $wishlistItems = [];
}
// Filter out any non-numeric or invalid IDs
$wishlistItems = array_filter($wishlistItems, function($id) {
    return is_numeric($id) && $id > 0;
});
$wishlist_count = count($wishlistItems);

// Load site config and settings
$siteTitle = "Emporio Sport";
$siteLogo = "sport-pics/logo-1.png";
$headerBgColor = "#ffffff";
$promoText = "Abbigliamento personalizzato per aziende e associazioni - Consulenza gratuita";
$dataDir = __DIR__ . '/data';
$configFile = $dataDir . '/site_config.json';
$settingsFile = $dataDir . '/site_settings.json';
$headerConfigFile = $dataDir . '/header_config.json';

// Detect web base path that works on both localhost (/emporio-sport)
// and cPanel root (/)
if (!defined('WEB_BASE_PATH')) {
    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    if (strpos($scriptName, '/emporio-sport/') === 0 || $scriptName === '/emporio-sport' || $scriptName === '/emporio-sport/index.php') {
        define('WEB_BASE_PATH', '/emporio-sport');
    } else {
        define('WEB_BASE_PATH', '');
    }
}

if (file_exists($configFile)) {
    $config = @json_decode(file_get_contents($configFile), true);
    if (is_array($config)) {
        if (!empty($config['title'])) $siteTitle = $config['title'];
        if (!empty($config['logo'])) {
            $siteLogo = $config['logo'];
        }
        if (!empty($config['header_bg_color'])) {
            $headerBgColor = $config['header_bg_color'];
        }
    }
}

if (file_exists($settingsFile)) {
    $settings = @json_decode(file_get_contents($settingsFile), true);
    if (is_array($settings) && !empty($settings['promo_strip']['text'])) {
        $promoText = $settings['promo_strip']['text'];
    }
}

// Load header configuration
$headerConfig = ['languages' => [], 'currencies' => [], 'help_link' => '/contact.php', 'selected_language' => 'en', 'selected_currency' => 'usd'];
if (file_exists($headerConfigFile)) {
    $headerConfigData = @json_decode(file_get_contents($headerConfigFile), true);
    if (is_array($headerConfigData)) {
        $headerConfig = $headerConfigData;
    }
}

// Get selected language and currency from session (already set at top of file)
// Uses $_SESSION values which default to ENG and USD
$selected_lang = strtolower($_SESSION['selected_language']);  // Will be 'eng', 'ita', 'esp', or 'ger'
$selected_currency = strtolower($_SESSION['selected_currency']);  // Will be 'usd', 'eur', 'gbp', or 'cad'

// Generate cache-buster for logo (if not already set by page-loader)
if (!isset($logoCacheBuster)) {
    $logoCacheBuster = '';
    // If siteLogo is already adjusted by page-loader (starts with ../), use it as-is
    // Otherwise, resolve relative to current directory
    if (strpos($siteLogo, '../') === 0) {
        $logoPath = __DIR__ . '/' . substr($siteLogo, 3);
    } else {
        $logoPath = __DIR__ . '/' . $siteLogo;
    }
    if (file_exists($logoPath)) {
        $logoCacheBuster = filemtime($logoPath);
    } else {
        $logoCacheBuster = time();
    }
}
?>

<!-- Promo Strip - NOT STICKY, scrolls away -->
<header style="background-color:<?php echo htmlspecialchars($headerBgColor); ?>;">
<div class="promo-strip" style="background:#1a1a1a; color:#fff; padding:12px 18px; font-size:12px; font-weight:600; display:flex; justify-content:space-between; align-items:center; gap:25px; flex-wrap:wrap; position: static;">
    <div style="display:flex; align-items:center; gap:25px;">
        <span><?php echo htmlspecialchars($promoText); ?></span>
    </div>
    <div style="display:flex; align-items:center; gap:25px;">
        <a href="<?php echo htmlspecialchars($headerConfig['help_link'] ?? '/contact.php'); ?>" style="color:#fff; text-decoration:none; display:flex; align-items:center; gap:6px;" title="Need Help">
            <span style="font-size:14px;">❓</span>
            <span><?php echo __('NEED_HELP', 'NEED HELP'); ?></span>
        </a>
        
        <!-- Language Dropdown -->
        <select id="languageSelect" onchange="changeLanguage(this)" style="background:#1a1a1a; color:#fff; border:none; cursor:pointer; font-size:12px; font-weight:600; outline:none; padding:4px 6px;">
            <?php
            if (!empty($headerConfig['languages']) && is_array($headerConfig['languages'])) {
                foreach ($headerConfig['languages'] as $lang) {
                    $langCode = isset($lang['code']) ? strtolower($lang['code']) : '';
                    $isSelected = ($langCode === $selected_lang) ? 'selected' : '';
                    echo '<option value="' . htmlspecialchars($langCode) . '" ' . $isSelected . '>' . htmlspecialchars($lang['label'] ?? '') . '</option>';
                }
            }
            ?>
        </select>
        
        <!-- Currency Dropdown -->
        <select id="currencySelect" onchange="changeCurrency(this)" style="background:#1a1a1a; color:#fff; border:none; cursor:pointer; font-size:12px; font-weight:600; outline:none; padding:4px 6px;">
            <?php
            if (!empty($headerConfig['currencies']) && is_array($headerConfig['currencies'])) {
                foreach ($headerConfig['currencies'] as $curr) {
                    $currCode = isset($curr['code']) ? strtolower($curr['code']) : '';
                    $isSelected = ($currCode === $selected_currency) ? 'selected' : '';
                    echo '<option value="' . htmlspecialchars($currCode) . '" ' . $isSelected . '>' . htmlspecialchars($curr['label'] ?? '') . '</option>';
                }
            }
            ?>
        </select>
    </div>
</div>

<!-- Google Translate Widget - With CSP Fix -->
<script>
// Simple language/currency preference handler
function changeLanguage(selectElement) {
    const value = selectElement.value;
    console.log('Changing language to:', value);
    
    // Save preference
    fetch('api_set_preference.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: 'language', value: value })
    })
    .then(r => r.json())
    .then(data => {
        console.log('Language saved, reloading...');
        // Reload silently - no alert
        window.location.reload();
    })
    .catch(e => console.error('Error:', e));
}

function changeCurrency(selectElement) {
    const value = selectElement.value;
    console.log('Changing currency to:', value);
    
    // Save preference
    fetch('api_set_preference.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: 'currency', value: value })
    })
    .then(r => r.json())
    .then(data => {
        console.log('Currency saved, reloading...');
        // Reload silently - no alert
        window.location.reload();
    })
    .catch(e => console.error('Error:', e));
}
</script>

<!-- Language/Currency switching - Clean server-side implementation -->
  <link rel="stylesheet" href="css/layout-system.css">
  <link rel="stylesheet" href="css/universal-image-system.css">
  <link rel="stylesheet" href="css/navigation-menu.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<nav class="site-nav">
    <a class="brand" href="index.php">
        <img src="<?php 
          $logoUrl = $siteLogo;
          // Handle path adjustments for different contexts
          if (defined('BASE_URL') && BASE_URL === '../') {
            // We're in a subdirectory (/pages/), adjust path
            if (strpos($logoUrl, '../') !== 0) {
              $logoUrl = '../' . $logoUrl;
            }
          }
          echo htmlspecialchars($logoUrl); 
        ?>?v=<?php echo $logoCacheBuster; ?>" alt="<?php echo htmlspecialchars($siteTitle); ?> Logo" class="brand-logo">
        <span class="brand-text"><?php echo htmlspecialchars($siteTitle); ?></span>
      </a>

    <div class="nav-links">
      <?php
      // Get featured pages from database
      $featuredPages = NavigationHelper::getFeaturedPages();
      $allPages = NavigationHelper::getAllPages();
      
      // Display featured pages
      foreach ($featuredPages as $navPage):
      ?>
        <a href="<?php echo htmlspecialchars($navPage['url']); ?>" title="<?php echo htmlspecialchars($navPage['title']); ?>">
          <?php echo htmlspecialchars(strtoupper($navPage['title'])); ?>
        </a>
      <?php endforeach; ?>
      
      <!-- <a href="<?php echo (defined('BASE_URL') ? BASE_URL : ''); ?>cart.php">Cart<?php echo $cart_count ? ' (' . $cart_count . ')' : ''; ?></a> -->
    </div>
<!-- header tag-->
 <!-- Header Tag -->
  
 <!-- header tag above-->

      <div class="nav-right">
        <!-- Search Icon and Hidden Search Bar -->
        <div class="search-container">
          <button id="searchIconBtn" class="search-icon-btn" type="button" onclick="toggleSearchBar()" title="Search">
          <i class="fa-solid fa-magnifying-glass"></i>
          </button>
          <form id="searchForm" action="shop.php" method="get" class="search-form">
            <input name="q" type="search" placeholder="Search styles, dresses..." class="search-input">
            <button class="search-btn" type="submit">Search</button>
          </form>
        </div>

        <?php if (!empty($_SESSION['user_id'])):
            $displayName = !empty($_SESSION['username']) ? $_SESSION['username'] : 'User';
            $parts = preg_split('/\s+/', $displayName);
            $initials = strtoupper(substr($parts[0],0,1) . (isset($parts[1])?substr($parts[1],0,1):''));
        ?>
          <div class="nav-user" id="navUser">
            <button class="user-btn" type="button" onclick="toggleUserDropdown(event)" aria-haspopup="true" aria-expanded="false" title="<?php echo htmlspecialchars($displayName); ?>">
              <i class="fa-solid fa-circle-user"></i>
            </button>
            <div class="user-dropdown" id="userDropdown">
              <a href="dashboard.php">Dashboard</a>
              <a href="profile.php">Profile</a>
              <a href="logout.php">Logout</a>
            </div>
          </div>
        <?php else: ?>
          <div class="user-area">
            <a class="user-btn" href="#" onclick="openLoginModal(); return false;" title="Sign In">
              👤
            </a>
          </div>
        <?php endif; ?>

        <!-- Wishlist Icon -->
        <a href="wishlist.php" class="user-btn user-btn-with-badge" title="Wishlist">
          <span class="icon-span"><i class="fa-regular fa-heart"></i></span>
          <?php if ($wishlist_count > 0): ?>
            <span class="badge">
              <?php echo $wishlist_count; ?>
            </span>
          <?php endif; ?>
        </a>

        <!-- Cart Icon -->
        <a href="cart.php" class="user-btn user-btn-with-badge" title="Cart">
          <span class="icon-span"><i class="fa-solid fa-basket-shopping"></i></span>
          <?php if ($cart_count > 0): ?>
            <span class="badge">
              <?php echo $cart_count; ?>
            </span>
          <?php endif; ?>
        </a>
      </div>
    </div>
  </nav>
</header>

<script>
// LANGUAGE CHANGER - Saves to server and reloads page for translations
function changeLanguage(selectElement) {
    const value = selectElement.value;
    
    console.log('Changing language to:', value);
    
    // Save to server
    fetch('/emporio-sport/api_set_preference.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: 'language', value: value })
    })
    .then(r => r.json())
    .then(data => {
        console.log('Language saved:', data);
        alert('Language changed to: ' + value.toUpperCase());
        // RELOAD PAGE to apply translations
        setTimeout(() => { 
            location.reload(); 
        }, 500);
    })
    .catch(e => {
        console.error('Language change error:', e);
        alert('Error changing language');
    });
}

// CURRENCY CONVERTER
function changeCurrency(selectElement) {
    const value = selectElement.value;
    
    console.log('Changing currency to:', value);
    fetch('api_set_preference.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: 'currency', value: value })
    })
    .then(r => r.json())
    .then(data => {
        console.log('Currency saved:', data);
        if (data.success) {
            // Reload to show prices in new currency
            alert('Currency changed to: ' + value.toUpperCase());
            setTimeout(() => { location.reload(); }, 500);
        }
    })
    .catch(e => {
        console.error('Currency change error:', e);
        alert('Error changing currency');
    });
}

// Toggle search bar
function toggleSearchBar() {
    const searchForm = document.getElementById('searchForm');
    if (searchForm) {
        if (searchForm.style.display === 'none' || !searchForm.style.display) {
            searchForm.style.display = 'flex';
            searchForm.querySelector('input').focus();
        } else {
            searchForm.style.display = 'none';
        }
    }
}

// Close search when clicking outside
document.addEventListener('click', function(event) {
    const searchContainer = event.target.closest('.search-container');
    if (!searchContainer) {
        const searchForm = document.getElementById('searchForm');
        if (searchForm) {
            searchForm.style.display = 'none';
        }
    }
});

// Toggle user dropdown on click
function toggleUserDropdown(event) {
    event.stopPropagation();
    const userDropdown = document.getElementById('userDropdown');
    if (userDropdown) {
        if (userDropdown.style.display === 'none' || !userDropdown.style.display) {
            userDropdown.style.display = 'block';
        } else {
            userDropdown.style.display = 'none';
        }
    }
}

// Close user dropdown when clicking outside
document.addEventListener('click', function(event) {
    const navUser = document.getElementById('navUser');
    if (navUser && !event.target.closest('.nav-user')) {
        const userDropdown = document.getElementById('userDropdown');
        if (userDropdown) {
            userDropdown.style.display = 'none';
        }
    }
});

// Login modal function
function openLoginModal() {
    // Find modal or create simple alert
    const loginModal = document.getElementById('loginModal');
    if (loginModal) {
        loginModal.style.display = 'block';
    } else {
        // Redirect to login page if no modal
        window.location.href = 'api_login.php';
    }
}
</script>

<!-- Image Loader - Handles automatic image path resolution -->
<script src="js/image_loader.js"></script>

<!-- Translation scripts removed - using clean server-side language switching -->