<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

use Shopware\Plugins\ViisonCommon\Classes\ExceptionHandling\BackendExceptionHandling;
use Shopware\Plugins\ViisonDHL\Classes\CreateShipmentOrderRequest;

/**
 * This controller is responsible for obtaining and translating the incoterm and frankatur terms of trades
 * for the TermsOfTrades Extjs SubApp.
 */
class Shopware_Controllers_Backend_ViisonDHLTermsOfTrade extends Shopware_Controllers_Backend_ExtJs
{
    use BackendExceptionHandling;

    public function getIncotermsAction()
    {
        try {
            $this->View()->assign([
                'success' => true,
                'data' => $this->getTermsOfTrades(CreateShipmentOrderRequest::INCOTERM_CODES),
            ]);
        } catch (\Exception $e) {
            $this->handleException($e);
        }
    }

    public function getIncotermsExpressAction()
    {
        try {
            $this->View()->assign([
                'success' => true,
                'data' => $this->getTermsOfTrades(CreateShipmentOrderRequest::INCOTERM_EXPRESS_CODES),
            ]);
        } catch (\Exception $e) {
            $this->handleException($e);
        }
    }

    public function getFrankatursAction()
    {
        try {
            $this->View()->assign([
                'success' => true,
                'data' => $this->getTermsOfTrades(CreateShipmentOrderRequest::FRANKATUR_CODES),
            ]);
        } catch (\Exception $e) {
            $this->handleException($e);
        }
    }

    private function getTermsOfTrades($termsOfTradeCodes)
    {
        $namespace = $this->get('snippets')->getNamespace('backend/viison_dhl_shipping/terms_of_trade');
        $result = array_map(
            function ($termsOfTrade) use ($namespace) {
                return [
                    'name' => $termsOfTrade,
                    'description' => $namespace->get($termsOfTrade),
                ];
            },
            $termsOfTradeCodes
        );
        array_unshift($result, [
            'name' => '',
            'description' => '-',
        ]);

        return $result;
    }
}
