<?php

namespace External\ZNZBundle\Resources\script;

use Doctrine\DBAL\Exception;
use KupShop\AdminBundle\Util\Script\Script;
use League\Csv\Reader;

class ImportRewritesScript extends Script
{
    protected static $name = '[ZNZ] Import rewrite';
    protected static $defaultParameters = [
        'file' => 'data/files/CDP.csv',
    ];

    protected function run(array $arguments)
    {
        $csv = Reader::createFromPath($arguments['file']);
        $csv->setHeaderOffset(0);

        $inserted = 0;
        $duplicated = 0;

        echo 'Progress: ';
        $this->log('Progress:');

        foreach ($csv->getRecords() as $item) {
            $this->progress();
            if (isset($item['id_path']) && strpos($item['id_path'], 'product/') === 0) {
                $type = 0;
                $id = $this->getProductIdFromSku($item['sku']);
                if (!$id) {
                    $type = 6;
                    $id = $this->getVariationIdFromSku($item['sku']);
                }

                if (!$id) {
                    continue;
                }

                try {
                    sqlQueryBuilder()
                        ->insert('rewrite')
                        ->directValues([
                            'url' => $item['request_path'],
                            'type' => $type,
                            'related_id' => $id,
                        ])->execute();
                    $inserted++;
                } catch (Exception\UniqueConstraintViolationException $e) {
                    $duplicated++;
                }
            }
        }

        $this->log('Inserted: '.$inserted);
        $this->log('Duplicated: '.$duplicated);
    }

    protected function getProductIdFromSku($sku)
    {
        return sqlQueryBuilder()
            ->select('p.id')
            ->fromProducts()
            ->where('p.code = :sku')
            ->setParameter('sku', $sku)
            ->execute()
            ->fetchOne();
    }

    protected function getVariationIdFromSku($sku)
    {
        return sqlQueryBuilder()
            ->select('pv.id')
            ->fromProducts()
            ->joinVariationsOnProducts()
            ->where('pv.code = :sku')
            ->setParameter('sku', $sku)
            ->execute()
            ->fetchOne();
    }
}

return ImportRewritesScript::class;
