<?php

namespace Autogedal\Extend\Cron;

use Magento\Framework\App\ResourceConnection;
use Magento\Store\Model\StoreManagerInterface;
use Magento\UrlRewrite\Model\UrlFinderInterface;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use Magento\Framework\UrlInterface;
use Amasty\ShopbySeo\Helper\Url as SeoUrlHelper;
use Psr\Log\LoggerInterface;

class RefreshGreenValleyPages
{
    const CATEGORY_ID   = 2161;
    const BRAND_ATTR_ID = 747;
    const MODEL_ATTR_ID = 748;
    const BRAND_CODE    = 'auto_brand';
    const MODEL_CODE    = 'auto_model';

    const POPULAR_BRANDS = [
        'Audi', 'BMW', 'Citroen', 'Dacia', 'Fiat', 'Ford',
        'Mercedes', 'Opel', 'Peugeot', 'Renault', 'Skoda', 'Toyota', 'Volkswagen'
    ];

    const POPULAR_MODELS = [
        ['brand' => 'Audi',       'model' => 'A4'],
        ['brand' => 'Audi',       'model' => 'A6'],
        ['brand' => 'BMW',        'model' => 'Seria 5'],
        ['brand' => 'BMW',        'model' => 'X3'],
        ['brand' => 'Dacia',      'model' => 'Duster'],
        ['brand' => 'Dacia',      'model' => 'Logan'],
        ['brand' => 'Ford',       'model' => 'Focus'],
        ['brand' => 'Ford',       'model' => 'Mondeo'],
        ['brand' => 'Hyundai',    'model' => 'Santa Fe'],
        ['brand' => 'Hyundai',    'model' => 'Tucson'],
        ['brand' => 'Kia',        'model' => 'Sportage'],
        ['brand' => 'Nissan',     'model' => 'Navara'],
        ['brand' => 'Opel',       'model' => 'Astra'],
        ['brand' => 'Opel',       'model' => 'Corsa'],
        ['brand' => 'Renault',    'model' => 'Captur'],
        ['brand' => 'Renault',    'model' => 'Clio'],
        ['brand' => 'Renault',    'model' => 'Megane'],
        ['brand' => 'Renault',    'model' => 'Scenic'],
        ['brand' => 'Seat',       'model' => 'Ibiza'],
        ['brand' => 'Skoda',      'model' => 'Fabia'],
        ['brand' => 'Skoda',      'model' => 'Octavia'],
        ['brand' => 'Skoda',      'model' => 'Superb'],
        ['brand' => 'Suzuki',     'model' => 'Vitara'],
        ['brand' => 'Toyota',     'model' => 'Corolla'],
        ['brand' => 'Toyota',     'model' => 'Rav4'],
        ['brand' => 'Volkswagen', 'model' => 'Golf'],
        ['brand' => 'Volkswagen', 'model' => 'Passat'],
        ['brand' => 'Volvo',      'model' => 'XC40'],
        ['brand' => 'Volvo',      'model' => 'XC60'],
    ];

    private $resource;
    private $storeManager;
    private $urlFinder;
    private $seoUrlHelper;
    private $logger;

    private $connection;
    private $baseUrl;
    private $catUrlPath;
    private $statusAttrId;

    public function __construct(
        ResourceConnection $resource,
        StoreManagerInterface $storeManager,
        UrlFinderInterface $urlFinder,
        SeoUrlHelper $seoUrlHelper,
        LoggerInterface $logger
    ) {
        $this->resource     = $resource;
        $this->storeManager = $storeManager;
        $this->urlFinder    = $urlFinder;
        $this->seoUrlHelper = $seoUrlHelper;
        $this->logger       = $logger;
    }

    public function execute()
    {
        $this->logger->info('RefreshGreenValleyPages: start');

        $this->connection = $this->resource->getConnection();
        $pageTable        = $this->resource->getTableName('amasty_amshopby_page');

        $this->statusAttrId = (int)$this->connection->fetchOne(
            "SELECT attribute_id FROM " . $this->resource->getTableName('eav_attribute') .
            " WHERE attribute_code = 'status' AND entity_type_id = 4"
        );

        /** @var \Magento\Store\Model\Store $store */
        $store   = $this->storeManager->getStore(1);
        $storeId = $store->getId();
        $this->storeManager->setCurrentStore($storeId);
        $this->baseUrl = rtrim($store->getBaseUrl(UrlInterface::URL_TYPE_WEB), '/');

        $rewrite = $this->urlFinder->findOneByData([
            UrlRewrite::ENTITY_TYPE   => 'category',
            UrlRewrite::ENTITY_ID     => self::CATEGORY_ID,
            UrlRewrite::STORE_ID      => $storeId,
            UrlRewrite::REDIRECT_TYPE => 0,
        ]);
        $this->catUrlPath = $rewrite
            ? str_replace('.html', '', $rewrite->getRequestPath())
            : 'bare-transversale';

        // Construieste URL map-urile filtrând doar branduri/modele cu produse active
        $brandUrlMap = $this->buildBrandUrlMap();
        $modelUrlMap = $this->buildModelUrlMap();

        $faqHtml     = $this->getFaqHtml();
        $updated     = 0;
        $skipped     = 0;

        // Itereaza toate brandurile cu produse active in categorie
        $brands = $this->getActiveBrands();

        foreach ($brands as $brand) {
            $brandId   = $brand['option_id'];
            $brandName = $brand['brand_name'];

            $conditions = json_encode([
                json_encode(['filter' => (string)self::BRAND_ATTR_ID, 'value' => (string)$brandId])
            ]);

            $pageId = $this->connection->fetchOne(
                $this->connection->select()
                    ->from($pageTable, 'page_id')
                    ->where('conditions = ?', $conditions)
                    ->where('FIND_IN_SET(?, categories)', self::CATEGORY_ID)
            );

            if (!$pageId) {
                $skipped++;
                continue;
            }

            $description = $this->buildDescription($brandName, $brandUrlMap, $modelUrlMap, $faqHtml);

            $this->connection->update(
                $pageTable,
                ['description' => $description],
                ['page_id = ?' => $pageId]
            );
            $updated++;
        }

        $this->logger->info("RefreshGreenValleyPages: done. Updated=$updated Skipped=$skipped");
    }

    private function getActiveBrands()
    {
        return $this->connection->fetchAll(
            $this->connection->select()
                ->from(['pei' => $this->resource->getTableName('catalog_product_entity_varchar')], [])
                ->joinInner(
                    ['eaov' => $this->resource->getTableName('eav_attribute_option_value')],
                    'eaov.option_id = pei.value AND eaov.store_id = 0',
                    ['option_id' => 'pei.value', 'brand_name' => 'eaov.value']
                )
                ->joinInner(
                    ['ccp' => $this->resource->getTableName('catalog_category_product')],
                    'ccp.product_id = pei.entity_id',
                    []
                )
                ->joinInner(
                    ['cpe_status' => $this->resource->getTableName('catalog_product_entity_int')],
                    'cpe_status.entity_id = pei.entity_id AND cpe_status.attribute_id = ' . $this->statusAttrId . ' AND cpe_status.store_id = 0 AND cpe_status.value = 1',
                    []
                )
                ->where('pei.attribute_id = ?', self::BRAND_ATTR_ID)
                ->where('ccp.category_id = ?', self::CATEGORY_ID)
                ->group('pei.value')
                ->order('eaov.value ASC')
        );
    }

    private function hasActiveProducts($brandOptionId, $modelOptionId = null)
    {
        $select = $this->connection->select()
            ->from(['pei_b' => $this->resource->getTableName('catalog_product_entity_varchar')], ['COUNT(DISTINCT pei_b.entity_id)'])
            ->joinInner(
                ['ccp' => $this->resource->getTableName('catalog_category_product')],
                'ccp.product_id = pei_b.entity_id',
                []
            )
            ->joinInner(
                ['cpe_status' => $this->resource->getTableName('catalog_product_entity_int')],
                'cpe_status.entity_id = pei_b.entity_id AND cpe_status.attribute_id = ' . $this->statusAttrId . ' AND cpe_status.store_id = 0 AND cpe_status.value = 1',
                []
            )
            ->where('pei_b.attribute_id = ?', self::BRAND_ATTR_ID)
            ->where('pei_b.value = ?', $brandOptionId)
            ->where('ccp.category_id = ?', self::CATEGORY_ID);

        if ($modelOptionId !== null) {
            $select->joinInner(
                ['pei_m' => $this->resource->getTableName('catalog_product_entity_varchar')],
                'pei_m.entity_id = pei_b.entity_id AND pei_m.attribute_id = ' . self::MODEL_ATTR_ID . ' AND pei_m.value = ' . (int)$modelOptionId,
                []
            );
        }

        return (int)$this->connection->fetchOne($select) > 0;
    }

    private function getOptionIdByLabel($attrId, $label)
    {
        return $this->connection->fetchOne(
            $this->connection->select()
                ->from(['eaov' => $this->resource->getTableName('eav_attribute_option_value')], ['eaov.option_id'])
                ->joinInner(
                    ['eao' => $this->resource->getTableName('eav_attribute_option')],
                    'eao.option_id = eaov.option_id AND eao.attribute_id = ' . (int)$attrId,
                    []
                )
                ->where('eaov.store_id = 0')
                ->where('eaov.value = ?', $label)
                ->limit(1)
        ) ?: null;
    }

    private function buildBrandUrlMap()
    {
        $map = [];
        foreach (self::POPULAR_BRANDS as $brandName) {
            $optionId = $this->getOptionIdByLabel(self::BRAND_ATTR_ID, $brandName);
            if (!$optionId || !$this->hasActiveProducts($optionId)) {
                continue; // brand fara produse active — skip
            }
            $rawUrl    = $this->baseUrl . '/' . $this->catUrlPath . '/?' . self::BRAND_CODE . '=' . $optionId;
            $map[$brandName] = $this->seoUrlHelper->seofyUrl($rawUrl, self::CATEGORY_ID, true) . '.html';
        }
        return $map;
    }

    private function buildModelUrlMap()
    {
        $map = [];
        foreach (self::POPULAR_MODELS as $item) {
            $brandOptionId = $this->getOptionIdByLabel(self::BRAND_ATTR_ID, $item['brand']);
            $modelOptionId = $this->getOptionIdByLabel(self::MODEL_ATTR_ID, $item['model']);
            if (!$brandOptionId || !$modelOptionId || !$this->hasActiveProducts($brandOptionId, $modelOptionId)) {
                continue; // combinatie fara produse active — skip
            }
            $key    = $item['brand'] . '|' . $item['model'];
            $rawUrl = $this->baseUrl . '/' . $this->catUrlPath . '/?'
                . self::BRAND_CODE . '=' . $brandOptionId
                . '&' . self::MODEL_CODE . '=' . $modelOptionId;
            $map[$key] = $this->seoUrlHelper->seofyUrl($rawUrl, self::CATEGORY_ID, true) . '.html';
        }
        return $map;
    }

    private function buildDescription($brandName, array $brandUrlMap, array $modelUrlMap, $faqHtml)
    {
        $currentBrandLower = strtolower($brandName);

        $brandsHtml = '';
        foreach (self::POPULAR_BRANDS as $b) {
            if (strtolower($b) === $currentBrandLower) continue;
            if (!isset($brandUrlMap[$b])) continue; // nu are produse active
            $url = htmlspecialchars($brandUrlMap[$b]);
            $brandsHtml .= '<a class="il-brand-card" href="' . $url . '">' . $b . '</a> ';
        }

        $modelsHtml = '';
        foreach (self::POPULAR_MODELS as $item) {
            if (strtolower($item['brand']) === $currentBrandLower) continue;
            $key = $item['brand'] . '|' . $item['model'];
            if (!isset($modelUrlMap[$key])) continue; // nu are produse active
            $url = htmlspecialchars($modelUrlMap[$key]);
            $modelsHtml .= '<a class="il-model-card" href="' . $url . '">'
                . '<div class="il-model-brand">' . $item['brand'] . '</div>'
                . '<div class="il-model-name">' . $item['model'] . '</div>'
                . '</a>';
        }

        $css = '<style>
.il-section{margin:40px 0}.il-block{margin-bottom:40px}.il-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.il-header-left{display:flex;align-items:center;gap:12px}.il-title{font-size:22px;font-weight:700;color:#1a1a1a;margin:0}.il-badge{background:#d1fae5;color:#065f46;font-size:11px;font-weight:600;letter-spacing:.5px;padding:3px 10px;border-radius:20px;text-transform:uppercase}.il-subtitle{font-size:13px;color:#9ca3af}.il-brands-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:8px}.il-brand-card{background:#f3f4f6;border-radius:8px;padding:14px 16px;text-decoration:none;display:block;border:2px solid transparent;transition:border-color .2s,background .2s;font-size:15px;font-weight:500;color:#1a1a1a}.il-brand-card:hover{border-color:#e53e3e;background:#fff;text-decoration:none;color:#1a1a1a}.il-models-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.il-model-card{background:#f3f4f6;border-radius:10px;padding:14px 18px;text-decoration:none;display:block;border:2px solid transparent;transition:border-color .2s,background .2s}.il-model-card:hover{border-color:#e53e3e;background:#fff;text-decoration:none}.il-model-brand{font-size:11px;font-weight:600;letter-spacing:.8px;text-transform:uppercase;color:#6b7280;margin-bottom:4px}.il-model-name{font-size:18px;font-weight:700;color:#111827}@media(max-width:767px){.il-brands-grid{grid-template-columns:repeat(3,1fr)}.il-models-grid{grid-template-columns:repeat(2,1fr)}.il-subtitle{display:none}}
</style>';

        return $css . '
<div class="il-section">
<div class="il-block">
<div class="il-header">
<div class="il-header-left"><h3 class="il-title">Alte mărci populare</h3></div>
</div>
<div class="il-brands-grid">' . $brandsHtml . '</div>
</div>
<div class="il-block">
<div class="il-header">
<div class="il-header-left"><h3 class="il-title">Modele populare de la alte mărci</h3></div>
</div>
<div class="il-models-grid">' . $modelsHtml . '</div>
</div>
</div>
' . $faqHtml;
    }

    private function getFaqHtml()
    {
        return '
<h2 style="font-size: 2.2rem;">Intrebari frecvente</h2>
<div class="faq-container">
    <div class="faq-item">
        <div class="faq-question"><h3>Aveti transport gratuit?</h3></div>
        <div class="faq-answer"><p>Nu. Taxele de transport variaza in functie de categoria produselor si sunt cuprinse intre 20 si 49 lei.</p></div>
    </div>
    <div class="faq-item">
        <div class="faq-question"><h3>Exista campanii de reduceri?</h3></div>
        <div class="faq-answer"><p>Da, derulam frecvent campanii de reduceri pentru diverse categorii de produse. Reducerile aplicate variaza, acestea putand ajunge pana la 40-50%. Urmareste site-ul nostru pentru a fi la curent cu ofertele.</p></div>
    </div>
    <div class="faq-item">
        <div class="faq-question"><h3>Care este politica de retur si cat dureaza rambursarea banilor?</h3></div>
        <div class="faq-answer"><p>Returul produselor se poate efectua in termen de 14 zile de la primirea acestora, indiferent de motivul returnarii. Viramentul bancar pentru contravaloarea produselor trimise si acceptate la retur se efectueaza in termen de maximum 14 zile de la momentul notificarii cu privire la decizia returnarii produselor, daca produsele sunt trimise inapoi inainte de expirarea perioadei de 14 zile. Mai multe detalii cu privire la politica de retur se regasesc aici: <a href="https://www.autogedal.ro/retur/">Retur</a></p></div>
    </div>
    <div class="faq-item">
        <div class="faq-question"><h3>Cum pot solicita un retur?</h3></div>
        <div class="faq-answer"><p>Pentru a solicita un retur, completeaza formularul disponibil pe site: <a href="https://www.autogedal.ro/retur/">Retur</a></p></div>
    </div>
    <div class="faq-item">
        <div class="faq-question"><h3>Ce metode de plata sunt disponibile?</h3></div>
        <div class="faq-answer"><p>Poti plati ramburs la curier, online cu cardul, in 3 rate fara dobanda (cu card de cumparaturi eligibil) sau prin ordin de plata pe baza unei facturi proforme. La selectarea platii online cu cardul, procesatorul de plati va permite inclusiv plata prin Apple Pay sau Google Pay.</p></div>
    </div>
    <div class="faq-item">
        <div class="faq-question"><h3>Pot plati in rate?</h3></div>
        <div class="faq-answer"><p>Da, poti plati in 3 rate fara dobanda, daca folosesti un <a href="https://www.autogedal.ro/cms/cum-platesc">card de cumparaturi eligibil</a> (Card Avantaj - Credit Europe Bank; Card StarBT - Banca Transilvania; Bonus Card - Garanti Bank; Card Cumparaturi - Alpha Bank; Card BRD Finance).</p></div>
    </div>
    <div class="faq-item">
        <div class="faq-question"><h3>Cum imi pot urmari coletul?</h3></div>
        <div class="faq-answer"><p>Dupa finalizarea comenzii vei primi un email cu nr de AWB al coletului si firma de curierat prin care a fost expediat coletul.</p></div>
    </div>
    <div class="faq-item">
        <div class="faq-question"><h3>Cat dureaza livrarea?</h3></div>
        <div class="faq-answer"><p>De regula, livrarea se face in 1-3 zile lucratoare, in functie de adresa de destinatie. Pentru anumite categorii de produse (precum carligele de remorcare marca Aragon), livrarea se poate prelungi pana la 7-9 zile lucratoare.</p></div>
    </div>
    <div class="faq-item">
        <div class="faq-question"><h3>Cum sunt protejate datele mele personale?</h3></div>
        <div class="faq-answer"><p>Protejam datele tale personale conform Regulamentului (UE) 2016/679 (GDPR). Nu transmitem (prin vanzare sau inchiriere) catre terte parti informatiile cu caracter personal. Ai dreptul de a solicita oricand stergerea informatiilor cu caracter personal existente in baza noastra de date. Poti consulta politica noastra completa de confidentialitate aici: <a href="https://www.autogedal.ro/politica-de-confidentialitate/">Politica de confidentialitate</a></p></div>
    </div>
</div>';
    }
}
