<?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\ViisonShippingCommon\Controllers\Backend\ViisonShippingCommonShipping;
use Shopware\Plugins\ViisonDHL\Util;
use Shopware\Plugins\ViisonDHL\Classes\PluginInfo;

/**
 * This controller adds some actions called in the shipping backend controller.
 * These actions are responsible for creating, updating and deleting associations
 * between dispatch methods and available DHL products.
 */
class Shopware_Controllers_Backend_ViisonDHLShipping extends ViisonShippingCommonShipping
{
    /** Use Germany as Fallback */
    const FALLBACK_COUNTRY_ISO = 'DE';

    public function __construct(Enlight_Controller_Request_Request $request = null, Enlight_Controller_Response_Response $response = null)
    {
        parent::__construct($request, $response, new PluginInfo());
    }

    /**
     * @override
     * @return array The columns of the product table that should be used for the ordering of the products (e.g. in comboboxes where a product can be chosen).
     */
    protected function getProductColumnOrder()
    {
        // Display normal DHL Paket products first, then Taggleich, then international products, then express products
        return [
            'FIELD(code, \'EPN\', \'EPO\', \'EPI\', \'BPI\', \'BPC\', \'WAP\', \'WPI\', \'EXP\')',
            'dateTimeOption',
            'premiumOption',
            'bulkfreightOption',
            'insuranceAmount',
        ];
    }

    /**
     * @override
     */
    protected function getCustomMappingAttributes()
    {
        return [
            'visualAgeCheck',
            'personalHandover',
            'incoterm',
            'frankatur',
            'isSaturdayDelivery',
            'isInsured',
            'parcelOutletRouting',
            'endorsementType',
            'identCheckAge',
            'postalDeliveryDutyPaid',
            'closestDroppointDelivery',
            'signedForByRecipient',
        ];
    }

    /**
     * @Override
     *
     * LEGEND:
     * - default -> Get Country specific products
     * - key :: allProducts -> Get all Products from DB
     */
    public function getProductsAction()
    {
        try {
            $params = $this->Request()->getParams() ?: null;
            if (empty($params)) {
                throw new Exception('Params is undefined.');
            }

            $util = Util::instance();

            // Prepare query
            $productTable = new Zend_Db_Table($this->pluginInfo->getProductTableName());
            $query = $productTable->select()->order($this->getProductColumnOrder());

            $allProducts = $params['allProducts'] ?: null;
            if (empty($allProducts)) {
                // Get Products by country, also always include International products (example DHL Express)
                $shopId = $params['shopId'] ?: Shopware()->Models()->getRepository('Shopware\\Models\\Shop\\Shop')->getActiveDefault()->getId();
                $selectedCountryIso = !empty($shopId) ? $util->config($shopId, 'countryiso') : self::FALLBACK_COUNTRY_ISO;
                $query = $query
                    ->where('availableInCountriesIso LIKE ?', '%' . $selectedCountryIso . '%')
                    ->orWhere('availableInCountriesIso = ?', 'INT');
            }

            // NOTE: Array deference is only allowed since PHP 5.4
            $namespace = $this->get('snippets')->getNamespace('backend/viison_dhl_util/util');
            $products = $productTable->fetchAll($query)->toArray();
            foreach ($products as $key => &$product) {
                // Add display country name to each product (localization is included)
                if (!empty($product) && !empty($product['availableInCountriesIso'])) {
                    $countryIsoName = $product['availableInCountriesIso'];
                    if ($countryIsoName !== $namespace->get('seperator_message/shipping/international_shipping/identifier')) {
                        $product['displayCountryName'] = $util->getCountryNameByIsoOrId($product['availableInCountriesIso']);
                    } else {
                        // If product is only for International shipping
                        $product['displayCountryName'] = $namespace->get('seperator_message/shipping/international_shipping/name');
                    }
                }
            }

            $this->View()->assign([
                'success' => true,
                'data' => $products,
            ]);
        } catch (\Zend_Db_Exception $e) {
            $this->View()->assign([
                'success' => false,
                'data' => null,
                'message' => $e->getMessage(),
            ]);
        } catch (\Zend_Db_Statement_Exception $e) {
            $this->View()->assign([
                'success' => false,
                'data' => null,
                'message' => $e->getMessage(),
            ]);
        } catch (\Zend_Db_Table_Select_Exception $e) {
            $this->View()->assign([
                'success' => false,
                'data' => null,
                'message' => $e->getMessage(),
            ]);
        } catch (\Exception $e) {
            $this->View()->assign([
                'success' => false,
                'data' => null,
                'error_cause' => 'internal_error',
                'message' => $e->getMessage(),
            ]);
        }
    }
}
