<?php

namespace KupShop\ReturnsBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\KupShopBundle\Util\Compat\SymfonyBridge;
use KupShop\ReturnsBundle\Util\ReturnsUtil;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class ReturnsSettingsTab extends WindowTab
{
    protected $title = 'flapReturnsSettings';
    protected $template = 'window/settings.returns.tpl';
    private ReturnsUtil $returnsUtil;

    public static function getTypes()
    {
        return [
            'settings' => 1,
        ];
    }

    public function getVars($smarty_tpl_vars)
    {
        $vars = parent::getVars($smarty_tpl_vars);

        $vars['tabView'] = $this;

        if (findModule(\Modules::RETURNS, \Modules::SUB_CP_AUTH_CODES)) {
            $vars['reclamations_auth_codes'] = sqlFetch($this->selectSQL('returns_auth_codes', [], ['COUNT(*) as total', 'SUM(used="Y") as used']));
        }

        $vars['enabledReturnPayments'] = [];

        foreach (\DeliveryType::getPayments(true) as $payment) {
            if ($payment['class'] && $payment['class']->enabledReturnPayment() && empty($vars['enabledReturnPayment'][$payment['class']->getClassName()])) {
                $vars['enabledReturnPayments'][$payment['class']->getClassName()] = $payment['class']::$name;
            }
        }

        return $vars;
    }

    public function handleUpdate()
    {
        $data = $this->window->getData();

        $reasons = $this->returnsUtil->prepareReturnReasons($data['returns']['reasons'] ?? []);
        $data['returns']['reasons'] = $reasons;

        $this->returnsUtil->updateReturnReasons($data);
    }

    public function getPlaceholders()
    {
        return [
            'KOD_VRATKY' => [
                'text' => 'Kód vytvořené vratky',
            ],
        ];
    }

    /** @required */
    public function setReturnsUtil(ReturnsUtil $returnsUtil): void
    {
        $this->returnsUtil = $returnsUtil;
    }

    public function handleImportAuthCodes()
    {
        if ($path = $this->getFile()) {
            try {
                $csv = new \SplFileObject($path);
                $csv->setFlags(\SplFileObject::READ_CSV);
                $csv->setCsvControl(';', "'");
                if ($csv->valid()) {
                    $columns = ['ID', 'Note', 'Date', 'Date2', 'Date3', 'PackageID'];
                    $codes = [];
                    while ($csv->valid()) {
                        $row_data = $csv->current();
                        if (count($row_data) == count($columns)) {
                            $row_data = array_combine($columns, $row_data);
                            $code = trim($row_data['ID']);
                            $date = trim($row_data['Date2']);
                            $packageID = trim($row_data['PackageID'], '"');
                            if (empty($packageID) && empty($date)) {
                                $codes[] = ['code' => $code];
                                sqlQuery("INSERT IGNORE INTO `returns_auth_codes` (`code`) VALUES ('{$code}')");
                            }
                        }
                        $csv->next();
                    }
                }
            } catch (Error $e) {
                $error = 'Chyba: '.$e->getMessage();

                $this->window->returnError($error);
            }
        }

        $this->window->returnOK();
    }

    public function getFile()
    {
        $request = SymfonyBridge::getCurrentRequest();

        /** @var $file UploadedFile */
        $file = $request->files->get('file');
        if (!$file) {
            return '';
        }

        return $file->getRealPath();
    }
}
