<?php
require_once 'includes/header.php';

// Get category slug from URL
$category_slug = isset($_GET['category']) ? $_GET['category'] : '';

// If no category slug provided, redirect to homepage
if (empty($category_slug)) {
    header('Location: /');
    exit;
}

// Get category data
$category = get_category_by_slug($category_slug);

// If category not found, show 404 page
if (!$category) {
    http_response_code(404);
    include '404.php';
    exit;
}

// Default sorting by price ascending
$order_by = "CASE WHEN p.sale_price > 0 THEN p.sale_price ELSE p.price END ASC";

// Get ALL products in this category (bez paginacije)
$products = get_rows("
    SELECT p.*, 
    (SELECT image FROM product_images pi WHERE pi.product_id = p.id ORDER BY pi.sort_order ASC LIMIT 1) as image,
    (SELECT name FROM categories c WHERE c.id = ?) as category_name
    FROM products p
    JOIN product_categories pc ON p.id = pc.product_id
    WHERE pc.category_id = ? AND p.status = 'active'
    ORDER BY $order_by
", [$category['id'], $category['id']]);

// Get child categories if any
$child_categories = get_rows("
    SELECT * FROM categories 
    WHERE parent_id = ? 
    ORDER BY name ASC
", [$category['id']]);

// Generate meta tags
$meta_title = !empty($category['meta_title']) ? $category['meta_title'] : $category['name'] . ' - ' . get_setting('site_name');
$meta_description = !empty($category['meta_description']) ? $category['meta_description'] : 'Pogledajte našu ponudu ' . $category['name'] . ' - kvalitetni Hugong aparati za zavarivanje uz besplatnu dostavu.';
?>

<!-- Breadcrumbs -->
<div class="breadcrumbs">
    <div class="container">
        <ul class="breadcrumb-list">
            <li><a href="/">Početna</a></li>
            <?php if (!empty($category['parent_id'])): 
                $parent = get_category($category['parent_id']); ?>
                <li><a href="/<?php echo $parent['slug']; ?>"><?php echo $parent['name']; ?></a></li>
            <?php endif; ?>
            <li class="active"><?php echo $category['name']; ?></li>
        </ul>
    </div>
</div>

<!-- Category Header -->
<div class="category-header">
    <div class="container">
        <h1 class="category-title"><?php echo $category['name']; ?></h1>
        
        <?php if (!empty($category['description'])): ?>
        <div class="category-description">
            <?php echo $category['description']; ?>
        </div>
        <?php endif; ?>
        
        <?php if (!empty($child_categories)): ?>
        <div class="subcategories-section">
            <div class="categories-grid">
                <?php foreach ($child_categories as $subcategory): ?>
                <div class="category-card">
                    <div class="category-image">
                        <?php if (!empty($subcategory['image'])): ?>
                        <img src="<?php echo UPLOADS_URL . '/categories/' . $subcategory['image']; ?>" alt="<?php echo $subcategory['name']; ?>">
                        <?php else: ?>
                        <img src="/assets/images/no-category-image.jpg" alt="<?php echo $subcategory['name']; ?>">
                        <?php endif; ?>
                    </div>
                    
                    <div class="category-info">
                        <h3 class="category-name"><?php echo $subcategory['name']; ?></h3>
                    </div>
                    
                    <a href="/<?php echo $subcategory['slug']; ?>" class="category-button">
                        POGLEDAJ SVE
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <polyline points="9 18 15 12 9 6"></polyline>
                        </svg>
                    </a>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Product Listing -->
<section class="sale-products-section">
    <div class="container">
        <?php if (!empty($products)): ?>
        <div class="recommended-products-container">
            <div class="recommended-products-wrapper">
                <div class="product-grid">
                    <?php foreach ($products as $product): ?>
                    <div class="product-card">
    <?php if (!empty($product['sale_price'])): 
        $discount_percent = round((($product['price'] - $product['sale_price']) / $product['price']) * 100);
    ?>
    <div class="product-discount">-<?php echo $discount_percent; ?>%</div>
    <?php endif; ?>
    <a href="/<?php echo $product['slug']; ?>" class="card-link-overlay"></a>
    
    <div class="product-image">
        <?php if (!empty($product['image'])): ?>
        <img src="<?php echo UPLOADS_URL . '/products/' . $product['image']; ?>" alt="<?php echo $product['name']; ?>" loading="lazy">
        <?php else: ?>
        <img src="/assets/images/no-image.jpg" alt="<?php echo $product['name']; ?>" loading="lazy">
        <?php endif; ?>
    </div>
    
    <div class="product-details">
        <div class="product-category"><?php echo $category['name']; ?></div>
        <h3 class="product-name"><?php echo $product['name']; ?></h3>
        
        <div class="product-price <?php echo !empty($product['sale_price']) ? 'sale-price' : ''; ?>">
            <?php if (!empty($product['sale_price'])): ?>
            <span class="price-old"><?php echo number_format($product['price'], 0, ',', '.'); ?> RSD</span>
            <span class="price-current"><?php echo number_format($product['sale_price'], 0, ',', '.'); ?> RSD</span>
            <?php else: ?>
            <span class="price-current"><?php echo number_format($product['price'], 0, ',', '.'); ?> RSD</span>
            <?php endif; ?>
        </div>
        
        <span class="btn-view">VIDI VIŠE <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="9 18 15 12 9 6"></polyline>
        </svg></span>
    </div>
</div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php else: ?>
            <div class="no-products">
                <h2>Nema proizvoda u ovoj kategoriji</h2>
                <p>Trenutno nema dostupnih proizvoda u kategoriji <?php echo $category['name']; ?>.</p>
                <a href="/" class="btn-primary">Povratak na početnu</a>
            </div>
        <?php endif; ?>
    </div>
</section>

<!-- Na kraju stranice pre footer-a -->
<?php if (!empty($category['seo_content'])): ?>
<div class="category-seo-content">
    <div class="container">
        <h2><?php echo $category['name']; ?> - Dodatne informacije</h2>
        <div class="content">
            <?php echo $category['seo_content']; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Schema.org structured data -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "CollectionPage",
  "name": "<?php echo htmlspecialchars($category['name']); ?>",
  "description": "<?php echo htmlspecialchars(strip_tags($category['description'] ?? '')); ?>",
  "url": "<?php echo SITE_URL . '/' . $category_slug; ?>",
  "mainEntity": {
    "@type": "ItemList",
    "itemListElement": [
      <?php $i = 0; foreach($products as $product): $i++; ?>
      {
        "@type": "ListItem",
        "position": <?php echo $i; ?>,
        "item": {
          "@type": "Product",
          "name": "<?php echo htmlspecialchars($product['name']); ?>",
          "url": "<?php echo SITE_URL . '/' . $product['slug']; ?>",
          "image": "<?php echo !empty($product['image']) ? UPLOADS_URL . '/products/' . $product['image'] : SITE_URL . '/assets/images/no-image.jpg'; ?>",
          "offers": {
            "@type": "Offer",
            "price": "<?php echo $product['sale_price'] ? $product['sale_price'] : $product['price']; ?>",
            "priceCurrency": "RSD",
            "availability": "https://schema.org/InStock"
          }
        }
      }<?php echo ($i < count($products)) ? ',' : ''; ?>
      <?php endforeach; ?>
    ]
  }
}
</script>

<?php require_once 'includes/footer.php'; ?>