<?php

namespace KupShop\ComponentsBundle\Twig\Components\Section;

use KupShop\CatalogBundle\BaseFilterParams;
use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\GTM\PageViews\Section;
use KupShop\ComponentsBundle\GTM\PostMount\GTMViewData;
use KupShop\ComponentsBundle\Interfaces\Microdata;
use KupShop\ComponentsBundle\Twig\Components\FilteredProductList;
use KupShop\ComponentsBundle\Twig\DataProvider\MicrodataProvider;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Section/View/View.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class View extends FilteredProductList implements Microdata
{
    use GTMViewData;

    private BaseFilterParams $baseFilterWrapper;

    protected bool $isBaseView = true;

    #[Required]
    public Section $gtmClass;

    protected function getRatingsStats()
    {
        return sqlQueryBuilder()->select('COUNT(*) as count, AVG(r.rating) as rating')
             ->from('reviews', 'r')
            ->execute()->fetchAssociative();
    }

    public function initMicrodata(): array
    {
        if (findModule(\Modules::REVIEWS) && $rating = $this->getRatingsStats()) {
            if (($rating['rating'] ?? 0) >= 4 && ($rating['count'] ?? 0) >= 5) {
                $dbcfg = \Settings::getDefault();

                return [MicrodataProvider::PRODUCT => [
                    '@context' => 'http://schema.org',
                    '@type' => 'Product',
                    'name' => $dbcfg['shop_firm_name'],
                    'aggregateRating' => [
                        '@type' => 'AggregateRating',
                        'ratingValue' => round($rating['rating']),
                        'reviewCount' => $rating['count'],
                    ],
                ],
                ];
            }
        }

        return [];
    }
}
