<?php

use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class SPSParcelShop extends Delivery
{
    public static $type = Delivery::TYPE_POINT;
    public static $className = 'SPS Parcel Shop';

    protected $heureka_delivery_id = 'SPS';
    protected $zbozi_delivery_id = 'SPS';

    protected $templateDescription = 'deliveries/delivery.SPSParcelShop.description.tpl';
    protected $templateInit = 'deliveries/delivery.SPSParcelShop.init.tpl';

    protected $AdminTemplateSettings = 'deliveries/block.delivery.SPSParcelShop.tpl';

    protected $track_and_trace = 'https://www.sps-sro.sk/sledovanie-zasielky/';

    public function getName()
    {
        $info = $this->getInfo();

        return parent::getName().' - '.$info['city'].', '.$info['street'].', '.$info['description'];
    }

    public function getPointId()
    {
        return $this->data['id_point'] ?? null;
    }

    public function storeDeliveryInfo($data)
    {
        parent::storeDeliveryInfo($data);

        if (isset($data['sps_parcel_shop_point'])) {
            $point = $data['sps_parcel_shop_point'];
            $point = json_decode($point, true);

            if (isset($point['id'])) {
                $this->data += [
                    'id_point' => $point['id'],
                    'zip' => $point['zip'],
                    'street' => $point['address'],
                    'city' => $point['city'],
                    'country' => $point['countryISO'],
                    'description' => $point['description'],
                ];
            } else {
                $this->data += $point;
            }
        }

        return $this->data;
    }

    public function getInfo()
    {
        if (!empty($this->data)) {
            return $this->data;
        } else {
            return ['description' => 'Neznámá pobočka'];
        }
    }

    /**
     * @param       $data  admin order data
     * @param Order $order
     *
     * @return bool|string
     */
    public function applyToOrder(&$data, $order)
    {
        parent::applyToOrder($data, $order);

        $info = $this->getInfo();
        if (empty($info['id_point'])) {
            return 'Není zvolena pobočka SPS ParcelShop!';
        }
        $data['delivery_zip'] = $info['zip'];
        $data['delivery_street'] = $info['street'];
        $data['delivery_city'] = $info['city'];
        $data['delivery_country'] = $info['country'];
        $data['delivery_firm'] = '';

        return true;
    }

    /**
     * @param $cart CartBase
     */
    public function applyToCart(CartBase $cart)
    {
        parent::applyToCart($cart);

        $info = $this->getInfo();

        if (empty($info['id_point'])) {
            return;
        }

        if (isset($cart->invoice['name'])) {
            $cart->delivery['name'] = $cart->invoice['name'];
            $cart->delivery['surname'] = $cart->invoice['surname'];
        }

        $cart->delivery['zip'] = $info['zip'];
        $cart->delivery['street'] = $info['street'];
        $cart->delivery['city'] = $info['city'];
        $cart->delivery['country'] = $info['country'];
        $cart->delivery['firm'] = '';
    }

    public function printDeliveryInfo()
    {
        $info = $this->getInfo();

        return "<strong>{$info['city']}</strong>, {$info['street']}, {$info['description']}, <strong>{$info['zip']}</strong>";
    }

    public function checkSelected(Cart $cart, ?Payment $payment = null)
    {
        if (empty($this->data['id_point']) && $cart->hasData('delivery')) {
            throw new \KupShop\OrderingBundle\Exception\DeliveryException(translate('branch_missing_zip', 'delivery'));
        }

        $info = $this->getInfo();
        $currencyContext = ServiceContainer::getService(CurrencyContext::class);
        if (!empty($this->data['id_point']) && !in_array($info['country'], $this->getCountryByCurrency($currencyContext->getActiveId()))) {
            throw new \KupShop\OrderingBundle\Exception\DeliveryException('Vybraná pobočka SPS ParcelShop nepodporuje vaši měnu.');
        }

        return parent::checkSelected($cart, $payment);
    }

    private function getCountryByCurrency($currency)
    {
        switch ($currency) {
            case 'CZK':
                return ['CZ'];
                break;
            case 'EUR':
                return ['SK', 'DE'];
                break;
            case 'HUF':
                return ['HU'];
                break;
            case 'RON':
                return ['RO'];
                break;
            case 'PLN':
                return ['PL'];
                break;
            default:
                return [];
        }
    }
}
