<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Model\Product;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;

/** @var ListProduct $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */

// Debug output
echo "<!-- Schema template is being executed -->";

$productCollection = $block->getLoadedProductCollection();

// Debug product collection
echo "<!-- Product collection count: " . ($productCollection ? $productCollection->count() : 'null') . " -->";

// Hardcoded rating values for now - in a real implementation, these would be dynamic
$ratingValue = '4.6';
$reviewCount = '378';

// Get current date for priceValidUntil
$currentDate = new \DateTime();
$currentDate->modify('+1 year');
$priceValidUntil = $currentDate->format('Y-m-d');

$currencyCode = 'GBP';

// Debug output
echo "<!-- Product collection exists: " . ($productCollection ? 'yes' : 'no') . " -->";
echo "<!-- Product collection count: " . ($productCollection ? $productCollection->count() : 'null') . " -->";

// Always process, even if product collection is empty
// Get category name and URL
$category = $block->getLayer()->getCurrentCategory();
$categoryName = $category->getName();

    // Get min and max prices for the category
    $minPrice = PHP_FLOAT_MAX;
    $maxPrice = 0;
    $productCount = 0;

    foreach ($productCollection as $product) {
        $productPrice = $product->getFinalPrice();
        if ($productPrice < $minPrice) {
            $minPrice = $productPrice;
        }
        if ($productPrice > $maxPrice) {
            $maxPrice = $productPrice;
        }
        $productCount++;
    }

    // Format prices
    $minPrice = number_format($minPrice, 2, '.', '');
    $maxPrice = number_format($maxPrice, 2, '.', '');
?>
<?php
// Create category schema data array
$categorySchemaData = [
    "@context" => "http://schema.org",
    "@type" => "Product",
    "@id" =>  $category->getUrl(),
    "name" => $categoryName,
    "offers" => [
        "@type" => "AggregateOffer",
        "lowPrice" => $minPrice,
        "highPrice" => $maxPrice,
        "priceCurrency" => $currencyCode,
        "offerCount" => (string)$productCount
    ]
];

// Add aggregateRating only if ratings exist
if (!empty($ratingValue) && !empty($reviewCount) && $reviewCount > 0) {
    $categorySchemaData["aggregateRating"] = [
        "@type" => "AggregateRating",
        "ratingValue" => $ratingValue,
        "reviewCount" => $reviewCount,
        "bestRating" => "5"
    ];
}
?>
<!-- Product Rating Schema for Category Page -->
<script type="application/ld+json">
<?= json_encode($categorySchemaData) ?>
</script>

