<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/config/image_config.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';

// Load all data files
$products = [];
$dataFile = __DIR__ . '/data/products.json';
if (file_exists($dataFile)) {
    $json = file_get_contents($dataFile);
    $decoded = json_decode($json, true);
    if ($decoded === null) {
        // Handle JSON decode error
        $products = [];
        error_log('JSON decode error in products.json: ' . json_last_error_msg());
    } else {
        $products = $decoded ?: [];
    }
} else {
    error_log('products.json file not found');
}

// Load categories
$categories = [];
$categoriesFile = __DIR__ . '/data/categories.json';
if (file_exists($categoriesFile)) {
    $cats = json_decode(file_get_contents($categoriesFile), true);
    if (is_array($cats)) {
        foreach ($cats as $cat) {
            $categories[] = $cat['name'];
        }
    }
}

// Load brands
$brands = [];
$brandsFile = __DIR__ . '/data/brands.json';
if (file_exists($brandsFile)) {
    $brandsData = json_decode(file_get_contents($brandsFile), true);
    if (is_array($brandsData)) {
        $brands = $brandsData;
    }
}

// Get filter parameters from URL
$selectedCategory = isset($_GET['cat']) ? $_GET['cat'] : '';
$selectedColors = isset($_GET['filter_color']) ? (is_array($_GET['filter_color']) ? $_GET['filter_color'] : [$_GET['filter_color']]) : [];
$selectedBrands = isset($_GET['brand']) ? (is_array($_GET['brand']) ? $_GET['brand'] : [$_GET['brand']]) : [];
$selectedTags = isset($_GET['tag']) ? (is_array($_GET['tag']) ? $_GET['tag'] : [$_GET['tag']]) : [];
$selectedSizes = isset($_GET['size']) ? (is_array($_GET['size']) ? $_GET['size'] : [$_GET['size']]) : [];
$minPrice = isset($_GET['min_price']) ? (float)$_GET['min_price'] : null;
$maxPrice = isset($_GET['max_price']) ? (float)$_GET['max_price'] : null;
$minRating = isset($_GET['rating']) ? (float)$_GET['rating'] : null;
$onSale = isset($_GET['on_sale']) && $_GET['on_sale'] == '1';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'latest';
// Ensure per_page and page are scalars
if (is_array($_GET['per_page'] ?? null)) {
    $_GET['per_page'] = is_array($_GET['per_page']) ? reset($_GET['per_page']) : null;
}
if (is_array($_GET['page'] ?? null)) {
    $_GET['page'] = is_array($_GET['page']) ? reset($_GET['page']) : null;
}
$perPage = isset($_GET['per_page']) ? max(1, (int)($_GET['per_page'] ?? 18)) : 18;
$page = isset($_GET['page']) ? max(1, (int)($_GET['page'] ?? 1)) : 1;
$searchQuery = isset($_GET['q']) ? strtolower(trim($_GET['q'])) : '';
$view = isset($_GET['view']) ? $_GET['view'] : 'grid-3';

// For color image display - store the first selected color to show its images
$displayColorName = !empty($selectedColors) ? strtolower($selectedColors[0]) : null;

// Filter products function
function filterProducts($products, $filters) {
    $filtered = $products;
    
    // Category filter
    if (!empty($filters['category'])) {
        $filtered = array_filter($filtered, function($p) use ($filters) {
            return strtolower($p['cat'] ?? '') === strtolower($filters['category']);
        });
    }
    
    // Color filter
    if (!empty($filters['colors'])) {
        $filtered = array_filter($filtered, function($p) use ($filters) {
            if (empty($p['colors']) || !is_array($p['colors'])) return false;
            foreach ($p['colors'] as $color) {
                if (in_array(strtolower($color['name'] ?? ''), array_map('strtolower', $filters['colors']))) {
                    return true;
                }
            }
            return false;
        });
    }
    
    // Brand filter
    if (!empty($filters['brands'])) {
        $filtered = array_filter($filtered, function($p) use ($filters) {
            $productBrand = strtolower($p['brand'] ?? '');
            foreach ($filters['brands'] as $brand) {
                if ($productBrand === strtolower($brand)) return true;
            }
            return false;
        });
    }
    
    // Tag filter
    if (!empty($filters['tags'])) {
        $filtered = array_filter($filtered, function($p) use ($filters) {
            $productTags = strtolower($p['tags'] ?? '');
            foreach ($filters['tags'] as $tag) {
                if (strpos($productTags, strtolower($tag)) !== false) return true;
            }
            return false;
        });
    }
    
    // Size filter
    if (!empty($filters['sizes'])) {
        $filtered = array_filter($filtered, function($p) use ($filters) {
            if (empty($p['sizes']) || !is_array($p['sizes'])) return false;
            foreach ($filters['sizes'] as $size) {
                if (in_array($size, $p['sizes'])) return true;
            }
            return false;
        });
    }
    
    // Price range filter
    if ($filters['min_price'] !== null || $filters['max_price'] !== null) {
        $filtered = array_filter($filtered, function($p) use ($filters) {
            $price = (float)($p['price'] ?? 0);
            $salePrice = isset($p['sale_price']) ? (float)$p['sale_price'] : null;
            $displayPrice = $salePrice !== null ? $salePrice : $price;
            
            if ($filters['min_price'] !== null && $displayPrice < $filters['min_price']) return false;
            if ($filters['max_price'] !== null && $displayPrice > $filters['max_price']) return false;
            return true;
        });
    }
    
    // Rating filter
    if ($filters['min_rating'] !== null) {
        $filtered = array_filter($filtered, function($p) use ($filters) {
            $rating = (float)($p['rating'] ?? 0);
            return $rating >= $filters['min_rating'];
        });
    }
    
    // Sale filter
    if ($filters['on_sale']) {
        $filtered = array_filter($filtered, function($p) {
            return !empty($p['on_sale']) || isset($p['sale_price']);
        });
    }
    
    // Search query filter
    if (!empty($filters['search'])) {
        $filtered = array_filter($filtered, function($p) use ($filters) {
            $title = strtolower($p['title'] ?? '');
            $desc = strtolower($p['desc'] ?? '');
            $search = strtolower($filters['search']);
            return strpos($title, $search) !== false || strpos($desc, $search) !== false;
        });
    }
    
    return array_values($filtered);
}

// Apply filters
$filters = [
    'category' => $selectedCategory,
    'colors' => $selectedColors,
    'brands' => $selectedBrands,
    'tags' => $selectedTags,
    'sizes' => $selectedSizes,
    'min_price' => $minPrice,
    'max_price' => $maxPrice,
    'min_rating' => $minRating,
    'on_sale' => $onSale,
    'search' => $searchQuery
];

$filteredProducts = filterProducts($products, $filters);

// Sort products
if ($sort === 'price-low') {
    usort($filteredProducts, function($a, $b) {
        $priceA = isset($a['sale_price']) ? (float)$a['sale_price'] : (float)($a['price'] ?? 0);
        $priceB = isset($b['sale_price']) ? (float)$b['sale_price'] : (float)($b['price'] ?? 0);
        return $priceA <=> $priceB;
    });
} elseif ($sort === 'price-high') {
    usort($filteredProducts, function($a, $b) {
        $priceA = isset($a['sale_price']) ? (float)$a['sale_price'] : (float)($a['price'] ?? 0);
        $priceB = isset($b['sale_price']) ? (float)$b['sale_price'] : (float)($b['price'] ?? 0);
        return $priceB <=> $priceA;
    });
} elseif ($sort === 'best-rated') {
    usort($filteredProducts, function($a, $b) {
        $ratingA = (float)($a['rating'] ?? 0);
        $ratingB = (float)($b['rating'] ?? 0);
        return $ratingB <=> $ratingA;
    });
} elseif ($sort === 'best-selling') {
    usort($filteredProducts, function($a, $b) {
        $salesA = (int)($a['sales_count'] ?? 0);
        $salesB = (int)($b['sales_count'] ?? 0);
        return $salesB <=> $salesA;
    });
} else {
    // Latest (default) - sort by ID descending
    usort($filteredProducts, function($a, $b) {
        return ($b['id'] ?? 0) <=> ($a['id'] ?? 0);
    });
}

// Pagination
$totalProducts = count($filteredProducts);
$totalPages = ceil($totalProducts / $perPage);
$offset = ($page - 1) * $perPage;
$paginatedProducts = array_slice($filteredProducts, $offset, $perPage);

// Calculate filter counts
function getCategoryCount($products, $category) {
    return count(array_filter($products, function($p) use ($category) {
        $productCat = strtolower($p['cat'] ?? '');
        if ($productCat === strtolower($category)) {
            return true;
        }
        // Fallback: check category_id if cat field doesn't exist
        if (empty($productCat) && isset($p['category_id'])) {
            // This would need category lookup - for now just check if products are assigned
            return false;
        }
        return false;
    }));
}

function getColorCount($products, $colorName) {
    return count(array_filter($products, function($p) use ($colorName) {
        if (empty($p['colors']) || !is_array($p['colors'])) return false;
        foreach ($p['colors'] as $color) {
            if (strtolower($color['name'] ?? '') === strtolower($colorName)) return true;
        }
        return false;
    }));
}

function getBrandCount($products, $brandName) {
    return count(array_filter($products, function($p) use ($brandName) {
        return strtolower($p['brand'] ?? '') === strtolower($brandName);
    }));
}

function getTagCount($products, $tag) {
    return count(array_filter($products, function($p) use ($tag) {
        $tags = strtolower($p['tags'] ?? '');
        return strpos($tags, strtolower($tag)) !== false;
    }));
}

// Get all unique colors from products
$allColors = [];
foreach ($products as $p) {
    if (!empty($p['colors']) && is_array($p['colors'])) {
        foreach ($p['colors'] as $color) {
            $colorName = strtolower($color['name'] ?? '');
            if (!empty($colorName) && !isset($allColors[$colorName])) {
                $allColors[$colorName] = $color;
            }
        }
    }
}

// Get all unique tags from products
$allTags = [];
foreach ($products as $p) {
    if (!empty($p['tags'])) {
        $tags = explode(',', $p['tags']);
        foreach ($tags as $tag) {
            $tag = trim($tag);
            if (!empty($tag) && !in_array($tag, $allTags)) {
                $allTags[] = $tag;
            }
        }
    }
}

// Build URL with filters
function buildFilterUrl($params = []) {
    $currentParams = $_GET;
    
    // Merge in the new parameters
    foreach ($params as $key => $value) {
        if ($value === null || $value === '') {
            unset($currentParams[$key]);
        } else {
            $currentParams[$key] = $value;
        }
    }
    
    // If we're just changing page (no filter params), keep all filters but update page
    if (isset($params['page']) && count($params) === 1) {
        // Only page is being changed, preserve all filters
        return 'shop.php' . (!empty($currentParams) ? '?' . http_build_query($currentParams) : '');
    }
    
    // If we're changing filters (not just pagination), reset to page 1
    $filterParamKeys = ['cat', 'filter_color', 'brand', 'tag', 'size', 'min_price', 'max_price', 'rating', 'on_sale', 'q'];
    $isFilterChange = false;
    foreach ($filterParamKeys as $key) {
        if (isset($params[$key])) {
            $isFilterChange = true;
            break;
        }
    }
    
    if ($isFilterChange && isset($currentParams['page'])) {
        // Reset to page 1 when filters change
        $currentParams['page'] = 1;
    }
    
    return 'shop.php' . (!empty($currentParams) ? '?' . http_build_query($currentParams) : '');
}
?>
<!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">
  
  <!-- Phase 2: SEO Meta Tags for Shop Page -->
  <?php
  // Generate page title and meta based on filters
  $pageTitle = 'Shop';
  if ($selectedCategory) {
    $pageTitle = htmlspecialchars($selectedCategory) . ' - Shop';
  } elseif (!empty($searchQuery)) {
    $pageTitle = 'Search: ' . htmlspecialchars($searchQuery);
  }
  
  $metaDescription = 'Browse our selection of fashion items. Discover great deals on quality clothing and accessories.';
  if ($selectedCategory) {
    $metaDescription = 'Shop ' . htmlspecialchars($selectedCategory) . ' fashion items at Esa\'s Fashion. Fast shipping and easy returns.';
  }
  
  // Phase 3: Optimize shop page title and description with keywords
  $categoryKey = strtolower(str_replace(' ', '-', $selectedCategory ?? 'women-clothing'));
  
  $optimizedTitle = $pageTitle;
  $optimizedDesc = $metaDescription;
  
  if (class_exists('KeywordOptimizer')) {
    $optimizedTitle = KeywordOptimizer::optimizeTitle(
      $pageTitle,
      $categoryKey,
      60
    );
    
    $optimizedDesc = KeywordOptimizer::optimizeDescription(
      $metaDescription,
      $categoryKey,
      160
    );
  }
  
  // Add canonical with parameters for pagination
  $canonicalUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/shop.php';
  if ($selectedCategory) {
    $canonicalUrl .= '?cat=' . htmlspecialchars($selectedCategory);
  }
  if ($page > 1) {
    $canonicalUrl .= (strpos($canonicalUrl, '?') ? '&' : '?') . 'page=' . $page;
  }
  ?>
  
  <title><?php echo htmlspecialchars($optimizedTitle); ?> | Esa's Fashion</title>
  <meta name="description" content="<?php echo htmlspecialchars($optimizedDesc); ?>">
  <meta name="keywords" content="fashion, shop, clothing, buy online, quality fashion">
  <link rel="canonical" href="<?php echo $canonicalUrl; ?>">
  
  <!-- Pagination Meta Tags -->
  <?php if ($page > 1): ?>
  <link rel="prev" href="<?php echo $canonicalUrl . (strpos($canonicalUrl, '?') ? '&' : '?') . 'page=' . ($page - 1); ?>">
  <?php endif; ?>
  
  <!-- Open Graph Tags -->
  <meta property="og:title" content="<?php echo htmlspecialchars($pageTitle); ?> - Esa's Fashion">
  <meta property="og:description" content="<?php echo htmlspecialchars($metaDescription); ?>">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/shop.php">
  
  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="<?php echo htmlspecialchars($pageTitle); ?>">
  <meta name="twitter:description" content="<?php echo htmlspecialchars($metaDescription); ?>">
  
  <!-- 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/7.0.1/css/all.min.css" integrity="sha512-2SwdPD6INVrV/lHTZbO2nodKhrnDdJK9/kg2XD1r9uGqPo1cUbujc+IYdlYdEErWNu69gVcYgdxlmVmzTWnetw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  <style>
    /* Shop Page Layout */
    .shop-page-wrapper {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
      position: relative;
      z-index: 1;
    }
    
    .shop-page-container {
      display: flex;
      gap: 30px;
      margin-top: 20px;
      position: relative;
      z-index: 1;
    }
    
    /* Sidebar */
    .shop-sidebar {
      width: 270px;
      flex-shrink: 0;
      max-height: none;
      overflow: visible;
    }
    
    .filter-section {
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid #e0e0e0;
      overflow: visible;
    }
    
    .filter-section:last-child {
      border-bottom: none;
    }
    
    .filter-section h3 {
      font-size: 16px;
      font-weight: 600;
      margin: 0 0 15px 0;
      color: #333;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    
    .filter-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 0;
      cursor: pointer;
    }
    
    .filter-item label {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      font-size: 14px;
      color: #666;
      flex: 1;
    }
    
    .filter-item input[type="checkbox"] {
      width: 16px;
      height: 16px;
      cursor: pointer;
    }
    
    .filter-count {
      color: #999;
      font-size: 13px;
    }
    
    /* Color Swatches in Filter */
    .color-filter-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
    
    .color-filter-swatch {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      border: 2px solid #ddd;
      cursor: pointer;
      position: relative;
      transition: all 0.3s ease;
    }
    
    .color-filter-swatch:hover {
      transform: scale(1.1);
      border-color: #333;
    }
    
    .color-filter-swatch.active {
      border-color: #F07E2D;
      border-width: 3px;
    }
    
    .color-filter-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 5px;
    }
    
    .color-filter-item .filter-count {
      font-size: 11px;
    }
    
    /* Price Range */
    
    /* Rating Filter */
    .rating-filter-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 0;
    }
    
    .rating-stars {
      color: #ffc107;
      font-size: 14px;
    }
    
    /* Content Area */
    .shop-content {
      flex: 1;
      min-width: 0;
    }
    
    /* Page Header */
    .shop-page-header {
      text-align: center;
      margin-bottom: 30px;
    }
    
    .shop-page-header h1 {
      font-size: 36px;
      font-weight: 700;
      margin: 0 0 10px 0;
      color: #333;
    }
    
    .breadcrumb {
      font-size: 14px;
      color: #666;
      margin-bottom: 20px;
      list-style: none;
      padding: 0;
    }
    
    .breadcrumb a {
      color: #666;
      text-decoration: none;
    }
    
    .breadcrumb a:hover {
      color: #F07E2D;
    }
    
    /* Top Bar */
    .shop-top-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      flex-wrap: wrap;
      gap: 15px;
      padding: 15px 0;
      border-bottom: 1px solid #e0e0e0;
    }
    
    .shop-controls-left {
      display: flex;
      gap: 15px;
      align-items: center;
      flex-wrap: wrap;
    }
    
    .shop-controls-right {
      display: flex;
      gap: 15px;
      align-items: center;
      flex-wrap: wrap;
    }
    
    .shop-controls select {
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      background: #fff;
      cursor: pointer;
    }
    
    .view-toggle {
      display: flex;
      gap: 5px;
      align-items: center;
    }
    
    .view-toggle-btn {
      width: 36px;
      height: 36px;
      border: 1px solid #ddd;
      background: #fff;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 4px;
      transition: all 0.3s ease;
    }
    
    .view-toggle-btn:hover {
      border-color: #F07E2D;
      color: #F07E2D;
    }
    
    .view-toggle-btn.active {
      background: #F07E2D;
      color: #fff;
      border-color: #F07E2D;
    }
    
    .sale-checkbox {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .sale-checkbox input[type="checkbox"] {
      width: 16px;
      height: 16px;
      cursor: pointer;
    }
    
    .active-filters {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 20px;
    }
    
    .active-filter-chip {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 6px 12px;
      background: #f0f0f0;
      border-radius: 20px;
      font-size: 13px;
      color: #333;
    }
    
    .active-filter-chip .remove {
      cursor: pointer;
      color: #999;
      font-weight: bold;
    }
    
    .active-filter-chip .remove:hover {
      color: #F07E2D;
    }
    
    /* Product Grid */
    .shop-product-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      margin-bottom: 40px;
      position: relative;
      z-index: 1;
    }
    
    .shop-product-grid.grid-2 {
      grid-template-columns: repeat(2, 1fr);
    }
    
    .shop-product-grid.grid-3 {
      grid-template-columns: repeat(3, 1fr);
    }
    
    .shop-product-grid.list-view {
      grid-template-columns: 1fr;
    }
    
    .shop-product-grid.list-view .product-display-wrapper {
      display: flex;
      flex-direction: row;
      gap: 20px;
      max-width: 100%;
    }
    
    .shop-product-grid.list-view .product-card-with-actions {
      width: 300px;
      flex-shrink: 0;
    }
    
    .shop-product-grid.list-view .product-info-outside {
      flex: 1;
      text-align: left;
    }
    
    @media (max-width: 992px) {
      .shop-product-grid {
        grid-template-columns: repeat(2, 1fr);
      }
    }
    
    @media (max-width: 768px) {
      .shop-page-container {
        flex-direction: column;
      }
      
      .shop-sidebar {
        width: 100%;
      }
      
      .shop-product-grid {
        grid-template-columns: 1fr;
      }
      
      .shop-product-grid.list-view .product-display-wrapper {
        flex-direction: column;
      }
      
      .shop-product-grid.list-view .product-card-with-actions {
        width: 100%;
      }
    }
    
    /* Pagination */
    .pagination {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 8px;
      margin-top: 40px;
      margin-bottom: 40px;
      padding: 20px;
      clear: both;
      position: relative;
      z-index: 10;
    }
    
    .pagination a,
    .pagination span {
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      text-decoration: none;
      color: #333;
      font-size: 14px;
      background: #fff;
      cursor: pointer;
      display: inline-block;
    }
    
    .pagination a {
      background: #F07E2D;
      color: #fff;
      border-color: #F07E2D;
      cursor: pointer;
    }
    
    .pagination a:hover {
      background: #e06a1a;
      color: #fff;
      border-color: #e06a1a;
      text-decoration: none;
    }
    
    .pagination span.current {
      background: #F07E2D;
      color: #fff;
      border-color: #F07E2D;
      padding: 8px 12px;
    }
    
    .pagination span.disabled {
      opacity: 0.5;
      cursor: not-allowed;
      background: #f5f5f5;
      color: #999;
      padding: 8px 12px;
    }
    
    /* Ensure pagination and footer are always visible */
    .pagination {
      width: 100%;
      display: flex !important;
      visibility: visible !important;
      opacity: 1 !important;
    }
    
    .shop-content {
      width: 100%;
      display: flex;
      flex-direction: column;
    }
    
    .shop-page-wrapper {
      width: 100%;
    }
    
    .shop-page-container {
      width: 100%;
      display: flex;
      gap: 30px;
    }
  </style>
</head>
<body>

<script>

function playProductVideo(overlay, videoSrc) {
  const video = overlay.querySelector('video');
  if (!video) return;
  
  overlay.classList.add('playing');
  overlay.style.opacity = '1';
  video.style.display = 'block';
  
  // Play the video
  const playPromise = video.play();
  if (playPromise !== undefined) {
    playPromise.catch(error => {
      console.log('Video autoplay prevented:', error);
    });
  }
}

function pauseProductVideo(overlay) {
  const video = overlay.querySelector('video');
  if (!video) return;
  
  overlay.classList.remove('playing');
  overlay.style.opacity = '0';
  video.style.display = 'none';
  video.pause();
  video.currentTime = 0;
}

function switchShopProductImage(event, colorImage, mainImage) {
  if (event) {
    event.preventDefault();
    event.stopPropagation();
  }
  
  const btn = event.target;
  
  // Get image from data attributes if available (more reliable)
  if (!colorImage && btn.dataset && btn.dataset.colorImage) {
    colorImage = btn.dataset.colorImage;
  }
  if (!mainImage && btn.dataset && btn.dataset.mainImage) {
    mainImage = btn.dataset.mainImage;
  }
  
  const productWrapper = btn.closest('.product-display-wrapper');
  if (!productWrapper) {
    console.error('Could not find product wrapper');
    return;
  }
  
  // Try multiple selectors to find the product image
  let productImage = productWrapper.querySelector('.product-card-with-actions img') || 
                     productWrapper.querySelector('.product-card-image-wrapper img') || 
                     productWrapper.querySelector('.product-image-link img') ||
                     productWrapper.querySelector('img');
  
  if (!productImage) {
    console.error('Could not find product image element');
    return;
  }
  
  // Use color image if valid, otherwise use main image
  let imageToShow = (colorImage && colorImage.trim() && colorImage !== 'undefined' && colorImage !== 'null' && colorImage !== '') ? colorImage : mainImage;
  
  if (imageToShow) {
    productImage.src = imageToShow;
    productImage.alt = productImage.alt || 'Product'; // Keep alt text
    
    // Update all swatches to show active state
    const allSwatches = productWrapper.querySelectorAll('.shop-color-swatch');
    allSwatches.forEach(swatch => {
      swatch.style.borderColor = '#ddd';
      swatch.style.borderWidth = '2px';
    });
    btn.style.borderColor = '#F07E2D';
    btn.style.borderWidth = '3px';
  } else {
    console.error('No valid image to show');
  }
}

function toggleColorFilter(colorName) {
  const url = new URL(window.location.href);
  const colors = url.searchParams.getAll('filter_color');
  const index = colors.indexOf(colorName);
  
  if (index > -1) {
    colors.splice(index, 1);
  } else {
    colors.push(colorName);
  }
  
  url.searchParams.delete('filter_color');
  colors.forEach(c => url.searchParams.append('filter_color', c));
  url.searchParams.delete('page');
  
  window.location.href = url.toString();
}

function updateFilter(filterType, value) {
  const url = new URL(window.location.href);
  
  if (filterType === 'category') {
    if (value) {
      url.searchParams.set('cat', value);
    } else {
      url.searchParams.delete('cat');
    }
  } else if (filterType === 'brand') {
    const brands = url.searchParams.getAll('brand');
    const index = brands.indexOf(value);
    if (index > -1) {
      brands.splice(index, 1);
      url.searchParams.delete('brand');
      brands.forEach(b => url.searchParams.append('brand', b));
    } else {
      url.searchParams.append('brand', value);
    }
  } else if (filterType === 'tag') {
    const tags = url.searchParams.getAll('tag');
    const index = tags.indexOf(value);
    if (index > -1) {
      tags.splice(index, 1);
      url.searchParams.delete('tag');
      tags.forEach(t => url.searchParams.append('tag', t));
    } else {
      url.searchParams.append('tag', value);
    }
  } else if (filterType === 'size') {
    const sizes = url.searchParams.getAll('size');
    const index = sizes.indexOf(value);
    if (index > -1) {
      sizes.splice(index, 1);
      url.searchParams.delete('size');
      sizes.forEach(s => url.searchParams.append('size', s));
    } else {
      url.searchParams.append('size', value);
    }
  } else if (filterType === 'rating') {
    if (value) {
      url.searchParams.set('rating', value);
    } else {
      url.searchParams.delete('rating');
    }
  } else if (filterType === 'on_sale') {
    if (value) {
      url.searchParams.set('on_sale', '1');
    } else {
      url.searchParams.delete('on_sale');
    }
  }
  
  url.searchParams.delete('page');
  window.location.href = url.toString();
}

function updatePriceRange(range) {
  const url = new URL(window.location.href);
  url.searchParams.delete('min_price');
  url.searchParams.delete('max_price');
  
  if (range === '0-100') {
    url.searchParams.set('min_price', '0');
    url.searchParams.set('max_price', '100');
  } else if (range === '100-299') {
    url.searchParams.set('min_price', '100');
    url.searchParams.set('max_price', '299');
  } else if (range === '300-999') {
    url.searchParams.set('min_price', '300');
    url.searchParams.set('max_price', '999');
  } else if (range === '700-6999') {
    url.searchParams.set('min_price', '700');
    url.searchParams.set('max_price', '6999');
  } else if (range === '6999+') {
    url.searchParams.set('min_price', '6999');
  }
  
  url.searchParams.delete('page');
  window.location.href = url.toString();
}

function applyCustomPriceRange() {
  const minPriceInput = document.getElementById('price-min');
  const maxPriceInput = document.getElementById('price-max');
  const minPrice = minPriceInput.value ? parseFloat(minPriceInput.value) : null;
  const maxPrice = maxPriceInput.value ? parseFloat(maxPriceInput.value) : null;
  
  if (minPrice === null || maxPrice === null || minPrice < 0 || maxPrice < 0) {
    alert('Please enter valid price range');
    return;
  }
  
  if (minPrice > maxPrice) {
    alert('Minimum price cannot be greater than maximum price');
    return;
  }
  
  const url = new URL(window.location.href);
  url.searchParams.delete('min_price');
  url.searchParams.delete('max_price');
  url.searchParams.set('min_price', minPrice.toString());
  url.searchParams.set('max_price', maxPrice.toString());
  url.searchParams.delete('page');
  window.location.href = url.toString();
}

function applyPriceFilter() {
  // This function is kept for backward compatibility
  // New function applyCustomPriceRange() should be used instead
  applyCustomPriceRange();
}

function removeFilter(filterType, value) {
  const url = new URL(window.location.href);
  
  if (filterType === 'category') {
    url.searchParams.delete('cat');
  } else if (filterType === 'color') {
    const colors = url.searchParams.getAll('filter_color');
    const newColors = colors.filter(c => c !== value);
    url.searchParams.delete('filter_color');
    newColors.forEach(c => url.searchParams.append('filter_color', c));
  } else if (filterType === 'brand') {
    const brands = url.searchParams.getAll('brand');
    const newBrands = brands.filter(b => b !== value);
    url.searchParams.delete('brand');
    newBrands.forEach(b => url.searchParams.append('brand', b));
  } else if (filterType === 'tag') {
    const tags = url.searchParams.getAll('tag');
    const newTags = tags.filter(t => t !== value);
    url.searchParams.delete('tag');
    newTags.forEach(t => url.searchParams.append('tag', t));
  } else if (filterType === 'size') {
    const sizes = url.searchParams.getAll('size');
    const newSizes = sizes.filter(s => s !== value);
    url.searchParams.delete('size');
    newSizes.forEach(s => url.searchParams.append('size', s));
  } else if (filterType === 'price') {
    url.searchParams.delete('min_price');
    url.searchParams.delete('max_price');
  } else if (filterType === 'rating') {
    url.searchParams.delete('rating');
  } else if (filterType === 'sale') {
    url.searchParams.delete('on_sale');
  }
  
  url.searchParams.delete('page');
  window.location.href = url.toString();
}

function clearAllFilters() {
  window.location.href = 'shop.php';
}

function setView(viewType) {
  const url = new URL(window.location.href);
  url.searchParams.set('view', viewType);
  url.searchParams.delete('page');
  window.location.href = url.toString();
}
</script>

<?php include __DIR__ . '/header.php'; ?>

<div class="shop-page-wrapper">
  <!-- Breadcrumb with Schema -->
  <?php
  $breadcrumbs = [
    ['title' => 'Home', 'url' => 'index.php'],
    ['title' => 'Shop', 'url' => null]
  ];
  
  // Output breadcrumb with schema
  echo InternalLinkingHelper::generateBreadcrumb($breadcrumbs);
  echo InternalLinkingHelper::generateBreadcrumbSchema($breadcrumbs);
  ?>
  
  <!-- Page Header -->
  <div class="shop-page-header">
    <?php
    $shopTitle = 'Shop';
    if ($selectedCategory) {
      $shopTitle = htmlspecialchars($selectedCategory);
    } elseif (!empty($searchQuery)) {
      $shopTitle = 'Search Results for "' . htmlspecialchars($searchQuery) . '"';
    }
    echo h1($shopTitle);
    ?>
    <!-- Original breadcrumb removed (now generated with schema above) -->
  </div>

  <div class="shop-page-container">
    <!-- Sidebar Filters -->
    <aside class="shop-sidebar">
      <form method="get" action="shop.php" id="filterForm">
        <!-- Categories Filter -->
        <div class="filter-section">
          <h3>Categories</h3>
          <div class="filter-item">
            <label>
              <input type="radio" name="cat" value="" <?php echo empty($selectedCategory) ? 'checked' : ''; ?> onchange="this.form.submit()">
              <span>All Categories</span>
            </label>
            <span class="filter-count">(<?php echo count($products); ?>)</span>
          </div>
          <?php foreach ($categories as $category): 
            $count = getCategoryCount($products, $category);
            if ($count > 0):
          ?>
            <div class="filter-item">
              <label>
                <input type="radio" name="cat" value="<?php echo htmlspecialchars($category); ?>" <?php echo strtolower($selectedCategory) === strtolower($category) ? 'checked' : ''; ?> onchange="this.form.submit()">
                <span><?php echo htmlspecialchars($category); ?></span>
              </label>
              <span class="filter-count">(<?php echo $count; ?>)</span>
            </div>
          <?php endif; endforeach; ?>
        </div>

        <!-- Price Filter -->
        <div class="filter-section">
          <h3>Price</h3>
          <div class="filter-item">
            <label>
              <input type="radio" name="price_range" value="" <?php echo ($minPrice === null && $maxPrice === null) ? 'checked' : ''; ?> onchange="updatePriceRange('')">
              <span>All</span>
            </label>
          </div>
          <div class="filter-item">
            <label>
              <input type="radio" name="price_range" value="0-100" <?php echo ($minPrice === null || $minPrice === 0) && ($maxPrice === 100 || ($maxPrice === null && $minPrice === null)) ? 'checked' : ''; ?> onchange="updatePriceRange('0-100')">
              <span>$100.00 & Under</span>
            </label>
          </div>
          <div class="filter-item">
            <label>
              <input type="radio" name="price_range" value="100-299" onchange="updatePriceRange('100-299')">
              <span>$100.00 - $299.00</span>
            </label>
          </div>
          <div class="filter-item">
            <label>
              <input type="radio" name="price_range" value="300-999" onchange="updatePriceRange('300-999')">
              <span>$300.00 - $999.00</span>
            </label>
          </div>
          <div class="filter-item">
            <label>
              <input type="radio" name="price_range" value="700-6999" onchange="updatePriceRange('700-6999')">
              <span>$700.00 - $6,999.00</span>
            </label>
          </div>
          <div class="filter-item">
            <label>
              <input type="radio" name="price_range" value="6999+" onchange="updatePriceRange('6999+')">
              <span>$6,999.00 & Over</span>
            </label>
          </div>
          
          <!-- Price Input Filter - Range Selector -->
          <div class="filter-item price-input-wrapper" style="margin-top: 15px; border-top: 1px solid #eee; padding-top: 15px;">
            <label style="display: block; margin-bottom: 8px; font-weight: 500; font-size: 14px;">Custom Price Range</label>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 10px;">
              <div>
                <label style="font-size: 12px; color: #666; display: block; margin-bottom: 4px;">Min Price</label>
                <input type="number" id="price-min" placeholder="Min" step="0.01" min="0" value="<?php echo htmlspecialchars($minPrice ?? ''); ?>" style="width: 100%; padding: 8px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
              </div>
              <div>
                <label style="font-size: 12px; color: #666; display: block; margin-bottom: 4px;">Max Price</label> 
                <input type="number" id="price-max" placeholder="Max" step="0.01" min="0" value="<?php echo htmlspecialchars($maxPrice ?? ''); ?>" style="width: 100%; padding: 8px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
              </div>
            </div>

            <button type="button" onclick="applyCustomPriceRange()" style="width: 100%; padding: 8px 16px; background: #F07E2D; color: white; border: none; border-radius: 4px; cursor: pointer; font-weight: 600; font-size: 14px;">Apply Range</button>
          </div>
        </div>

        <!-- Color Filter -->
        <?php if (!empty($allColors)): ?>
        <div class="filter-section">
          <h3>Filter By Color</h3>
          <div class="color-filter-grid">
            <?php foreach ($allColors as $colorName => $color): 
              $count = getColorCount($products, $colorName);
              if ($count > 0):
                $isActive = in_array($colorName, array_map('strtolower', $selectedColors));
            ?>
              <div class="color-filter-item">
                <div class="color-filter-swatch <?php echo $isActive ? 'active' : ''; ?>" 
                     style="background-color: <?php echo htmlspecialchars($color['code'] ?? '#ccc'); ?>;"
                     onclick="toggleColorFilter('<?php echo htmlspecialchars($colorName); ?>')"
                     title="<?php echo htmlspecialchars(ucfirst($colorName)); ?>">
                </div>
                <span class="filter-count"><?php echo $count; ?></span>
              </div>
            <?php endif; endforeach; ?>
          </div>
        </div>
        <?php endif; ?>

        <!-- Brands Filter -->
        <?php if (!empty($brands)): ?>
        <div class="filter-section">
          <h3>Brands</h3>
          <?php foreach ($brands as $brand): 
            $count = getBrandCount($products, $brand['name']);
            if ($count > 0):
              $isChecked = in_array($brand['name'], $selectedBrands);
          ?>
            <div class="filter-item">
              <label>
                <input type="checkbox" name="brand[]" value="<?php echo htmlspecialchars($brand['name']); ?>" 
                       <?php echo $isChecked ? 'checked' : ''; ?> 
                       onchange="updateFilter('brand', '<?php echo htmlspecialchars($brand['name']); ?>')">
                <span><?php echo htmlspecialchars($brand['name']); ?></span>
              </label>
              <span class="filter-count">(<?php echo $count; ?>)</span>
            </div>
          <?php endif; endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Size Filter -->
        <div class="filter-section">
          <h3>Size</h3>
          <?php
          $allSizes = [];
          foreach ($products as $p) {
            if (!empty($p['sizes']) && is_array($p['sizes'])) {
              foreach ($p['sizes'] as $size) {
                if (!in_array($size, $allSizes)) {
                  $allSizes[] = $size;
                }
              }
            }
          }
          sort($allSizes);
          $selectedSizes = isset($_GET['size']) ? (is_array($_GET['size']) ? $_GET['size'] : [$_GET['size']]) : [];
          foreach ($allSizes as $size):
            $sizeCount = count(array_filter($products, function($p) use ($size) {
              return !empty($p['sizes']) && is_array($p['sizes']) && in_array($size, $p['sizes']);
            }));
            if ($sizeCount > 0):
              $isChecked = in_array($size, $selectedSizes);
          ?>
            <div class="filter-item">
              <label>
                <input type="checkbox" name="size[]" value="<?php echo htmlspecialchars($size); ?>" 
                       <?php echo $isChecked ? 'checked' : ''; ?> 
                       onchange="updateFilter('size', '<?php echo htmlspecialchars($size); ?>')">
                <span><?php echo htmlspecialchars($size); ?></span>
              </label>
              <span class="filter-count">(<?php echo $sizeCount; ?>)</span>
            </div>
          <?php endif; endforeach; ?>
        </div>

        <!-- Tags Filter -->
        <?php if (!empty($allTags)): ?>
        <div class="filter-section">
          <h3>Tags</h3>
          <?php foreach ($allTags as $tag): 
            $count = getTagCount($products, $tag);
            if ($count > 0):
              $isChecked = in_array($tag, $selectedTags);
          ?>
            <div class="filter-item">
              <label>
                <input type="checkbox" name="tag[]" value="<?php echo htmlspecialchars($tag); ?>" 
                       <?php echo $isChecked ? 'checked' : ''; ?> 
                       onchange="updateFilter('tag', '<?php echo htmlspecialchars($tag); ?>')">
                <span><?php echo htmlspecialchars($tag); ?></span>
              </label>
              <span class="filter-count">(<?php echo $count; ?>)</span>
            </div>
          <?php endif; endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Rating Filter -->
        <div class="filter-section">
          <h3>Average Rating</h3>
          <?php for ($i = 5; $i >= 1; $i--): 
            $count = count(array_filter($products, function($p) use ($i) {
              return (float)($p['rating'] ?? 0) >= $i;
            }));
            if ($count > 0):
              $isChecked = $minRating !== null && $minRating == $i;
          ?>
            <div class="rating-filter-item">
              <label style="cursor: pointer; display: flex; align-items: center; gap: 8px; flex: 1;">
                <input type="radio" name="rating" value="<?php echo $i; ?>" 
                       <?php echo $isChecked ? 'checked' : ''; ?> 
                       onchange="updateFilter('rating', <?php echo $i; ?>)">
                <span class="rating-stars">
                  <?php for ($j = 0; $j < 5; $j++): ?>
                    <i class="fa<?php echo $j < $i ? 's' : 'r'; ?> fa-star"></i>
                  <?php endfor; ?>
                </span>
                <span class="filter-count">(<?php echo $count; ?>)</span>
              </label>
            </div>
          <?php endif; endfor; ?>
        </div>

      </form>
    </aside>

    <!-- Main Content -->
    <div class="shop-content">
      <!-- Top Bar Controls -->
      <div class="shop-top-bar">
        <div class="shop-controls-left">
          <span style="color: #666; font-size: 14px;">Sort by :</span>
          <select name="sort" onchange="window.location.href=buildSortUrl(this.value)">
            <option value="latest" <?php echo $sort === 'latest' ? 'selected' : ''; ?>>Latest</option>
            <option value="best-selling" <?php echo $sort === 'best-selling' ? 'selected' : ''; ?>>Best Selling</option>
            <option value="best-rated" <?php echo $sort === 'best-rated' ? 'selected' : ''; ?>>Best Rated</option>
            <option value="price-low" <?php echo $sort === 'price-low' ? 'selected' : ''; ?>>Price Low</option>
            <option value="price-high" <?php echo $sort === 'price-high' ? 'selected' : ''; ?>>Price High</option>
          </select>
          <div class="sale-checkbox">
            <input type="checkbox" id="on_sale_check" <?php echo $onSale ? 'checked' : ''; ?> onchange="updateFilter('on_sale', this.checked)">
            <label for="on_sale_check" style="cursor: pointer; font-size: 14px; color: #666;">Show only products on sale</label>
          </div>
        </div>
        <div class="shop-controls-right">
          <div class="view-toggle">
            <button class="view-toggle-btn <?php echo (!isset($_GET['view']) || $_GET['view'] === 'grid-3') ? 'active' : ''; ?>" onclick="setView('grid-3')" title="Grid 3 Columns">
              <i class="fa-solid fa-th" style="font-size: 14px;"></i>
            </button>
            <button class="view-toggle-btn <?php echo isset($_GET['view']) && $_GET['view'] === 'grid-2' ? 'active' : ''; ?>" onclick="setView('grid-2')" title="Grid 2 Columns">
              <i class="fa-solid fa-th-large" style="font-size: 14px;"></i>
            </button>
            <button class="view-toggle-btn <?php echo isset($_GET['view']) && $_GET['view'] === 'list' ? 'active' : ''; ?>" onclick="setView('list')" title="List View">
              <i class="fa-solid fa-list" style="font-size: 14px;"></i>
            </button>
          </div>
          <select name="per_page" onchange="window.location.href=buildPerPageUrl(this.value)" style="margin-left: 10px;">
            <option value="18" <?php echo $perPage === 18 ? 'selected' : ''; ?>>Show: 18</option>
            <option value="36" <?php echo $perPage === 36 ? 'selected' : ''; ?>>Show: 36</option>
            <option value="54" <?php echo $perPage === 54 ? 'selected' : ''; ?>>Show: 54</option>
            <option value="72" <?php echo $perPage === 72 ? 'selected' : ''; ?>>Show: 72</option>
          </select>
        </div>
      </div>

      <!-- Active Filters -->
      <?php 
      $hasActiveFilters = !empty($selectedCategory) || !empty($selectedColors) || !empty($selectedBrands) || 
                         !empty($selectedTags) || !empty($selectedSizes) || $minPrice !== null || $maxPrice !== null || 
                         $minRating !== null || $onSale;
      ?>
      <?php if ($hasActiveFilters): ?>
      <div class="active-filters">
        <?php if (!empty($selectedCategory)): ?>
          <span class="active-filter-chip">
            Category: <?php echo htmlspecialchars($selectedCategory); ?>
            <span class="remove" onclick="removeFilter('category', '')">×</span>
          </span>
        <?php endif; ?>
        
        <?php foreach ($selectedColors as $color): ?>
          <span class="active-filter-chip">
            Color: <?php echo htmlspecialchars(ucfirst($color)); ?>
            <span class="remove" onclick="removeFilter('color', '<?php echo htmlspecialchars($color); ?>')">×</span>
          </span>
        <?php endforeach; ?>
        
        <?php foreach ($selectedBrands as $brand): ?>
          <span class="active-filter-chip">
            Brand: <?php echo htmlspecialchars($brand); ?>
            <span class="remove" onclick="removeFilter('brand', '<?php echo htmlspecialchars($brand); ?>')">×</span>
          </span>
        <?php endforeach; ?>
        
        <?php foreach ($selectedTags as $tag): ?>
          <span class="active-filter-chip">
            Tag: <?php echo htmlspecialchars($tag); ?>
            <span class="remove" onclick="removeFilter('tag', '<?php echo htmlspecialchars($tag); ?>')">×</span>
          </span>
        <?php endforeach; ?>
        
        <?php foreach ($selectedSizes as $size): ?>
          <span class="active-filter-chip">
            Size: <?php echo htmlspecialchars($size); ?>
            <span class="remove" onclick="removeFilter('size', '<?php echo htmlspecialchars($size); ?>')">×</span>
          </span>
        <?php endforeach; ?>
        
        <?php if ($minPrice !== null || $maxPrice !== null): ?>
          <span class="active-filter-chip">
            Price: $<?php echo $minPrice !== null ? $minPrice : '0'; ?> - $<?php echo $maxPrice !== null ? $maxPrice : '∞'; ?>
            <span class="remove" onclick="removeFilter('price', '')">×</span>
          </span>
        <?php endif; ?>
        
        <?php if ($minRating !== null): ?>
          <span class="active-filter-chip">
            Rating: <?php echo $minRating; ?>+ stars
            <span class="remove" onclick="removeFilter('rating', '')">×</span>
          </span>
        <?php endif; ?>
        
        <?php if ($onSale): ?>
          <span class="active-filter-chip">
            On Sale
            <span class="remove" onclick="removeFilter('sale', '')">×</span>
          </span>
        <?php endif; ?>
        
        <span class="active-filter-chip" style="background: #F07E2D; color: #fff; cursor: pointer;" onclick="clearAllFilters()">
          Clear All
        </span>
      </div>
      <?php endif; ?>

      <!-- Product Grid -->
      <?php if (!empty($paginatedProducts)): ?>
      <div class="shop-product-grid <?php echo htmlspecialchars($view); ?>">
        <?php foreach ($paginatedProducts as $p): 
      $productTitle = htmlspecialchars($p['title'] ?? 'Product');
      $basePrice = (float)($p['price'] ?? 0);
          $baseSalePrice = isset($p['sale_price']) ? (float)$p['sale_price'] : null;
          $baseDisplayPrice = $baseSalePrice !== null ? $baseSalePrice : $basePrice;

          // Convert prices based on selected currency
          $convertedPrice = $basePrice * $currencyRate;
          $convertedSalePrice = $baseSalePrice !== null ? $baseSalePrice * $currencyRate : null;
          $convertedDisplayPrice = $baseDisplayPrice * $currencyRate;

      $productId = $p['id'] ?? '';
          $rating = (float)($p['rating'] ?? 0);
      
      // Determine which image to display - use selected color image if color filter is active
      $imageToDisplay = $p['image'] ?? '';
      if ($displayColorName && !empty($p['colors']) && is_array($p['colors'])) {
        foreach ($p['colors'] as $color) {
          if (strtolower($color['name'] ?? '') === $displayColorName && !empty($color['image'])) {
            $imageToDisplay = $color['image'];
            break;
          }
        }
      }
      
      // Generate SEO-friendly alt text
      $altText = ImageAltHelper::generateProductAlt($productTitle, $displayColorName ?? 'Various colors', 'Shop');
    ?>
      <div class="product-display-wrapper">
            <!-- Product Card -->
        <div class="product-card-with-actions">
          <div class="product-card-image-wrapper" style="position:relative;">
            <a href="product.php?id=<?php echo htmlspecialchars($p['id']); ?>" class="product-image-link">
              <?php
              if (!empty($imageToDisplay)) {
                  $imageUrl = getImageForSection($imageToDisplay, 'shop');
                  echo '<img id="prod-img-' . $p['id'] . '" src="' . htmlspecialchars($imageUrl) . '" alt="' . htmlspecialchars($altText) . '">';
              } else {
                  echo '<img id="prod-img-' . $p['id'] . '" src="pics_ecom/placeholder.png" alt="' . htmlspecialchars($altText) . '">';
              }
              ?>
            </a>
            
            <!-- Video Hover Overlay -->
            <?php if (!empty($p['video'])): ?>
            <div class="product-video-overlay" 
                 style="position:absolute; top:0; left:0; width:100%; height:100%; background:#000; opacity:0; display:flex; align-items:center; justify-content:center; transition:opacity 0.3s ease; border-radius:8px; cursor:pointer;"
                 onmouseenter="playProductVideo(this, '<?php echo htmlspecialchars($p['video']); ?>')"
                 onmouseleave="pauseProductVideo(this)"
                 onclick="window.location.href='product.php?id=<?php echo $p['id']; ?>'">
              <video style="width:100%; height:100%; object-fit:cover; border-radius:8px; display:none;" muted playsinline>
                <source src="<?php echo htmlspecialchars($p['video']); ?>" type="video/mp4">
              </video>
              <i class="fas fa-play" style="color:#fff; font-size:48px; position:absolute; z-index:10;"></i>
            </div>
            <style>
              .product-video-overlay video {
                display: none !important;
              }
              .product-video-overlay.playing video {
                display: block !important;
              }
              .product-video-overlay.playing i.fa-play {
                display: none;
              }
            </style>
            <?php endif; ?>
            
                <!-- Quick Action Icons -->
            <div class="product-quick-actions">
                  <button type="button" class="quick-action-btn wishlist" onclick="toggleWishlistQuick(<?php echo $p['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 $p['id']; ?>, event)" title="Add to Cart">
                    <i class="fa-solid fa-basket-shopping"></i>
                  </button>
            </div>
          </div>
        </div>
            <!-- Product Info -->
        <div class="product-info-outside">
              <!-- Color Swatches -->
          <?php if (!empty($p['colors']) && is_array($p['colors'])): ?>
                <div class="color-swatches-grid" style="gap:6px; margin-bottom:8px; justify-content: center;">
              <?php 
              $mainImageUrl = !empty($p['image']) ? getImageForSection($p['image'], 'shop') : 'pics_ecom/placeholder.png';
              foreach (array_slice($p['colors'], 0, 4) as $idx => $color): 
                $colorImagePath = isset($color['image']) && !empty($color['image']) ? $color['image'] : (isset($p['image']) ? $p['image'] : '');
                $colorImageUrl = !empty($colorImagePath) && file_exists(__DIR__ . '/' . $colorImagePath) ? getImageForSection($colorImagePath, 'shop') : $mainImageUrl;
                $colorCode = htmlspecialchars($color['code'] ?? '#cccccc');
                $colorName = htmlspecialchars($color['name'] ?? '');
              ?>
                <button type="button" class="color-swatch shop-color-swatch" 
                        style="width: 28px; height: 28px; background-color: <?php echo $colorCode; ?>; border: 2px solid #ddd; cursor: pointer; border-radius: 50%;"
                        title="<?php echo $colorName; ?>"
                        data-color-image="<?php echo htmlspecialchars($colorImageUrl); ?>"
                        data-main-image="<?php echo htmlspecialchars($mainImageUrl); ?>"
                        onclick="switchShopProductImage(event, '<?php echo htmlspecialchars($colorImageUrl); ?>', '<?php echo htmlspecialchars($mainImageUrl); ?>')"></button>
              <?php endforeach; ?>
              <?php if (count($p['colors']) > 4): ?>
                <div style="display:flex; align-items:center; font-size:12px; color:#666;">+<?php echo count($p['colors']) - 4; ?></div>
              <?php endif; ?>
            </div>
          <?php endif; ?>
          
              <h3 style="margin:8px 0 4px 0; font-size:14px; font-weight:600; color:#333; text-align:center;"><?php echo $productTitle; ?></h3>
              
              <!-- Rating -->
              <?php if ($rating > 0): ?>
                <div style="display:flex; align-items:center; justify-content:center; gap:4px; margin:4px 0;">
                  <span class="rating-stars" style="font-size:12px;">
                    <?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; ?>
                  </span>
                  <span style="font-size:12px; color:#666;">(<?php echo $rating; ?>)</span>
                </div>
              <?php endif; ?>
              
              <!-- Price (converted with selected currency) -->
              <p style="margin:0; font-size:16px; font-weight:700; color:#F07E2D; text-align:center;">
                <?php if ($convertedSalePrice !== null): ?>
                  <span style="text-decoration: line-through; color: #999; font-size: 14px; margin-right: 8px;">
                    <?php echo $currencySymbol . number_format($convertedPrice, 2, '.', ''); ?>
                  </span>
                  <span>
                    <?php echo $currencySymbol . number_format($convertedSalePrice, 2, '.', ''); ?>
                  </span>
                <?php else: ?>
                  <?php echo $currencySymbol . number_format($convertedDisplayPrice, 2, '.', ''); ?>
                <?php endif; ?>
              </p>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
  
      <?php else: ?>
        <p style="text-align: center; padding: 40px; color: #666;">No products found matching your filters.</p>
      <?php endif; ?>

      <!-- Pagination -->
      <?php if ($totalPages > 1): ?>
      <div class="pagination">
        <?php if ($page > 1): ?>
          <a href="shop.php?page=<?php echo ($page - 1); ?>">&laquo; Previous</a>
        <?php else: ?>
          <span class="disabled">&laquo; Previous</span>
        <?php endif; ?>
        
        <?php
        $startPage = max(1, $page - 2);
        $endPage = min($totalPages, $page + 2);
        
        if ($startPage > 1): ?>
          <a href="shop.php?page=1">1</a>
          <?php if ($startPage > 2): ?>
            <span>...</span>
          <?php endif; ?>
        <?php endif; ?>
        
        <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
          <?php if ($i == $page): ?>
            <span class="current"><?php echo $i; ?></span>
          <?php else: ?>
            <a href="shop.php?page=<?php echo $i; ?>"><?php echo $i; ?></a>
          <?php endif; ?>
        <?php endfor; ?>
        
        <?php if ($endPage < $totalPages): ?>
          <?php if ($endPage < $totalPages - 1): ?>
            <span>...</span>
          <?php endif; ?>
          <a href="shop.php?page=<?php echo $totalPages; ?>"><?php echo $totalPages; ?></a>
        <?php endif; ?>
        
        <?php if ($page < $totalPages): ?>
          <a href="shop.php?page=<?php echo ($page + 1); ?>">Next &raquo;</a>
        <?php else: ?>
          <span class="disabled">Next &raquo;</span>
        <?php endif; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

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

<script>
function buildSortUrl(sortValue) {
  const url = new URL(window.location.href);
  url.searchParams.set('sort', sortValue);
  url.searchParams.delete('page');
  return url.toString();
}

function buildPerPageUrl(perPageValue) {
  const url = new URL(window.location.href);
  url.searchParams.set('per_page', perPageValue);
  url.searchParams.delete('page');
  return url.toString();
}

function toggleWishlistQuick(productId, event) {
  event.preventDefault();
  const btn = event.target.closest('.quick-action-btn, .action-icon-btn');
  
  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) {
      btn.classList.toggle('active');
      if (data.action === 'added') {
        btn.innerHTML = '<i class="fa-solid fa-heart"></i>';
        btn.title = 'Remove from Wishlist';
      } else {
        btn.innerHTML = '<i class="fa-regular fa-heart"></i>';
        btn.title = 'Add to Wishlist';
      }
    }
  })
  .catch(error => console.error('Error:', error));
}

function addToCartQuick(productId, event) {
  event.preventDefault();
  const form = new FormData();
  form.append('action', 'add');
  form.append('id', productId);
  form.append('qty', 1);
  
  fetch('cart.php', {
    method: 'POST',
    body: form
  })
  .then(() => {
    alert('Product added to cart!');
    window.location.href = 'cart.php';
  })
  .catch(error => console.error('Error:', error));
}
</script>

</body>
</html>
