<?php

namespace KupShop\ContentBundle\Sitemap;

use KupShop\CatalogBundle\Section\SectionTree;
use Query\Operator;

class ProducerSectionSitemap extends BaseSitemap
{
    protected static $type = 'producersection';
    protected static $module = 'producersection';
    protected $sectionTree;

    public function __construct(SectionTree $sectionTree)
    {
        $this->sectionTree = $sectionTree;
    }

    public function getData(): \Generator
    {
        $producerSectionList = sqlQueryBuilder()
            ->select('pis.id_section, p.producer, s.name, pr.name as producer_name')
            ->from('products_in_sections', 'pis')
            ->leftJoin('pis', 'products', 'p', 'p.id = pis.id_product')
            ->leftJoin('pis', 'sections', 's', 's.id = pis.id_section')
            ->innerJoin('p', 'producers', 'pr', 'pr.id = p.producer')
            ->where(Operator::equals(['pis.figure' => 'Y', 'pr.active' => 'Y']))
            ->andWhere('p.producer IS NOT NULL')
            ->groupBy('pis.id_section, p.producer')
            ->orderBy('pis.id_section')->execute();
        foreach ($producerSectionList as $producerSection) {
            $section = $this->sectionTree->getSectionById($producerSection['id_section']);
            yield [
                'loc' => createScriptURL([
                    'URL' => 'launch.php',
                    's' => 'category',
                    'IDcat' => $producerSection['id_section'],
                    'IDpd' => $producerSection['producer'],
                    'IDpv' => null,
                    'TITLE' => $producerSection['name'],
                    'producerTitle' => $producerSection['producer_name'] ?? null,
                    'ESCAPE' => 'NO',
                    'parents' => key($section->getParents()),
                    'campaign' => null,
                    'absolute' => true,
                ]),
                'priority' => '0.7',
                'changefreq' => 'monthly',
            ];
        }
    }

    public static function isAllowed(): bool
    {
        return (bool) findModule('sitemap', 'generate_producers_sections');
    }
}
