<?php

declare(strict_types=1);

namespace External\HannahBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\PricelistBundle\Util\PriceListWorker;
use Query\Operator;

class ImportEURPricesScript extends Script
{
    protected static $name = '[outdoor] Import EUR cen';
    protected static $defaultParameters = [
        'pathToFile' => 'data/files/eur_prices.csv',
    ];

    protected function run(array $arguments)
    {
        $file = file_get_contents($arguments['pathToFile']);
        $lines = explode("\n", $file);

        $priceListWorker = ServiceContainer::getService(PriceListWorker::class);

        $priceListId = $this->getPriceListId('EUR1');
        foreach ($lines as $i => $line) {
            if ($i == 0) {
                continue;
            }

            $elements = explode(';', $line);
            if ($elements[0] == '') {
                continue;
            }

            $elements[6] = str_replace(',', '.', $elements[6]);
            $materialCode = $elements[1];
            $dateSince = $elements[4];
            $price = toDecimal(str_replace(',', '.', $elements[6]));

            if (!($product = $this->getProduct($materialCode))) {
                continue;
            }

            [$productId, $variationId] = $product;

            if ($vat = $this->getProductVat($productId)) {
                $vat = toDecimal($vat)->add(\DecimalConstants::hundred())->div(\DecimalConstants::hundred());
                $price = $price->div($vat);
            }

            $priceListWorker->updatePriceList(
                (int) $priceListId,
                $productId,
                $variationId,
                $price
            );

            $variationQb = sqlQueryBuilder()
                ->select('id')
                ->from('products_variations')
                ->where(Operator::equals(['id_product' => $productId]));

            foreach ($variationQb->execute() as $item) {
                $priceListWorker->updatePriceList(
                    (int) $priceListId,
                    $productId,
                    (int) $item['id'],
                    $price
                );
            }
        }
    }

    protected function getPriceListId($name)
    {
        $qb = sqlQueryBuilder()
            ->select('id')
            ->from('pricelists')
            ->where(Operator::equals([
                'name' => $name,
            ]))
            ->execute();

        return $qb->fetchOne();
    }

    protected function getProduct($code): ?array
    {
        $productId = sqlQueryBuilder()
            ->select('id')
            ->fromProducts()
            ->where(
                Operator::orX(
                    Operator::equals(['code' => $code]),
                    Operator::equals(['code' => $code.'01'])
                )
            )
            ->execute()->fetchOne();

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

        $variation = sqlQueryBuilder()
            ->select('id, id_product')
            ->from('products_variations')
            ->where(Operator::equals(['code' => $code]))
            ->execute()->fetchAssociative();

        if ($variation) {
            return [(int) $variation['id_product'], (int) $variation['id']];
        }

        return null;
    }

    private function getProductVat(int $productId): float
    {
        $vatId = sqlQueryBuilder()
            ->select('vat')
            ->from('products')
            ->where(Operator::equals(['id' => $productId]))
            ->execute()->fetchOne();

        return (float) getVat($vatId);
    }
}

return ImportEURPricesScript::class;
