<?php

declare(strict_types=1);

namespace External\SprintBundle\Resources\script;

use Query\Operator;

class ImportRewriteScript extends \KupShop\AdminBundle\Util\Script\Script
{
    protected static $name = 'Import rewrite';

    protected static $defaultParameters = [
        'run' => false,
        'filename' => 'data/files/swixshop_cz_heureka.xml',
    ];

    protected function run(array $arguments)
    {
        if (!$arguments['run'] && !isLocalDevelopment()) {
            return;
        }

        $xml = simplexml_load_file($arguments['filename']);

        foreach ($xml->SHOPITEM as $item) {
            $url = rtrim($item->URL->__toString(), '/');
            $url = str_replace('https://ulvang.cz/', '', $url);

            if ($variations = sqlQueryBuilder()
                ->select('id,id_product')
                ->from('products_variations')
                ->where(Operator::equals([
                    'code' => $item->PRODUCTNO->__toString(),
                ]))
                ->setMaxResults(1)->execute()
                ->fetchAssociative()) {
                $type = 6;

                $productUrl = rtrim(strtok($url, '?'), '/');
                sqlQueryBuilder()
                    ->insert('rewrite')
                    ->directValues([
                        'type' => 0,
                        'url' => $productUrl,
                        'related_id' => $variations['id_product'],
                    ])
                    ->onDuplicateKeyUpdate(['id' => 'id'])
                    ->execute();
                $productId = $variations['id'];
            } elseif (
                $productId = sqlQueryBuilder()
                    ->select('id')
                    ->fromProducts()
                    ->where(Operator::equals([
                        'code' => $item->PRODUCTNO->__toString(),
                    ]))
                    ->execute()
                    ->fetchOne()) {
                $type = 0;
            }

            if (!$productId) {
                continue;
            }
            $productUrl = rtrim(strtok($url, '?'), '/');
            sqlQueryBuilder()
                ->insert('rewrite')
                ->directValues([
                    'type' => $type,
                    'url' => $productUrl,
                    'related_id' => $productId,
                ])
                ->onDuplicateKeyUpdate(['id' => 'id'])
                ->execute();
        }
    }
}

return ImportRewriteScript::class;
