<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/config/image_config.php';
require_once __DIR__ . '/qrcode_generator.php';

// Currency preference and conversion setup
$selectedCurrency = $_SESSION['selected_currency'] ?? 'eur';

// Keep in sync with api_set_preference.php
$exchangeRates = [
    'eur' => 1.0,
    'usd' => 1.10,
    'gbp' => 0.87,
    'cad' => 1.48,
];

$currencySymbols = [
    'eur' => '€',
    'usd' => '$',
    'gbp' => '£',
    'cad' => 'C$',
];

$currencyRate = $exchangeRates[$selectedCurrency] ?? 1.0;
$currencySymbol = $currencySymbols[$selectedCurrency] ?? '€';

// Load Phase 3 helpers early
require_once __DIR__ . '/helpers/keyword_optimizer.php';
require_once __DIR__ . '/helpers/faq_helper.php';
require_once __DIR__ . '/helpers/content_optimizer.php';
require_once __DIR__ . '/helpers/schema_helper.php';

// Load products
$dataFile = __DIR__ . '/data/products.json';
$productsList = [];
if (file_exists($dataFile)) {
    $productsList = json_decode(file_get_contents($dataFile), true) ?: [];
}

$products = [];
foreach ($productsList as $pr) { $products[$pr['id']] = $pr; }

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$metaTags = 'fashion, women, clothing';
if ($id && isset($products[$id])) {
    $metaTags = !empty($products[$id]['tags']) ? htmlspecialchars($products[$id]['tags']) : 'fashion, ' . strtolower($products[$id]['cat'] ?? 'clothing');
}

// Get category name for breadcrumb
$categoryName = 'Shop';
if ($id && isset($products[$id]) && !empty($products[$id]['cat'])) {
    $catFile = __DIR__ . '/data/categories.json';
    if (file_exists($catFile)) {
        $categories = json_decode(file_get_contents($catFile), true) ?: [];
        foreach ($categories as $cat) {
            if ($cat['id'] == $products[$id]['cat']) {
                $categoryName = $cat['name'];
                break;
            }
        }
    }
}

// Get related products (same category, exclude current)
$relatedProducts = [];
if ($id && isset($products[$id])) {
    $currentCat = $products[$id]['cat'] ?? null;
    foreach ($productsList as $prod) {
        if ($prod['id'] != $id && (!empty($currentCat) && ($prod['cat'] ?? null) == $currentCat)) {
            $relatedProducts[] = $prod;
            if (count($relatedProducts) >= 5) break;
        }
    }
    // If not enough in same category, add random products
    if (count($relatedProducts) < 5) {
        foreach ($productsList as $prod) {
            if ($prod['id'] != $id && !in_array($prod['id'], array_column($relatedProducts, 'id'))) {
                $relatedProducts[] = $prod;
                if (count($relatedProducts) >= 5) break;
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
  <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">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  
  <!-- Phase 2: SEO Meta Tags for Product Pages -->
  <?php
  if (isset($products[$id])) {
      $product = $products[$id];
      $title = htmlspecialchars($product['title'] . ' - Shop Online | Esa\'s Fashion');
      $description = htmlspecialchars(substr($product['desc'] ?? 'Shop this fashion item', 0, 160));
      $keywords = htmlspecialchars(($product['cat'] ?? 'fashion') . ', ' . ($product['title'] ?? '') . ', buy online');
      
      echo "<title>{$title}</title>\n";
      echo "<meta name=\"description\" content=\"{$description}\">\n";
      echo "<meta name=\"keywords\" content=\"{$keywords}\">\n";
      echo "<link rel=\"canonical\" href=\"https://{$_SERVER['HTTP_HOST']}/product.php?id={$id}\">\n";
  } else {
      echo "<title>Product - Esa\'s Fashion | Shop</title>\n";
      echo "<meta name=\"description\" content=\"Shop our fashion collection\">\n";
  }
  ?>
  
  <!-- Open Graph Tags -->
  <?php
  if (isset($products[$id])) {
      $product = $products[$id];
      $imageUrl = !empty($product['image']) ? getImageForSection($product['image'], 'product_page') : 'pics_ecom/placeholder.png';
  ?>
  <meta property="og:title" content="<?php echo htmlspecialchars($product['title']); ?> - Esa's Fashion">
  <meta property="og:description" content="<?php echo htmlspecialchars(substr($product['desc'] ?? '', 0, 160)); ?>">
  <meta property="og:type" content="product">
  <meta property="og:url" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/product.php?id=<?php echo $id; ?>">
  <meta property="og:image" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/<?php echo $imageUrl; ?>">
  <meta property="og:price:amount" content="<?php echo htmlspecialchars($product['price'] ?? '0'); ?>">
  <meta property="og:price:currency" content="USD">
  
  <!-- Twitter Card -->
  <meta name="twitter:card" content="product">
  <meta name="twitter:title" content="<?php echo htmlspecialchars($product['title']); ?>">
  <meta name="twitter:description" content="<?php echo htmlspecialchars(substr($product['desc'] ?? '', 0, 160)); ?>">
  <meta name="twitter:image" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/<?php echo $imageUrl; ?>">
  <?php } ?>
  
  <!-- Robots Meta -->
  <meta name="robots" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
  
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="css/responsive-system.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    .product-page-wrapper {
      max-width: 1320px;
      margin: 0 auto;
      padding: 0 20px;
    }
    
    .breadcrumb {
      margin: 20px 0 40px;
      font-size: 14px;
      list-style: none;
      padding: 0;
    }
    
    .breadcrumb a {
      color: #666;
      text-decoration: none;
      transition: color 0.3s;
    }
    
    .breadcrumb a:hover {
      color: #F07E2D;
    }
    
    .breadcrumb span {
      color: #999;
      margin: 0 8px;
    }
    
    .product-detail-container {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 60px;
      margin-bottom: 80px;
    }
    
    .product-gallery-section {
      position: relative;
      margin-left: 100px;
    }
    
    .main-image-wrapper {
      position: relative;
      width: 90%;
      aspect-ratio: 1/1;
      margin-bottom: 0;
      border-radius: 8px;
      overflow: hidden;
      background: #f5f5f5;
    }
    
    .main-image-wrapper img {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
      cursor: zoom-in;
      transition: transform 0.3s ease;
    }
    
    .main-image-wrapper video {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 8px;
    }
    
    .gallery-thumbnails {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
      margin-top: 8px;
    }
    
    .gallery-thumbnail {
      width: 80px;
      height: 80px;
      border-radius: 6px;
      overflow: hidden;
      cursor: pointer;
      border: 2px solid #ddd;
      transition: all 0.3s ease;
      background: #f5f5f5;
    }
    
    .gallery-thumbnail.active {
      border-color: #F07E2D;
    }
    
    .gallery-thumbnail img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .product-info-section h1 {
      font-size: 32px;
      font-weight: 700;
      color: #333;
      margin-bottom: 20px;
      line-height: 1.3;
    }
    
    .product-rating {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 20px;
    }
    
    .star-rating {
      display: flex;
      gap: 4px;
      color: #ffc107;
    }
    
    .product-price {
      font-size: 28px;
      font-weight: 700;
      color: #F07E2D;
      margin-bottom: 20px;
    }
    
    .product-price .sale-price {
      color: #F07E2D;
    }
    
    .product-price .regular-price {
      text-decoration: line-through;
      color: #999;
      font-size: 20px;
      margin-left: 12px;
      font-weight: 400;
    }
    
    .color-swatches-section {
      margin-bottom: 20px;
    }
    
    .color-swatches-section label {
      font-weight: 600;
      display: block;
      margin-bottom: 12px;
      color: #333;
    }
    
    .color-swatches-container {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
    }
    
    .color-swatch {
      width: 35px;
      height: 35px;
      border-radius: 50%;
      border: 3px solid #ddd;
      cursor: pointer;
      transition: all 0.3s;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .color-swatch:hover {
      transform: scale(1.1);
      border-color: #F07E2D;
    }
    
    .color-swatch.active {
      border-color: #F07E2D;
      box-shadow: 0 0 0 2px #fff, 0 0 0 4px #F07E2D;
    }
    
    .color-swatch-tooltip {
      position: absolute;
      bottom: -30px;
      left: 50%;
      transform: translateX(-50%);
      background: #333;
      color: #fff;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      white-space: nowrap;
      opacity: 0;
      pointer-events: none;
      transition: opacity 0.3s;
      z-index: 10;
    }
    
    .color-swatch:hover .color-swatch-tooltip {
      opacity: 1;
    }
    
    .size-variants-section {
      margin-bottom: 20px;
    }
    
    .size-variants-section label {
      font-weight: 600;
      display: block;
      margin-bottom: 12px;
      color: #333;
    }
    
    .size-variant-option {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      border: 2px solid #ddd;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s;
      margin-bottom: 8px;
    }
    
    .size-variant-option:hover {
      border-color: #F07E2D;
      background: #fff5f8;
    }
    
    .size-variant-option input[type="radio"] {
      cursor: pointer;
    }
    
    .size-variant-option.selected {
      border-color: #F07E2D;
      background: #fff5f8;
    }
    
    .size-variant-image {
      width: 40px;
      height: 40px;
      border-radius: 4px;
      object-fit: cover;
      border: 1px solid #ddd;
    }
    
    .size-variant-info {
      flex: 1;
    }
    
    .size-variant-info strong {
      display: block;
      color: #333;
      margin-bottom: 2px;
    }
    
    .size-variant-price {
      color: #F07E2D;
      font-weight: 700;
      font-size: 16px;
    }
    
    .qr-code-section {
      background: #f9f9f9;
      padding: 16px;
      border-radius: 8px;
      text-align: center;
      margin-bottom: 20px;
      place-items: center;
    }
    
    .qr-code-section h4 {
      font-size: 12px;
      font-weight: 600;
      color: #666;
      margin: 0 0 12px 0;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    
    .qr-code-section img {
      max-width: 150px;
      height: auto;
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 4px;
      background: #fff;
    }
    
    .product-description {
      color: #666;
      line-height: 1.8;
      margin-bottom: 30px;
      font-size: 15px;
    }
    
    .product-actions-wrapper {
      margin-bottom: 30px;
    }
    
    .quantity-selector {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 20px;
    }
    
    .quantity-label {
      font-weight: 600;
      color: #333;
      min-width: 60px;
    }
    
    .quantity-controls {
      display: flex;
      align-items: center;
      border: 1px solid #ddd;
      border-radius: 6px;
      overflow: hidden;
    }
    
    .quantity-btn {
      width: 40px;
      height: 40px;
      border: none;
      background: #f5f5f5;
      cursor: pointer;
      font-size: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: background 0.3s;
    }
    
    .quantity-btn:hover {
      background: #e9e9e9;
    }
    
    .quantity-input {
      width: 60px;
      height: 40px;
      border: none;
      text-align: center;
      font-size: 16px;
      font-weight: 600;
    }
    
    .action-buttons {
      display: flex;
      gap: 12px;
      margin-bottom: 20px;
    }
    
    .btn-add-cart {
      flex: 1;
      background: #F07E2D;
      color: #fff;
      border: none;
      padding: 14px 30px;
      border-radius: 6px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s;
    }
    
    .btn-add-cart:hover {
      background: #d16a95;
      transform: translateY(-2px);
    }
    
    .btn-buy-now {
      background: #333;
      color: #fff;
      border: none;
      padding: 14px 30px;
      border-radius: 6px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      text-decoration: none;
      display: inline-block;
      transition: all 0.3s;
    }
    
    .btn-buy-now:hover {
      background: #222;
      transform: translateY(-2px);
    }
    
    .product-meta-actions {
      display: flex;
      gap: 20px;
      margin-bottom: 30px;
      padding-bottom: 30px;
      border-bottom: 1px solid #eee;
    }
    
    .meta-action-link {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #666;
      text-decoration: none;
      font-size: 14px;
      transition: color 0.3s;
    }
    
    .meta-action-link:hover {
      color: #F07E2D;
    }
    
    .shipping-info {
      background: #f9f9f9;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 30px;
    }
    
    .shipping-info h4 {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 16px;
      color: #333;
    }
    
    .shipping-item {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 12px;
    }
    
    .shipping-item:last-child {
      margin-bottom: 0;
    }
    
    .shipping-item strong {
      color: #333;
      font-weight: 600;
    }
    
    .share-section {
      margin-bottom: 40px;
    }
    
    .share-section label {
      font-weight: 600;
      color: #333;
      margin-right: 12px;
    }
    
    .share-buttons {
      display: flex;
      gap: 12px;
      margin-top: 12px;
    }
    
    .share-btn {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      border: 1px solid #ddd;
      background: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #666;
      text-decoration: none;
      transition: all 0.3s;
    }
    
    .share-btn:hover {
      background: #F07E2D;
      color: #fff;
      border-color: #F07E2D;
    }
    
    .product-tabs {
      margin-bottom: 60px;
    }
    
    .tab-buttons {
      display: flex;
      gap: 0;
      border-bottom: 2px solid #eee;
      margin-bottom: 30px;
    }
    
    .tab-button {
      padding: 14px 24px;
      background: none;
      border: none;
      font-size: 16px;
      font-weight: 600;
      color: #666;
      cursor: pointer;
      border-bottom: 2px solid transparent;
      margin-bottom: -2px;
      transition: all 0.3s;
    }
    
    .tab-button.active {
      color: #F07E2D;
      border-bottom-color: #F07E2D;
    }
    
    .tab-content {
      display: none;
    }
    
    .tab-content.active {
      display: block;
    }
    
    .tab-content h6 {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 12px;
    }
    
    .tab-content ul {
      list-style: none;
      padding: 0;
      margin: 0 0 20px 0;
    }
    
    .tab-content li {
      padding: 8px 0;
      color: #666;
      border-bottom: 1px solid #f0f0f0;
    }
    
    .tab-content p {
      color: #666;
      line-height: 1.8;
      margin-bottom: 16px;
    }
    
    .related-products-section {
      margin-bottom: 60px;
    }
    
    .section-title {
      font-size: 28px;
      font-weight: 700;
      color: #333;
      margin-bottom: 40px;
      text-align: center;
    }
    
    .related-products-carousel {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 30px;
    }
    
    .why-emall-section {
      margin-bottom: 80px;
    }
    
    .info-cards-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 40px;
    }
    
    .info-card-item {
      display: flex;
      gap: 20px;
      align-items: flex-start;
    }
    
    .info-card-icon {
      font-size: 48px;
      flex-shrink: 0;
    }
    
    .info-card-content h3 {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
    }
    
    .info-card-content p {
      color: #666;
      font-size: 14px;
      margin: 0;
      line-height: 1.6;
    }
    
    @media (max-width: 968px) {
      .product-detail-container {
        grid-template-columns: 1fr;
        gap: 40px;
      }
      
      .related-products-carousel {
        grid-template-columns: repeat(2, 1fr);
      }
      
      .info-cards-grid {
        grid-template-columns: 1fr;
      }
    }
    
    @media (max-width: 640px) {
      .related-products-carousel {
        grid-template-columns: 1fr;
      }
      
      .action-buttons {
        flex-direction: column;
      }
      
      .tab-buttons {
        flex-wrap: wrap;
      }
      
      .product-info-section h1 {
        font-size: 24px;
      }
      
      .product-price {
        font-size: 24px;
      }
      
      .gallery-thumbnails {
        justify-content: center;
      }
      
      .main-image-wrapper {
        aspect-ratio: 1/1;
      }
    }
  </style>
</head>
<body>
<?php include __DIR__ . '/header.php'; ?>

<div class="product-page-wrapper">
  <?php
  $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
  if(!$id || !isset($products[$id])){
    echo '<div style="text-align:center; padding:60px 20px;"><h2>Product not found</h2><p class="muted">Try browsing the <a href="shop.php">shop</a>.</p></div>';
  } else {
    $p = $products[$id];
    $gallery = !empty($p['gallery']) && is_array($p['gallery']) ? $p['gallery'] : [];
    $mainImage = !empty($p['image']) ? getImageForSection($p['image'], 'product') : 'pics_ecom/placeholder.png';
    $allImages = array_merge([$mainImage], $gallery);
    $rating = isset($p['rating']) ? (float)$p['rating'] : 4.5;
    $salePrice = isset($p['sale_price']) ? (float)$p['sale_price'] : null;
    $regularPrice = (float)$p['price'];

    // Convert base prices using selected currency
    $convertedRegularPrice = $regularPrice * $currencyRate;
    $convertedSalePrice = $salePrice !== null ? $salePrice * $currencyRate : null;
    $sizeVariants = !empty($p['size_variants']) && is_array($p['size_variants']) ? $p['size_variants'] : [];
    $colors = !empty($p['colors']) && is_array($p['colors']) ? $p['colors'] : [];
    // Legacy support for old sizes - convert to size_variants format
    $displaySizes = [];
    if (!empty($sizeVariants)) {
        $displaySizes = array_column($sizeVariants, 'name');
    } elseif (!empty($p['sizes']) && is_array($p['sizes'])) {
        // Convert old sizes to variant format on-the-fly
        foreach ($p['sizes'] as $size) {
            $sizeVariants[] = ['name' => $size, 'price' => $regularPrice, 'image' => $mainImage];
        }
        $displaySizes = $p['sizes'];
    } elseif (!empty($p['size'])) {
        $displaySizes = [$p['size']];
        $sizeVariants = [['name' => $p['size'], 'price' => $regularPrice, 'image' => $mainImage]];
    }
    
    // Convert colors data to include image switching info
    $colorImageMap = [];
    if (!empty($colors)) {
        foreach ($colors as $idx => $color) {
            if (!empty($color['image'])) {
                $colorImageMap[$idx] = $color['image'];
            }
        }
    }
    ?>
    
    <!-- Breadcrumb with Schema Markup -->
    <?php
    // Build breadcrumb array for schema
    $breadcrumbs = [
      ['title' => 'Home', 'url' => 'index.php'],
      ['title' => 'Shop', 'url' => 'shop.php'],
      ['title' => htmlspecialchars($categoryName), 'url' => 'shop.php?category=' . htmlspecialchars($p['cat'] ?? '')],
      ['title' => htmlspecialchars($p['title']), 'url' => null]
    ];
    
    // Output breadcrumb HTML
    if (class_exists('InternalLinkingHelper')) {
      echo InternalLinkingHelper::generateBreadcrumb($breadcrumbs);
      // Output breadcrumb schema
      echo InternalLinkingHelper::generateBreadcrumbSchema($breadcrumbs);
    }
    ?>
    
    <!-- Product Detail -->
    <div class="product-detail-container">
      <!-- Gallery Section -->
      <div class="product-gallery-section">
        <div class="main-image-wrapper" id="mainMediaWrapper">
          <img id="mainProductImage" src="<?php echo htmlspecialchars($mainImage); ?>" alt="<?php echo htmlspecialchars($p['title']); ?>">
        </div>
        
        <?php 
        // Prepare thumbnails including video if available
        $thumbnailMedia = [];
        $thumbnailMedia[] = ['type' => 'image', 'src' => $mainImage, 'alt' => 'Main Image'];
        
        if (!empty($gallery) && is_array($gallery)) {
            foreach ($gallery as $img) {
                $thumbnailMedia[] = ['type' => 'image', 'src' => $img, 'alt' => 'Gallery Image'];
            }
        }
        
        // Add video to thumbnails if available
        if (!empty($p['video'])) {
            $thumbnailMedia[] = ['type' => 'video', 'src' => $p['video'], 'alt' => 'Product Video'];
        }
        ?>
        
        <?php if (!empty($thumbnailMedia)): ?>
        <div class="gallery-thumbnails">
          <?php foreach ($thumbnailMedia as $idx => $media): ?>
          <div class="gallery-thumbnail <?php echo $idx === 0 ? 'active' : ''; ?>" 
               onclick="switchMainMedia(<?php echo $idx; ?>, '<?php echo htmlspecialchars($media['src']); ?>', '<?php echo $media['type']; ?>', this)"
               style="<?php echo $media['type'] === 'video' ? 'position:relative;' : ''; ?>">
            <?php if ($media['type'] === 'image'): ?>
              <img src="<?php echo htmlspecialchars($media['src']); ?>" alt="<?php echo $media['alt']; ?>">
            <?php else: ?>
              <div style="width:100%; aspect-ratio:1; background:#000; display:flex; align-items:center; justify-content:center; border-radius:6px;">
                <i class="fas fa-play" style="color:#fff; font-size:24px;"></i>
              </div>
            <?php endif; ?>
          </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>
      </div>
      
      <!-- Product Info Section -->
      <div class="product-info-section">
        <div class="product-rating">
          <div class="star-rating">
            <?php 
            $fullStars = floor($rating);
            $hasHalfStar = ($rating - $fullStars) >= 0.5;
            for ($i = 0; $i < 5; $i++): 
              if ($i < $fullStars):
            ?>
              <i class="fas fa-star"></i>
            <?php elseif ($i == $fullStars && $hasHalfStar): ?>
              <i class="fas fa-star-half-alt"></i>
            <?php else: ?>
              <i class="far fa-star"></i>
            <?php endif; endfor; ?>
          </div>
          <span style="color:#666; font-size:14px;">(<?php echo rand(2, 50); ?>)</span>
        </div>
        
        <h1><?php echo htmlspecialchars($p['title']); ?></h1>
        
        <div class="product-price" id="priceDisplay">
          <?php 
          // For size variants, show the first variant price, or base price if no variants
          if (!empty($sizeVariants)) {
            $displayPrice = (float)$sizeVariants[0]['price'] * $currencyRate;
            echo '<span class="sale-price">' . $currencySymbol . number_format($displayPrice, 2, '.', '') . '</span>';
            if (count($sizeVariants) > 1) {
              echo '<span style="color:#999; font-size:14px; margin-left:12px;">(varies by size)</span>';
            }
          } else {
            if ($convertedSalePrice !== null && $convertedSalePrice < $convertedRegularPrice) {
              echo '<span class="sale-price">' . $currencySymbol . number_format($convertedSalePrice, 2, '.', '') . '</span>';
              echo '<span class="regular-price">' . $currencySymbol . number_format($convertedRegularPrice, 2, '.', '') . '</span>';
            } else {
              echo '<span class="sale-price">' . $currencySymbol . number_format($convertedRegularPrice, 2, '.', '') . '</span>';
            }
          }
          ?>
        </div>
        
        <!-- Phase 3: Keyword-Optimized Product Description -->
        <div class="product-description">
          <?php
            // Optimize description with Phase 3 keyword helper
            if (class_exists('KeywordOptimizer')) {
              $optimizedDescription = KeywordOptimizer::optimizeDescription(
                htmlspecialchars($p['desc'] ?? 'Premium quality product with excellent craftsmanship.'),
                $p['cat'] ?? 'products',
                160
              );
              echo $optimizedDescription;
              
              // Get keyword recommendations for this product
              $keywords = KeywordOptimizer::getKeywords($p['cat'] ?? 'products');
              $keywordDensity = KeywordOptimizer::calculateKeywordDensity(
                htmlspecialchars($p['desc'] ?? 'Premium quality product'),
                $keywords['primary'] ?? 'product'
              );
            } else {
              echo htmlspecialchars($p['desc'] ?? 'Premium quality product with excellent craftsmanship.');
            }
          ?>
        </div>
        
        <div style="background:#f0f7ff; padding:12px; border-radius:6px; margin-bottom:20px; display:flex; align-items:center; gap:8px; color:#666; font-size:14px;">
          <i class="fas fa-users"></i>
          <span><?php echo rand(1, 10); ?> people are viewing this right now</span>
        </div>
        
        <div class="product-actions-wrapper">
          <!-- Color Swatches -->
          <?php if (!empty($colors)): ?>
          <div class="color-swatches-section">
            <label>Color:</label>
            <div class="color-swatches-container" id="colorSwatchesContainer">
              <?php foreach ($colors as $idx => $color): ?>
              <div class="color-swatch <?php echo $idx === 0 ? 'active' : ''; ?>" 
                   style="background-color: <?php echo htmlspecialchars($color['code'] ?? '#cccccc'); ?>;"
                   onclick="selectColor(<?php echo $idx; ?>, event)"
                   data-color-image="<?php echo htmlspecialchars($color['image'] ?? ''); ?>"
                   title="<?php echo htmlspecialchars($color['name']); ?>">
                <span class="color-swatch-tooltip"><?php echo htmlspecialchars($color['name']); ?></span>
              </div>
              <?php endforeach; ?>
            </div>
          </div>
          <?php endif; ?>
          
          <!-- Size Variants or Simple Size Selection -->
          <?php if (!empty($sizeVariants)): ?>
          <div class="size-variants-section">
            <label>Size:</label>
            <select id="sizeVariantSelect" onchange="selectSizeVariant()" style="padding:10px; border:1px solid #ddd; border-radius:6px; width:100%; font-size:15px;">
              <option value="">Select Size</option>
              <?php foreach ($sizeVariants as $idx => $variant): ?>
              <option value="<?php echo $idx; ?>" data-size-image="<?php echo htmlspecialchars($variant['image'] ?? ''); ?>" data-size-price="<?php echo htmlspecialchars($variant['price']); ?>"><?php echo htmlspecialchars($variant['name']); ?> - $<?php echo number_format($variant['price'], 2, '.', ''); ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <?php endif; ?>
          
          <!-- QR Code with SR NO -->
          <div class="qr-code-section">
            <h4>Product Code</h4>
            <?php 
            $srNo = !empty($p['sr_no']) ? $p['sr_no'] : null;
            $qrCodeUrl = getProductQRCode($p['id'], $srNo);
            ?>
            <!-- <img src="<?php echo htmlspecialchars($qrCodeUrl); ?>" alt="Product QR Code" title="Scan to view product" style="max-width:150px; align-item:center; display:block; margin:8px 0;"> -->
            <?php if (!empty($srNo)): ?>
              <p style="font-size:12px; color:#333; margin:8px 0; font-weight:600;">SR NO: <strong style="color:#F07E2D;"><?php echo formatProductSRNo($srNo); ?></strong></p>
            <?php endif; ?>
            <p style="font-size:11px; color:#999; margin:8px 0 0 0;">Scan QR code to view product</p>
          </div>
          
          <div class="quantity-selector">
            <span class="quantity-label">QTY</span>
            <div class="quantity-controls">
              <button class="quantity-btn" onclick="decreaseQuantity()">-</button>
              <input type="number" id="productQuantity" class="quantity-input" value="1" min="1" readonly>
              <button class="quantity-btn" onclick="increaseQuantity()">+</button>
            </div>
          </div>
          
          <div class="action-buttons">
            <button class="btn-add-cart" onclick="addToCart()">
              <i class="fas fa-shopping-cart" style="margin-right:8px;"></i> Add to cart
            </button>
            <a href="cart.php" class="btn-buy-now">Buy it now</a>
          </div>
        </div>
        
        <div class="product-meta-actions">
          <a href="#" class="meta-action-link" onclick="toggleWishlist(<?php echo $p['id']; ?>, event); return false;">
            <i class="far fa-heart"></i> Add to wishlist
          </a>
          <a href="#" class="meta-action-link">
            <i class="fas fa-balance-scale"></i> Compare
          </a>
          <a href="contact.php" class="meta-action-link">
            <i class="fas fa-question-circle"></i> Ask a question
          </a>
        </div>
        
        <div class="shipping-info">
          <h4>Guarantee Safe & Secure Checkout</h4>
          <div class="shipping-item">
            <i class="fas fa-truck" style="color:#F07E2D;"></i>
            <div>
              <strong>Estimated Delivery:</strong> <?php echo date('M d', strtotime('+3 days')); ?> - <?php echo date('M d', strtotime('+7 days')); ?>
            </div>
          </div>
          <div class="shipping-item">
            <i class="fas fa-shipping-fast" style="color:#F07E2D;"></i>
            <div>
              <strong>Free Shipping & Return:</strong> On all orders over $199
            </div>
          </div>
        </div>
        
        <div class="share-section">
          <label>Share:</label>
          <div class="share-buttons">
            <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>" target="_blank" class="share-btn">
              <i class="fab fa-facebook-f"></i>
            </a>
            <a href="https://twitter.com/intent/tweet?url=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>" target="_blank" class="share-btn">
              <i class="fab fa-twitter"></i>
            </a>
            <a href="http://linkedin.com/shareArticle?mini=true&url=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>" target="_blank" class="share-btn">
              <i class="fab fa-linkedin-in"></i>
            </a>
            <a href="https://pinterest.com/pin/create/button/?url=<?php echo urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); ?>&media=<?php echo urlencode($mainImage); ?>" target="_blank" class="share-btn">
              <i class="fab fa-pinterest"></i>
            </a>
          </div>
        </div>
        
        <!-- Phase 2: Product Schema Markup (JSON-LD) -->
        <?php
        // Output structured product schema
        $productSchema = SchemaHelper::generateProductSchema([
          'id' => $p['id'],
          'title' => $p['title'],
          'desc' => $p['desc'] ?? 'Premium fashion item',
          'price' => $p['price'],
          'sale_price' => $salePrice,
          'image' => $mainImage,
          'rating' => $rating,
          'cat' => $p['cat'] ?? 'Fashion',
          'colors' => $colors
        ]);
        echo SchemaHelper::outputSchema($productSchema);
        ?>
      </div>
    </div>
    
    <!-- Product Tabs -->
    <div class="product-tabs">
      <div class="tab-buttons">
        <button class="tab-button active" onclick="switchTab('description')">Description</button>
        <button class="tab-button" onclick="switchTab('size-guide')">Size guide</button>
        <button class="tab-button" onclick="switchTab('reviews')">Reviews (<?php echo rand(2, 50); ?>)</button>
        <button class="tab-button" onclick="switchTab('faq')">FAQ</button>
      </div>
      
      <div id="tab-description" class="tab-content active">
        <div style="display:grid; grid-template-columns: 1fr 1fr; gap:40px;">
          <div>
            <h6>Information</h6>
            <ul>
              <li>Premium quality materials</li>
              <li>Expert craftsmanship</li>
              <li>Comfortable fit</li>
              <li>Durable construction</li>
            </ul>
            
            <h6>Base Fabric</h6>
            <ul>
              <li>100% High Quality Material</li>
            </ul>
            
            <h6>Wearing</h6>
            <ul>
              <li>Model is 1.8m wearing</li>
              <li>Size M</li>
            </ul>
          </div>
          <div>
            <h6>Care</h6>
            <p>Machine wash cold with like colors. Do not bleach. Tumble dry low. Iron on low heat if needed.</p>
          </div>
        </div>
        
        <!-- Phase 3: Content Optimization & Keyword Enhancement -->
        <?php
          $baseDescription = htmlspecialchars($p['desc'] ?? 'This premium product features exceptional quality and attention to detail. Designed for comfort and style, it combines modern aesthetics with timeless appeal.');
          
          $contentScore = ['score' => 0];
          $expandedDesc = $baseDescription;
          $readability = ['level' => 'N/A', 'score' => 0, 'recommendations' => ''];
          
          if (class_exists('KeywordOptimizer') && class_exists('ContentOptimizer')) {
            // Get content quality score and recommendations
            $contentScore = KeywordOptimizer::getContentQualityScore(
              $p['title'] ?? 'Product',
              $baseDescription,
              $baseDescription,
              $p['cat'] ?? 'products'
            );
            
            // Expand product description with Phase 3 helper
            $expandedDesc = ContentOptimizer::expandProductDescription(
              $baseDescription,
              $p['cat'] ?? 'products',
              ['Premium quality', 'Expert craftsmanship', 'Durable construction', 'Comfortable fit']
            );
            
            // Calculate readability score
            $readability = ContentOptimizer::calculateReadability($expandedDesc);
          }
        ?>
        
        <p style="margin-top:20px; color:#666; line-height:1.8;">
          <?php echo $expandedDesc; ?>
        </p>
        
        <!-- Content Quality Indicator -->
        <?php if ($contentScore['score'] > 0): ?>
        <div style="margin-top:30px; padding:20px; background:#f0f8ff; border-left:4px solid #2196F3; border-radius:4px;">
          <p style="margin:0 0 10px 0;"><strong>Content Quality Score:</strong> <span style="color:#2196F3; font-weight:bold;"><?php echo $contentScore['score']; ?>/100</span></p>
          <p style="margin:0 0 10px 0; font-size:14px; color:#555;">Readability Level: <strong><?php echo $readability['level']; ?></strong> (Flesch Score: <?php echo number_format($readability['score'], 1); ?>/100)</p>
          <?php if (!empty($readability['recommendations'])): ?>
          <p style="margin:0; font-size:13px; color:#666; line-height:1.6;"><?php echo htmlspecialchars($readability['recommendations']); ?></p>
          <?php endif; ?>
        </div>
        <?php endif; ?>
      </div>
      
      <div id="tab-size-guide" class="tab-content">
        <h6>Size Guide</h6>
        <p>Please refer to our size guide to find the perfect fit. Measurements are in inches.</p>
        <table style="width:100%; border-collapse:collapse; margin-top:20px;">
          <thead>
            <tr style="background:#f5f5f5;">
              <th style="padding:12px; text-align:left; border:1px solid #ddd;">Size</th>
              <th style="padding:12px; text-align:left; border:1px solid #ddd;">Chest</th>
              <th style="padding:12px; text-align:left; border:1px solid #ddd;">Length</th>
              <th style="padding:12px; text-align:left; border:1px solid #ddd;">Sleeve</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td style="padding:12px; border:1px solid #ddd;">S</td>
              <td style="padding:12px; border:1px solid #ddd;">36"</td>
              <td style="padding:12px; border:1px solid #ddd;">27"</td>
              <td style="padding:12px; border:1px solid #ddd;">24"</td>
            </tr>
            <tr>
              <td style="padding:12px; border:1px solid #ddd;">M</td>
              <td style="padding:12px; border:1px solid #ddd;">40"</td>
              <td style="padding:12px; border:1px solid #ddd;">28"</td>
              <td style="padding:12px; border:1px solid #ddd;">25"</td>
            </tr>
            <tr>
              <td style="padding:12px; border:1px solid #ddd;">L</td>
              <td style="padding:12px; border:1px solid #ddd;">44"</td>
              <td style="padding:12px; border:1px solid #ddd;">29"</td>
              <td style="padding:12px; border:1px solid #ddd;">26"</td>
            </tr>
            <tr>
              <td style="padding:12px; border:1px solid #ddd;">XL</td>
              <td style="padding:12px; border:1px solid #ddd;">48"</td>
              <td style="padding:12px; border:1px solid #ddd;">30"</td>
              <td style="padding:12px; border:1px solid #ddd;">27"</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div id="tab-reviews" class="tab-content">
        <h6>Customer Reviews</h6>
        <p>Read what our customers are saying about this product.</p>
        <div style="margin-top:30px;">
          <div style="padding:20px; background:#f9f9f9; border-radius:8px; margin-bottom:20px;">
            <div style="display:flex; align-items:center; gap:12px; margin-bottom:12px;">
              <strong style="color:#333;">John Doe</strong>
              <div class="star-rating">
                <i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i>
              </div>
              <span style="color:#999; font-size:14px;"><?php echo date('M d, Y', strtotime('-5 days')); ?></span>
            </div>
            <p style="color:#666; margin:0; line-height:1.6;">Great product! Excellent quality and fast shipping. Highly recommend!</p>
          </div>
          <div style="padding:20px; background:#f9f9f9; border-radius:8px;">
            <div style="display:flex; align-items:center; gap:12px; margin-bottom:12px;">
              <strong style="color:#333;">Jane Smith</strong>
              <div class="star-rating">
                <i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="fas fa-star"></i><i class="far fa-star"></i>
              </div>
              <span style="color:#999; font-size:14px;"><?php echo date('M d, Y', strtotime('-10 days')); ?></span>
            </div>
            <p style="color:#666; margin:0; line-height:1.6;">Very satisfied with my purchase. The product matches the description perfectly.</p>
          </div>
        </div>
      </div>
      
      <div id="tab-faq" class="tab-content">
        <h6>Frequently Asked Questions</h6>
        <?php
          if (class_exists('FAQHelper')) {
            // Get FAQ data with schema using Phase 3 helper
            $faqData = FAQHelper::getFAQsWithSchema($product['category'], 'product-faq-' . $product['id']);
            
            // Output FAQ schema for Google rich snippets
            echo $faqData['schema'];
            
            // Display FAQ accordion
            echo $faqData['accordion'];
          }
        ?>
      </div>
    </div>
    
    <!-- Phase 3: Internal Link Recommendations for SEO -->
    <?php
      $linkRecommendations = [];
      if (class_exists('KeywordOptimizer') && class_exists('ContentOptimizer')) {
        // Get internal link recommendations using Phase 3 helper
        $keywords = KeywordOptimizer::getKeywords($product['category'] ?? 'products');
        $linkRecommendations = ContentOptimizer::getInternalLinkRecommendations(
          'product.php?id=' . $product['id'],
          array_merge([$keywords['primary'] ?? ''], $keywords['variations'] ?? [])
        );
      }
      
      if (!empty($linkRecommendations)) {
    ?>
    <div style="margin:40px 0; padding:20px; background:#fafafa; border-radius:8px; border-left:4px solid #F07E2D;">
      <h3 style="margin-top:0; color:#333;">Related Content & Resources</h3>
      <p style="color:#666; margin-bottom:15px;">Enhance your shopping experience with these related items and information:</p>
      <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap:15px;">
        <?php foreach (array_slice($linkRecommendations, 0, 4) as $recommendation): ?>
        <a href="<?php echo htmlspecialchars($recommendation['url'] ?? '#'); ?>" style="display:block; padding:12px; background:#fff; border-radius:6px; border:1px solid #ddd; text-decoration:none; color:#F07E2D; transition:all 0.3s; hover:border-color: #F07E2D; hover:box-shadow: 0 2px 8px rgba(225,123,169,0.2);">
          <strong style="display:block; margin-bottom:6px;"><?php echo htmlspecialchars($recommendation['text'] ?? $recommendation['title'] ?? 'Related Item'); ?></strong>
          <span style="font-size:13px; color:#999;"><?php echo htmlspecialchars($recommendation['reason'] ?? $recommendation['desc'] ?? 'Shop related items'); ?></span>
        </a>
        <?php endforeach; ?>
      </div>
    </div>
    <?php } ?>
    
    <!-- Related Products -->
    <?php if (!empty($relatedProducts)): ?>
    <div class="related-products-section">
      <h2 class="section-title">You may also like…</h2>
      <div class="related-products-carousel">
        <?php foreach (array_slice($relatedProducts, 0, 5) as $related): ?>
        <div class="product-display-wrapper">
          <div class="featured-product-card product-card-with-actions">
            <div class="product-card-image-wrapper">
              <a href="product.php?id=<?php echo $related['id']; ?>" class="product-image-link">
                <img src="<?php echo htmlspecialchars(getImageForSection($related['image'] ?? 'pics_ecom/placeholder.png', 'shop')); ?>" alt="<?php echo htmlspecialchars($related['title']); ?>">
              </a>
              <div class="product-quick-actions">
                <button type="button" class="quick-action-btn wishlist" onclick="toggleWishlistQuick(<?php echo $related['id']; ?>, event)" title="Add to Wishlist"><i class="fa-regular fa-heart"></i></button>
                <button type="button" class="quick-action-btn cart" onclick="addToCartQuick(<?php echo $related['id']; ?>, event)" title="Add to Cart"><i class="fa-solid fa-basket-shopping"></i></button>
              </div>
              <?php if (isset($related['on_sale']) && $related['on_sale']): ?>
              <div style="position:absolute; top:10px; left:10px; background:#F07E2D; color:#fff; padding:4px 8px; border-radius:4px; font-size:12px; font-weight:600;">
                -<?php echo round((($related['price'] - ($related['sale_price'] ?? $related['price'])) / $related['price']) * 100); ?>%
              </div>
              <?php endif; ?>
            </div>
          </div>
          <div class="product-info-outside">
            <h3 style="margin:12px 0 6px 0; font-size:15px; font-weight:600; color:#333; line-height:1.4;">
              <a href="product.php?id=<?php echo $related['id']; ?>" style="color:inherit; text-decoration:none;"><?php echo htmlspecialchars($related['title']); ?></a>
            </h3>
            <?php 
            $relSalePrice = isset($related['sale_price']) ? (float)$related['sale_price'] : null;
            $relRegularPrice = (float)$related['price'];
            if ($relSalePrice !== null && $relSalePrice < $relRegularPrice) {
              echo '<p style="margin:0; font-size:16px; font-weight:700; color:#F07E2D;">$' . number_format($relSalePrice, 2, '.', '') . ' <span style="text-decoration:line-through; color:#999; font-size:14px; font-weight:400; margin-left:8px;">$' . number_format($relRegularPrice, 2, '.', '') . '</span></p>';
            } else {
              echo '<p style="margin:0; font-size:16px; font-weight:700; color:#F07E2D;">$' . number_format($relRegularPrice, 2, '.', '') . '</p>';
            }
            ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
    
    <!-- Why Emall Section -->
    <div class="why-emall-section">
      <h2 class="section-title">Why Emall?</h2>
      <div class="info-cards-grid">
        <div class="info-card-item">
          <div class="info-card-icon">🚚</div>
          <div class="info-card-content">
            <h3>Free Shipping & Return</h3>
            <p>Free shipping for all orders over $130</p>
          </div>
        </div>
        <div class="info-card-item">
          <div class="info-card-icon">📞</div>
          <div class="info-card-content">
            <h3>Customer Support 24/7</h3>
            <p>Instant access to perfect support everyday</p>
          </div>
        </div>
        <div class="info-card-item">
          <div class="info-card-icon">🔒</div>
          <div class="info-card-content">
            <h3>100% Secure Payment</h3>
            <p>We ensure secure payment for customers</p>
          </div>
        </div>
      </div>
    </div>
    
    <script>
    function switchMainImage(src, thumb) {
      document.getElementById('mainProductImage').src = src;
      document.querySelectorAll('.gallery-thumbnail').forEach(t => t.classList.remove('active'));
      if (thumb) thumb.classList.add('active');
    }
    
    function switchMainMedia(index, src, mediaType, thumb) {
      const wrapper = document.getElementById('mainMediaWrapper');
      
      if (mediaType === 'image') {
        wrapper.innerHTML = '<img id="mainProductImage" src="' + src + '" alt="Product Image">';
      } else if (mediaType === 'video') {
        wrapper.innerHTML = '<video id="mainProductVideo" style="width:100%; height:100%; object-fit:cover;" controls>' +
                           '<source src="' + src + '" type="video/mp4">' +
                           'Your browser does not support the video tag.' +
                           '</video>';
      }
      
      document.querySelectorAll('.gallery-thumbnail').forEach(t => t.classList.remove('active'));
      if (thumb) thumb.classList.add('active');
    }
    
    function increaseQuantity() {
      const input = document.getElementById('productQuantity');
      input.value = parseInt(input.value) + 1;
    }
    
    function decreaseQuantity() {
      const input = document.getElementById('productQuantity');
      if (parseInt(input.value) > 1) {
        input.value = parseInt(input.value) - 1;
      }
    }
    
    function switchTab(tabName) {
      document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
      document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
      event.target.classList.add('active');
      document.getElementById('tab-' + tabName).classList.add('active');
    }
    
    function addToCart() {
      const productId = <?php echo $p['id']; ?>;
      const quantity = parseInt(document.getElementById('productQuantity').value);
      
      // Get size from dropdown or hidden input
      const sizeSelectEl = document.getElementById('sizeVariantSelect');
      const sizeInputEl = document.getElementById('selectedSizeVariant');
      const sizeEl = document.getElementById('productSize');
      
      let size = '';
      if (sizeSelectEl && sizeSelectEl.value !== '') {
        size = sizeSelectEl.options[sizeSelectEl.selectedIndex].text.split(' - ')[0];
      } else if (sizeInputEl && sizeInputEl.value !== '') {
        size = sizeInputEl.value;
      } else if (sizeEl && sizeEl.value !== '') {
        size = sizeEl.value;
      }
      
      if (!size && (sizeSelectEl || sizeInputEl || sizeEl)) {
        alert('Please select a size before adding to cart');
        return;
      }
      
      const formData = new FormData();
      formData.append('action', 'add');
      formData.append('id', productId);
      formData.append('qty', quantity);
      if (size) formData.append('size', size);
      
      fetch('cart.php', {
        method: 'POST',
        body: formData
      })
      .then(response => {
        if (response.redirected) {
          window.location.href = 'cart.php';
        } else {
          alert('Product added to cart!');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        alert('Error adding product to cart');
      });
    }
    
    function selectColor(colorIdx, event) {
      event.preventDefault();
      const swatch = event.target.closest('.color-swatch');
      const colorImage = swatch.getAttribute('data-color-image');
      
      // Update active swatch
      document.querySelectorAll('.color-swatch').forEach(s => s.classList.remove('active'));
      swatch.classList.add('active');
      
      // Change main image if color has an image
      if (colorImage && colorImage.trim() !== '') {
        switchMainImage(colorImage, null);
        // Also update gallery thumbnails if this image is in gallery
        updateGalleryThumbnails(colorImage);
      }
    }
    
    function selectSizeVariant() {
      const sizeSelect = document.getElementById('sizeVariantSelect');
      if (!sizeSelect || sizeSelect.value === '') return;
      
      const selectedOption = sizeSelect.options[sizeSelect.selectedIndex];
      const sizeImage = selectedOption.getAttribute('data-size-image');
      const sizePrice = selectedOption.getAttribute('data-size-price');
      
      // Update price display
      if (sizePrice) {
        const priceDisplay = document.getElementById('priceDisplay');
        if (priceDisplay) {
          const priceSpan = priceDisplay.querySelector('.sale-price');
          if (priceSpan) {
            priceSpan.textContent = '$' + parseFloat(sizePrice).toFixed(2);
          }
        }
      }
      
      // Change main image if size has an image
      if (sizeImage && sizeImage.trim() !== '') {
        switchMainImage(sizeImage, null);
        updateGalleryThumbnails(sizeImage);
      }
    }
    
    function updateGalleryThumbnails(imageUrl) {
      // Update which thumbnail is highlighted to match main image
      const thumbnails = document.querySelectorAll('.gallery-thumbnail');
      thumbnails.forEach((thumb, idx) => {
        const thumbImg = thumb.querySelector('img');
        if (thumbImg && thumbImg.src.includes(imageUrl.split('/').pop())) {
          thumb.classList.add('active');
        }
      });
    }
    
    function selectSizeVariantLegacy(variantIdx, labelEl) {
      document.getElementById('selectedSizeVariant').value = variantIdx;
      document.querySelectorAll('.size-variant-option').forEach(opt => opt.classList.remove('selected'));
      labelEl.classList.add('selected');
      
      // Update price display for selected size
      const selectedPrice = labelEl.querySelector('.size-variant-price').textContent;
      const priceDisplay = document.getElementById('priceDisplay');
      if (priceDisplay) {
        const priceSpan = priceDisplay.querySelector('.sale-price');
        if (priceSpan) {
          priceSpan.textContent = selectedPrice;
        }
      }
    }
    
    function toggleWishlist(productId, event) {
      event.preventDefault();
      const formData = new FormData();
      formData.append('action', 'wishlist');
      formData.append('product_id', productId);
      
      fetch('wishlist_handler.php', {
        method: 'POST',
        body: formData
      })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          const link = event.target.closest('.meta-action-link');
          if (data.action === 'added') {
            link.innerHTML = '<i class="fas fa-heart" style="color:#F07E2D;"></i> Remove from wishlist';
          } else {
            link.innerHTML = '<i class="far fa-heart"></i> Add to wishlist';
          }
        }
      })
      .catch(error => console.error('Error:', error));
    }
    
    function toggleWishlistQuick(productId, event) {
      event.preventDefault();
      event.stopPropagation();
      const formData = new FormData();
      formData.append('action', 'wishlist');
      formData.append('product_id', productId);
      
      fetch('wishlist_handler.php', {
        method: 'POST',
        body: formData
      })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          const btn = event.target.closest('.quick-action-btn');
          if (data.action === 'added') {
            btn.classList.add('active');
            btn.innerHTML = '<i class="fa-solid fa-heart"></i>';
          } else {
            btn.classList.remove('active');
            btn.innerHTML = '<i class="fa-regular fa-heart"></i>';
          }
        }
      })
      .catch(error => console.error('Error:', error));
    }
    
    function addToCartQuick(productId, event) {
      event.preventDefault();
      event.stopPropagation();
      const formData = new FormData();
      formData.append('action', 'add');
      formData.append('id', productId);
      formData.append('qty', 1);
      
      fetch('cart.php', {
        method: 'POST',
        body: formData
      })
      .then(response => {
        alert('Product added to cart!');
      })
      .catch(error => {
        console.error('Error:', error);
        alert('Error adding product to cart');
      });
    }
    
    // Initialize size variants
    document.addEventListener('DOMContentLoaded', function() {
      const firstVariant = document.querySelector('.size-variant-option');
      if (firstVariant) {
        firstVariant.classList.add('selected');
      }
    });
    
    // Image zoom on hover
    const mainImage = document.getElementById('mainProductImage');
    const imageWrapper = mainImage.closest('.main-image-wrapper');
    
    if (mainImage && imageWrapper) {
      imageWrapper.addEventListener('mousemove', function(e) {
        const rect = imageWrapper.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        const xPercent = (x / rect.width) * 100;
        const yPercent = (y / rect.height) * 100;
        
        mainImage.style.transformOrigin = xPercent + '% ' + yPercent + '%';
        mainImage.style.transform = 'scale(2)';
      });
      
      imageWrapper.addEventListener('mouseleave', function() {
        mainImage.style.transform = 'scale(1)';
      });
    }
    </script>
    
    <?php
  }
  ?>
</div>

<?php include __DIR__ . '/footer.php'; ?>
</body>
</html>
