<?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 */

$productCollection = $block->getLoadedProductCollection();

// 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';

// Only process if we have products
if ($productCollection->count() > 0):
    // 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",
    "name" => $categoryName,
    "offers" => [
        "@type" => "AggregateOffer",
        "lowPrice" => $minPrice,
        "highPrice" => $maxPrice,
        "priceCurrency" => $currencyCode,
        "offerCount" => (string)$productCount
    ],
    "aggregateRating" => [
        "@type" => "AggregateRating",
        "ratingValue" => $ratingValue,
        "reviewCount" => $reviewCount,
        "bestRating" => "5"
    ]
];
?>
<!-- Product Rating Schema for Category Page -->
<script type="application/ld+json">
<?= json_encode($categorySchemaData) ?>
</script>

<?php
// Create individual product schema data array
$productGraphData = [
    "@context" => "https://schema.org",
    "@graph" => []
];

$productCount = 0;
$totalProducts = count($productCollection->getItems());

/** @var Product $product */
foreach ($productCollection->getItems() as $product) {
    $productCount++;

    // Get product data
    $productName = $product->getName();
    $productSku = $product->getSku();
    $productDescription = $product->getShortDescription() ? strip_tags($product->getShortDescription()) : '';

    // Get product brand
    $brandName = '';
    $brandAttribute = $product->getResource()->getAttribute('manufacturer');
    if ($brandAttribute) {
        $brandName = $brandAttribute->getFrontend()->getValue($product);
    }

    // Get product image
    $productImage = '';
    if ($product->getMediaGalleryImages()->count() > 0) {
        $productImage = $product->getMediaGalleryImages()->getFirstItem()->getUrl();
    }
    if (!$productImage && $product->getImage()) {
        $productImage = $block->getUrl('pub/media/catalog/product') . $product->getImage();
    }

    // Get product URL
    $productUrl = $product->getProductUrl();

    // Get product price
    $productPrice = $product->getFinalPrice();

    // Get product availability
    $availability = $product->isAvailable() ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock';

    // Create product schema
    $productSchema = [
        "@type" => "Product",
        "name" => $productName,
        "sku" => $productSku,
        "brand" => [
            "@type" => "Brand",
            "name" => $brandName ?: 'Banyo'
        ],
        "aggregateRating" => [
            "@type" => "AggregateRating",
            "ratingValue" => $ratingValue,
            "reviewCount" => $reviewCount
        ],
        "offers" => [
            "@type" => "Offer",
            "url" => $productUrl,
            "price" => number_format($productPrice, 2, '.', ''),
            "priceCurrency" => $currencyCode,
            "priceValidUntil" => $priceValidUntil,
            "sku" => $productSku,
            "availability" => $availability
        ]
    ];

    // Add image if available
    if ($productImage) {
        $productSchema["image"] = $productImage;
    }

    // Add description if available
    if ($productDescription) {
        $productSchema["description"] = $productDescription;
    }

    // Add to graph
    $productGraphData["@graph"][] = $productSchema;
}
?>
<!-- Individual Product Schema -->
<script type="application/ld+json">
<?= json_encode($productGraphData) ?>
</script>
<?php endif; ?>
