<?php

namespace KupShop\BalikonosBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use KupShop\ReturnsBundle\Deliveries\Utils\ReturnDeliveries;

class BalikobotReturnDeliveryTab extends WindowTab
{
    protected $title = 'flapBalikobotReturnDelivery';

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

    protected ReturnDeliveries $returnDeliveries;

    /**
     * @required
     */
    public function setReturnDeliveries(?ReturnDeliveries $returnDeliveries): void
    {
        $this->returnDeliveries = $returnDeliveries;
    }

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

    public function getVars($smarty_tpl_vars)
    {
        $data = [];
        $dbcfg = \Settings::getDefault();
        $users = array_map(function ($user) {
            return $user['name'];
        }, $dbcfg->balikobot['users'] ?? []);

        $data['users'] = array_combine($users, $users);

        $data['balikobot_user'] = $this->window->getCustomData()['balikobot_user'] ?? '';

        return $data;
    }

    public function handleUpdate()
    {
        $data = getVal('data');

        $customData = $this->window->getCustomData();
        if ($data['balikobot_user'] ?? false) {
            $customData['balikobot_user'] = $data['balikobot_user'];
        }
        $this->window->setCustomData($customData);
    }

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

    public function isVisible()
    {
        $id = getVal('ID');

        if ($id) {
            $returnEntity = $this->returnDeliveries->getReturnDeliveryEntity($id);
            if ($returnEntity && $returnEntity->getClass()->retrieveDataFromBalikobot()) {
                return parent::isVisible();
            }

            return false;
        }

        return parent::isVisible();
    }

    public function getLabel()
    {
        return translate('balikobot', 'suppliers');
    }
}
