<?php

namespace External\SprintBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\StringUtil;
use KupShop\KupShopBundle\Util\System\PathFinder;

class ImportCouponsScript extends Script
{
    use \DatabaseCommunication;
    protected static $name = 'Import slevových poukazů';
    protected static $defaultParameters = [
        'pathToFile' => 'data/files/discountCoupons.csv',
    ];

    private $couponsCSVFile = 'data/files/discountCoupons.csv';

    protected function run(array $arguments)
    {
        $this->couponsCSVFile = $arguments['pathToFile'];
        $this->importDiscountsCodes();
    }

    public function importDiscountsCodes()
    {
        $keys = [];
        $count = 0;
        $path = 'data/files/discountCoupons.csv';

        foreach ($this->loadCSV($path) as $coupon) {
            $order_discounts = [
                'date_created' => (new \DateTime($coupon['issuedate']))->format('Y-m-d H:i:s'),
                'name' => $coupon['code'],
                'uses_count' => $coupon['usagecount'] ?? 0,
                'active' => 'Y',
            ];

            $actions = [];
            $triggers = [];

            $triggers['coupon'] = ['codes' => [$coupon['code']]];
            if (!$coupon['multipleusability']) {
                if (empty($order_discounts['usagecount']) || $order_discounts['usagecount'] > 0) {
                } else {
                    $triggers['usagecount'] = ['max_uses_count' => 1];
                }
            }

            $validDate = [];
            if (!empty($coupon['validfrom'])) {
                $validDate['dateFrom'] = (new \DateTime($coupon['validfrom']))->format('Y-m-d H:i:s');
            }
            if (!empty($coupon['validuntil'])) {
                $dateTo = new \DateTime($coupon['validuntil']);
                if ((new \DateTime()) > $dateTo) {
                    continue;
                }
                $validDate['dateTo'] = $dateTo->format('Y-m-d H:i:s');
                if (empty($coupon['validfrom'])) {
                    $validDate['dateFrom'] = (new \DateTime('now'))->format('Y-m-d H:i:s');
                }
            }
            if (!empty($validDate)) {
                $triggers['datetime'] = $validDate;
            }

            if (!empty($coupon['fromamount']) && $coupon['fromamountcurrency'] == 'CZK') {
                $triggers['price_range'] = ['min' => (float) str_replace(' ', '', $coupon['fromamount']), 'withVat' => '1'];
            }
            if ($coupon['delivery'] == 'free') {
                $actions['free_delivery'] = '';
            }

            switch ($coupon['templateId'] ?? null) {
                case null:
                case '1':
                case '42':
                    $actions['product_discount'] = [
                        'discount' => (float) str_replace(' ', '', $coupon['discount']),
                        'unit' => ($coupon['type'] == 'percentual') ? 'perc' : $coupon['currency'],
                        'filter' => [],
                    ];
                    break;
                case '38':
                    $actions['product_discount'] = [
                        'discount' => (float) str_replace(' ', '', $coupon['discount']),
                        'unit' => ($coupon['type'] == 'percentual') ? 'perc' : $coupon['currency'],
                        'filter' => ['campaigns' => ['D'], 'campaigns_invert' => 'invert', 'parametersValuesOperator' => 'AND'],
                    ];
                    break;

                default:
                    var_dump($coupon['templateId']);
            }

            $this->insertSQL('order_discounts', $order_discounts);
            $idDiscount = sqlInsertId();
            foreach ($actions as $type => $action) {
                $data = json_encode($action);
                if (!$data) {
                    $this->log(var_dump($action));
                    continue;
                }
                $importAction = [
                    'id_order_discount' => $idDiscount,
                    'type' => $type,
                    'data' => $data,
                ];

                $this->insertSQL('order_discounts_actions', $importAction);
            }

            foreach ($triggers as $type => $trigger) {
                $data = json_encode($trigger);
                if (!$data) {
                    $this->log(var_dump($trigger));
                    continue;
                }
                $importTrigger = [
                    'id_order_discount' => $idDiscount,
                    'type' => $type,
                    'data' => $data,
                ];

                $this->insertSQL('order_discounts_triggers', $importTrigger);
            }
        }
    }

    public function loadCSV($path)
    {
        $pathFinder = PathFinder::getService();

        if (!StringUtil::startsWith($path, 'http')) {
            $path = $pathFinder->getShopDir().$path;
            if (!file_exists($path)) {
                return false;
            }
        }

        $file = fopen($path, 'r');
        $return = [];
        $i = 1;
        $header = [];
        while (($data = fgetcsv($file, 0, ';')) !== false) {
            if ($i++ == 1) {
                foreach ($data as $item) {
                    $key = StringUtil::slugify($item);
                    $keyIndex = 2;
                    while (in_array($key, $header)) {
                        $key = StringUtil::slugify($item).'-'.$keyIndex++;
                    }

                    $header[] = $key;
                }
                continue;
            }

            $return[] = array_combine($header, $data);
        }

        return $return;
    }
}

return ImportCouponsScript::class;
