<?php

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

class InTimePoint extends Delivery
{
    public static $type = Delivery::TYPE_POINT;
    public static $className = 'InTime - Výdejní místa';

    public static $tableName = '`kupshop_shared`.`delivery_intime`';
    public static $jsonDeliveryBalikobot = 'https://test20cztest:QKCufcWs@api.balikobot.cz/intime/branches/4';

    protected $templateDescription = 'deliveries/delivery.InTimePoint.description.tpl';
    protected $AdminTemplateSettings = 'deliveries/block.delivery.InTimePoint.tpl';

    public $zip;

    public $intime_id;

    protected $track_and_trace = 'https://trace.intime.cz/index.php?action=vSearch';

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

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

    public function storeDeliveryInfo($data)
    {
        $id = trim($data['intime_id'] ?? '');

        $info = $this->getInfo($id);

        return empty($id) ? [] : ($this->data = [
            'zip' => $info['zip'],
            'intime_id' => $info['id'],
        ]);
    }

    public function getInfo($id = null)
    {
        if (is_null($id)) {
            $id = getVal('intime_id', $this->data);
        }

        $data = sqlFetchAssoc(sqlQuery('SELECT * FROM '.self::$tableName.'
            WHERE id=:id', ['id' => $id]));

        if (!$data) {
            return ['name' => 'Neznámá pobočka'];
        }

        $data['address'] = $data['street'].', '.$data['zip'].', '.$data['city'];

        return $data;
    }

    /**
     * @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'])) {
            return 'Není zvolena pobočka InTime!';
        }
        $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'])) {
            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['name']}, <strong>{$info['zip']}</strong>";
    }

    public function checkSelected(Cart $cart, ?Payment $payment = null)
    {
        if (empty($this->data['intime_id']) && $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['intime_id']) && $info['country'] != $this->getCountryByCurrency($currencyContext->getActiveId())) {
            throw new \KupShop\OrderingBundle\Exception\DeliveryException('Vybraná pobočka InTime nepodporuje vaši měnu.');
        }

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

    /**
     * @param $currency string
     *
     * @return string
     */
    private function getCountryByCurrency($currency)
    {
        switch ($currency) {
            case 'CZK':
                return 'CZ';
                break;
            case 'EUR':
                return 'SK';
                break;
            case 'HUF':
                return 'HU';
                break;
            case 'RON':
                return 'RO';
                break;
            case 'PLN':
                return 'PL';
                break;
            default:
                return '';
        }
    }
}
