<?php

declare(strict_types=1);

namespace KupShop\ConvertorsBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\ConvertorsBundle\Utils\ConvertorsUtil;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Excel\ExcelGenerator;
use KupShop\KupShopBundle\Util\Excel\ExcelHeaderBuilder;
use Query\Operator;

class FindProductsWithMissingConversionsScript extends Script
{
    protected static $name = 'Export produktý kterým chybí hodnota v převodnících';

    protected static $defaultParameters = [
        'filename' => 'data/files/missing.xlsx',
    ];

    protected function run(array $arguments)
    {
        $convertorsUtil = ServiceContainer::getService(ConvertorsUtil::class);

        $productIds = sqlQueryBuilder()->select('id_product, GROUP_CONCAT(id_table) tables')
            ->from('convertors_table_cache', 'ctc')
            ->innerJoin('ctc', 'products', 'p', 'p.id = ctc.id_product and p.figure = "Y"')
            ->groupBy('id_product');

        $countCache = [];
        $missing = [];
        foreach ($productIds->execute() as $id) {
            $variationsIds = sqlQueryBuilder()->select('id')
                ->from('products_variations')
                ->where(Operator::equals(['id_product' => $id['id_product']]))
                ->execute()->fetchFirstColumn();

            $tables = explode(',', $id['tables']);
            $out = [];
            $activeTables = [];
            foreach ($tables as $table) {
                $tableVal = $convertorsUtil->getTableValues($table, $variationsIds);
                // Pokud je na produktu label co na převodníku, tak zobraz převodní tabulku
                if (isset($tableVal['id_label'])) {
                    $out[$table] = $tableVal;
                    $activeTables[$tableVal['id_label']] = $table;
                }
            }

            foreach ($activeTables as $key) {
                $paramCount = count($out[$key]['parameters']);
                $current = $out[$key]['values'];
                // current[label_value][id_parameter][][]
                foreach ($current as $k => &$v) {
                    unset($v['id']);
                    // TODO: kolik jich je vyplnenejch
                    if (!isset($countCache[$id['id_product']])) {
                        $countCache[$id['id_product']] = 0;
                    }
                    $countCache[$id['id_product']] += count($v);
                    if (count($v) != $paramCount) {
                        $missing[$id['id_product']] = $id['id_product'];
                    }
                }
            }
        }

        $header = (new ExcelHeaderBuilder())
            ->string('ID produktu', 'id_product')
            ->string('Kód', 'code')
            ->string('Název produktu', 'title')
            ->int('Počet variant', 'count')
            ->string('URL', 'url')
            ->string('Admin URL', 'url_admin');

        $callback = function () use ($missing): \Generator {
            $qb = sqlQueryBuilder()->select('id id_product, title, code, c.c count, CONCAT("https://www.hanibal.cz/presmerovat/?type=product&id=", id_product) url, CONCAT("https://www.hanibal.cz/admin/launch.php?s=products.php&acn=edit&ID=", id_product, "&") url_admin')
                ->fromProducts()->where(Operator::inIntArray(array_keys($missing), 'id'))
                ->joinSubQuery('p', sqlQueryBuilder()->select('id_product,COUNT(id) c')->from('products_variations')->groupBy('id_product'), 'c', 'c.id_product=p.id')
                ->execute();

            foreach ($qb as $row) {
                yield $row;
            }
        };

        $string = ServiceContainer::getService(ExcelGenerator::class)->generateAsString($header->getHeader(), $callback());

        file_put_contents($arguments['filename'], $string);
    }
}

return FindProductsWithMissingConversionsScript::class;
