<?php

namespace KupShop\BalikonosBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\BalikonosBundle\Balikobot;
use KupShop\BalikonosBundle\Exception\BalikonosException;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class BalikobotSettingsWindowTab extends WindowTab
{
    protected $title = 'flapBalikobotSettings';

    protected $template = 'window/settings.balikobot.tpl';

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

    public static function isAllowed()
    {
        return findModule(\Modules::BALIKONOS, 'provider') === 'balikobot';
    }

    public function handleUpdate()
    {
        $dbcfg = \Settings::createFromDB();
        $data = $this->getData();

        $users = [];
        foreach ($data['users'] as $index => $user) {
            if (($index > 0 || $index < 0) && empty($user['delete'])) {
                $users[] = $user;
            }
        }

        $balikobot = $dbcfg->balikobot;
        $originalUsers = $balikobot['users'] ?? [];
        $balikobot['users'] = $users;

        if ($originalUsers != $users) {
            clearCache('balikobot_carriers');
            clearCache('balikobot_carrier_services');
        }

        $dbcfg->saveValue('balikobot', $balikobot);
    }

    public function getVars($smarty_tpl_vars)
    {
        $dbcfg = \Settings::getDefault();
        $data['delivery_type'] = \Delivery::getAll(false);
        $balikobot = ServiceContainer::getService(Balikobot::class);

        if ($balikobot->hasMultipleCollectionPlaces()) {
            $users = $balikobot->getCollectionPlaces();
            if (!empty($users)) {
                $user = reset($users);
                $balikobot->setCredentials($user['user'], $user['key']);
            }
        }

        $data['carriers'] = ['' => '-- nevybráno --'] + $balikobot->getCarriers();

        try {
            $carrierServicesTmp = $balikobot->getAllCarrierServices();
        } catch (BalikonosException $e) {
        }

        if (isset($balikobot->authorizationFailed)) {
            $data['balikobot']['authorizationFailed'] = 'Balíkobot autorizace selhala: zkontrolujte své přihlašovací údaje';
        }

        $carrierServices = [];
        foreach ($balikobot->getCarriers() as $key => $name) {
            $carrierData = $carrierServicesTmp[$key] ?? [];
            if ($key === 'zasilkovna') {
                foreach ($carrierData as $k => $v) {
                    if (str_starts_with($k, 'VM')) {
                        unset($carrierData[$k]);
                    }
                }
            }

            $carrierServices[$key] = ['' => '-- nevybráno --'] + $carrierData;
        }
        $data['carrierServices'] = $carrierServices;
        $data['balikobot']['users'] = $dbcfg->balikobot['users'] ?? [];
        unset($balikobot);

        return $data;
    }
}
