<?php

namespace YSquare\Shipcloud\Application\Controller\Admin;

use Doctrine\DBAL\Query\QueryBuilder;
use OxidEsales\Eshop\Application\Controller\Admin\AdminDetailsController;
use OxidEsales\Eshop\Application\Model\DeliverySetList;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\TableViewNameGenerator;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;

class AdminController extends AdminDetailsController
{
    public const ERROR_MESSAGE_TIME = [
        "SHORT"  => 5000,
        "MEDIUM" => 10000,
        "LONG"   => 20000,
    ];
    /**
     * Current Settings
     *
     * @var AdminSettings
     */
    protected $adminSettings;
    protected $adminRest;
    protected $aSettings = null;
    protected $active_carriers = null;
    /**
     * @var QueryBuilderFactory
     */
    protected $queryBuilderFactory;

    public function __construct($defaultSettingsName = 'main_settings')
    {
        $this->adminSettings = oxNew(AdminSettings::Class, $defaultSettingsName);
        $this->adminRest = oxNew(AdminRestController::class);

        $container = ContainerFactory::getInstance()->getContainer();
        $this->queryBuilderFactory = $container->get(QueryBuilderFactoryInterface::class);

        parent::__construct();
    }

    public function render()
    {
        $ret = parent::render();

        $this->_aViewData['settings'] = $this->adminSettings->loadValues();

        return $ret;
    }

    public function save()
    {
        // Setup the value array from the sent parameters
        $editValues = Registry::getRequest()->getRequestEscapedParameter('ysedit');
        $this->adminSettings->save($editValues);
    }

    public function getCarriers($api_key = null): array
    {
        if (isset($api_key) && $api_key != '') {
            $this->adminRest->setApiKey($api_key);
        }
        return $this->adminRest->getCarriers();
    }

    public function isReturnAvailable($carrier): bool
    {
        $services = $this->getCarrierServices($carrier);
        if (array_key_exists('returns', $services)) {
            return true;
        } else {
            return false;
        }
    }

    public function getCarrierServices($carrierKey): array
    {
        $carriers = $this->getActiveCarriers();
        if ($carriers and $carriers[$carrierKey] and $carriers[$carrierKey]['services']) {
            return $carriers[$carrierKey]['services'];
        } else {
            return [];
        }
    }

    public function getActiveCarriers(): array
    {
        if (!$this->active_carriers) {
            $carriers = $this->adminSettings->getSettings('carriers', 'main_settings');
            if (!$carriers) {
                $carriers = [];
            }
            $this->active_carriers = array_filter(
                $carriers,
                function ($v) {
                    return $v['active'] == 'on';
                }
            );
        }
        return $this->active_carriers;
    }

    public function getDeliverySet(): DeliverySetList
    {
        /** @var DeliverySetList $deliverySetList */
        $deliverySetList = oxnew(DeliverySetList::class);

        /** @var TableViewNameGenerator $viewNameGenerator */
        $viewNameGenerator = Registry::get(TableViewNameGenerator::class);
        $sViewName = $viewNameGenerator->getViewName('oxdeliveryset');

        /** @var QueryBuilder $queryBuilder */
        $queryBuilder = $this->queryBuilderFactory->create();
        $queryBuilder
            ->select('*')
            ->from($sViewName)
            ->where($deliverySetList->getBaseObject()->getSqlActiveSnippet());

        $deliverySetList->selectString($queryBuilder->getSQL());

        return $deliverySetList;
    }
}
