<?php

declare(strict_types=1);

namespace KupShop\OrderDiscountBundle\Admin\Actions;

use Box\Spout\Reader\Common\Creator\ReaderFactory;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use KupShop\AdminBundle\Admin\Actions\AbstractAction;
use KupShop\AdminBundle\Admin\Actions\ActionResult;
use KupShop\AdminBundle\Admin\Actions\IAction;
use KupShop\KupShopBundle\Util\Compat\SymfonyBridge;
use KupShop\KupShopBundle\Util\StringUtil;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class ImportOrderDiscountsCouponsAction extends AbstractAction implements IAction
{
    public const IMPORT_FAIL_MSG = 'Importní soubor se nepodařilo načíst. Zkontrolujte že je ve formátu XLS či XLSX.';

    public function getName(): string
    {
        return 'Importovat kódy';
    }

    public function getTypes(): array
    {
        return ['OrderDiscountsCoupons'];
    }

    public function getIcon()
    {
        return 'glyphicon glyphicon-import';
    }

    public function execute(&$data, array $config, string $type): ActionResult
    {
        if (!($file = $this->getFile())) {
            return new ActionResult(false);
        }

        try {
            $reader = ReaderFactory::createFromType($file->getClientOriginalExtension());
            $reader->open($file->getRealPath());
        } catch (\Throwable $e) {
            return new ActionResult(false, self::IMPORT_FAIL_MSG);
        }

        $header = null;

        try {
            foreach ($reader->getSheetIterator() as $sheet) {
                foreach ($sheet->getRowIterator() as $item) {
                    if (is_null($header)) {
                        $header = array_map(fn ($x) => StringUtil::slugify($x), $item->toArray());
                        continue;
                    }

                    $item = array_combine($header, array_pad($item->toArray(), count($header), null));

                    if (empty($item['kod'])) {
                        continue;
                    }

                    try {
                        sqlQueryBuilder()
                            ->insert('discounts_coupons')
                            ->directValues(
                                [
                                    'id_discount' => $this->getId(),
                                    'code' => $item['kod'],
                                    'date_from' => !empty($item['platnost-od']) ? $this->getDateTime($item['platnost-od']) : null,
                                    'date_activated' => !empty($item['datum-aktivace']) ? $this->getDateTime($item['datum-aktivace']) : null,
                                    'date_to' => !empty($item['platnost-do']) ? $this->getDateTime($item['platnost-do']) : null,
                                ]
                            )->execute();
                    } catch (UniqueConstraintViolationException $e) {
                        // duplicity ignorujeme
                    }
                }
            }
        } catch (ReaderNotOpenedException $e) {
            return new ActionResult(false, self::IMPORT_FAIL_MSG);
        }

        return new ActionResult(true);
    }

    private function getDateTime($date): ?string
    {
        if (empty($date)) {
            return null;
        }

        return $date->format('Y-m-d');
    }

    private function getFile(): ?UploadedFile
    {
        $request = SymfonyBridge::getCurrentRequest();
        if ($file = ($request->files->get('config')['file'] ?? null)) {
            return $file;
        }

        return null;
    }
}
