<?php

declare(strict_types=1);

namespace External\HannahBundle\Resources\script;

use External\HannahBundle\SAP\Util\SAPUtil;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\FileUtil;
use KupShop\KupShopBundle\Util\System\PathFinder;
use KupShop\RewriteBundle\Util\Rewrite;
use Query\Operator;

class ImportRewriteScript extends Script
{
    protected static $name = 'Import rewrite';

    protected static $defaultParameters = [
        'file' => 'files/rockpoint_urls.csv',
    ];

    protected function run(array $arguments)
    {
        $this->processUrls($arguments);
    }

    private function processUrls(array $arguments): void
    {
        $pathFinder = PathFinder::getService();
        $rewrite = ServiceContainer::getService(Rewrite::class);

        $count = 0;
        foreach (FileUtil::loadCSV($pathFinder->dataPath($arguments['file'])) as $key => $item) {
            if ($key == 0) {
                continue;
            }

            $url = $item[1];
            $target = $item[2];

            $rewrite->addRewrite($url, Rewrite::TYPE_CUSTOM, $target);
            $count++;
        }

        $this->log('Rewrites added:', $count);
    }

    private function processProductUrls(array $arguments): void
    {
        $pathFinder = PathFinder::getService();

        $rewrite = ServiceContainer::getService(Rewrite::class);
        $sapUtil = ServiceContainer::getService(SAPUtil::class);

        $count = 0;
        foreach ($this->loadCSV($pathFinder->dataPath($arguments['file'])) as $key => $item) {
            if ($key == 0) {
                continue;
            }

            $code = $item[0];
            $codeShort = substr($code, 0, -2);
            $url = str_replace('https://www.rockpoint.cz/', '', $item[1]);

            if (!($mapping = $sapUtil->getItemMapping($code))) {
                $productId = sqlQueryBuilder()
                    ->select('id')
                    ->from('products')
                    ->where(
                        Operator::orX(
                            Operator::equals(['code' => $code]),
                            Operator::equals(['code' => $codeShort]),
                            'data LIKE :code'
                        )
                    )
                    ->setParameter('code', '%'.$code.'%')
                    ->execute()->fetchOne();

                if ($productId) {
                    $mapping = [(int) $productId, null];
                }
            }

            if (!$mapping) {
                continue;
            }

            [$productId, $_] = $mapping;

            $rewrite->addRewrite($url, Rewrite::TYPE_PRODUCT, $productId);

            $count++;
        }

        $this->log('Rewrites added:', $count);
    }

    private function loadCSV(string $file): array
    {
        $file = fopen($file, 'r');
        $return = [];
        $index = 0;
        while (($data = fgetcsv($file, 0, ',')) !== false) {
            if ($index++ === 0) {
                continue;
            }

            $return[] = $data;
        }

        return $return;
    }
}

return ImportRewriteScript::class;
