<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

require_once __DIR__ . '/config/image_config.php';

// 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';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  
  <!-- Phase 2: SEO Meta Tags for Category Pages -->
  <?php
  // Get category info for meta tags
  $categoryId = isset($_GET['id']) ? (int)$_GET['id'] : null;
  $categoryName = isset($_GET['cat']) ? $_GET['cat'] : null;
  $cat = 'All Products';
  
  // Load categories to map ID to name
  $categories = [];
  $categoriesFile = __DIR__ . '/data/categories.json';
  if (file_exists($categoriesFile)) {
    $categories = json_decode(file_get_contents($categoriesFile), true) ?: [];
  }
  
  // If ID is provided, find the category name
  if ($categoryId !== null) {
    foreach ($categories as $c) {
      if ($c['id'] === $categoryId) {
        $cat = $c['name'];
        $categoryName = $c['slug'] ?? strtolower($c['name']);
        break;
      }
    }
  } elseif ($categoryName) {
    $cat = $categoryName;
  }
  
  // Phase 3: Optimize category title and description with keywords
  $categoryTitle = $cat . ' - Shop';
  $categoryDesc = 'Browse our collection of ' . htmlspecialchars($cat) . ' fashion. Shop quality items at great prices.';
  $categoryKeywords = ['fashion', 'clothing', strtolower($cat), 'shop', 'buy online'];
  
  if (class_exists('KeywordOptimizer')) {
    $optimizerKeywords = KeywordOptimizer::getKeywords(strtolower($categoryName ?? $cat));
    
    // Extract keywords from optimizer (handles both simple array and associative array formats)
    if (is_array($optimizerKeywords)) {
      if (isset($optimizerKeywords['primary'])) {
        // Associative array format: extract primary and build array
        $categoryKeywords = [$optimizerKeywords['primary']];
        if (isset($optimizerKeywords['variations']) && is_array($optimizerKeywords['variations'])) {
          $categoryKeywords = array_merge($categoryKeywords, array_slice($optimizerKeywords['variations'], 0, 2));
        }
      } else {
        // Simple array format
        $categoryKeywords = $optimizerKeywords;
      }
    }
    
    $categoryTitle = KeywordOptimizer::optimizeTitle(
      $cat . ' - Shop',
      strtolower($categoryName ?? $cat),
      60
    );
    
    $categoryDesc = KeywordOptimizer::optimizeDescription(
      'Browse our collection of ' . htmlspecialchars($cat) . ' fashion. Shop quality items at great prices.',
      strtolower($categoryName ?? $cat),
      160
    );
  }
  
  // Generate SEO meta tags
  $title = (function_exists('seo_title') ? seo_title($categoryTitle, 'Esa\'s Fashion') : htmlspecialchars($categoryTitle));
  $description = (function_exists('seo_description') ? seo_description($categoryDesc) : htmlspecialchars($categoryDesc));
  $keywordsArray = is_array($categoryKeywords) ? $categoryKeywords : [$categoryKeywords];
  $keywords = (function_exists('seo_keywords') ? seo_keywords(implode(', ', $keywordsArray)) : implode(', ', $keywordsArray));
  ?>
  
  <title><?php echo $title; ?></title>
  <meta name="description" content="<?php echo $description; ?>">
  <meta name="keywords" content="<?php echo $keywords; ?>">
  <link rel="canonical" href="https://<?php echo $_SERVER['HTTP_HOST']; ?>/category.php<?php echo $categoryId ? '?id=' . $categoryId : ($categoryName ? '?cat=' . htmlspecialchars($categoryName) : ''); ?>">
  
  <!-- Open Graph Tags -->
  <meta property="og:title" content="<?php echo htmlspecialchars($cat); ?> - Esa's Fashion">
  <meta property="og:description" content="Browse our collection of <?php echo htmlspecialchars($cat); ?> fashion items.">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://<?php echo $_SERVER['HTTP_HOST']; ?>/category.php<?php echo $categoryId ? '?id=' . $categoryId : ''; ?>">
  
  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="<?php echo htmlspecialchars($cat); ?>">
  <meta name="twitter:description" content="Shop <?php echo htmlspecialchars($cat); ?> at Esa's Fashion">
  
  <!-- 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">
</head>
<body>
<?php include __DIR__ . '/header.php'; ?>

<main class="container">
  <!-- Breadcrumb with Schema -->
  <?php
  // Build breadcrumb array
  $breadcrumbs = [
    ['title' => 'Home', 'url' => 'index.php'],
    ['title' => 'Shop', 'url' => 'shop.php']
  ];
  if ($categoryId !== null || $categoryName) {
    $breadcrumbs[] = ['title' => htmlspecialchars($cat), 'url' => null];
  }
  
  // Output breadcrumb with schema
  echo InternalLinkingHelper::generateBreadcrumb($breadcrumbs);
  echo InternalLinkingHelper::generateBreadcrumbSchema($breadcrumbs);
  ?>
  
  <!-- H1 Heading for SEO -->
  <?php echo h1('Shop ' . htmlspecialchars($cat)); ?>
  <p style="text-align: center; color: #666; margin-bottom: 30px; font-size: 15px;">Explore our collection of <?php echo htmlspecialchars($cat); ?> fashion items</p>
  
  <?php
  // Load products from JSON
  $products = [];
  $dataFile = __DIR__ . '/data/products.json';
  if (file_exists($dataFile)) {
    $json = file_get_contents($dataFile);
    $decoded = json_decode($json, true);
    if ($decoded === null) {
      error_log('JSON decode error in products.json: ' . json_last_error_msg());
      $products = [];
    } else {
      $products = $decoded ?: [];
    }
  }

  // Filter by category
  $filtered = array_filter($products, function($p) use ($cat, $categoryName){
    // Check by category name
    if (isset($p['cat']) && strtolower($p['cat']) === strtolower($cat)) {
      return true;
    }
    // Check by category slug
    if ($categoryName && isset($p['category']) && strtolower($p['category']) === strtolower($categoryName)) {
      return true;
    }
    return false;
  });

  if(empty($filtered)){
    echo '<p class="muted">No products in this category yet.</p>';
  } else {
    echo '<div class="product-grid" style="margin-top:14px;">';
    foreach($filtered as $p){
      echo '<div>';
      echo '<a class="product" href="product.php?id=' . $p['id'] . '">';
      $imageUrl = !empty($p['image']) ? getImageForSection($p['image'], 'shop') : 'pics_ecom/placeholder.png';
      $altText = ImageAltHelper::generateProductAlt($p['title'], $p['color'] ?? 'Various colors', 'Category');
      echo '<img src="' . htmlspecialchars($imageUrl) . '" alt="' . htmlspecialchars($altText) . '">';
      echo '<h3>' . htmlspecialchars($p['title']) . '</h3>';
      echo '<p class="price">$' . $p['price'] . '</p>';
      echo '</a>';
      if (!empty($_SESSION['user_id'])): ?>
        <form action="cart.php" method="post" style="margin-top:8px;">
          <input type="hidden" name="action" value="add">
          <input type="hidden" name="id" value="<?php echo $p['id']; ?>">
          <input type="hidden" name="qty" value="1">
          <button class="btn" type="submit">Add to Cart</button>
        </form>
      <?php else: ?>
        <p class="muted" style="margin-top:8px; font-size:13px;"><a href="index.php" style="color:#667eea;">Sign in</a> to add items to cart</p>
      <?php endif;
      echo '</div>';
    }
    echo '</div>';
  }
  ?>
</main>
<?php include __DIR__ . '/footer.php'; ?>
