<?php

use KupShop\OrderingBundle\Exception\DeliveryException;

class DHLServicePoint extends Delivery
{
    public static $className = 'DHL ServicePoint';
    public static $type = self::TYPE_POINT;

    protected $track_and_trace = 'https://www.logistics.dhl/de-de/home/tracking.html?tracking-id=[PACKAGE_ID]&submit=1';

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

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

    public $defaultIcon = '../../common/static/deliveries/dhl.svg';

    public array $pointData = [];

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

        $this->pointData = [];
        $pointData = $data['DHLServicePoint_point'] ?? [];

        if (empty($pointData)) {
            return [];
        }

        $pointData = json_decode($pointData, true);
        $pointIds = $this->storeIds($pointData);
        $this->pointData = array_merge($pointData, $pointIds);

        return $this->pointData;
    }

    public function loadDeliveryInfo($data)
    {
        $this->pointData = $data;
    }

    public function getInfo($id = null)
    {
        return $this->pointData;
    }

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

    public function applyToCart(CartBase $cart)
    {
        parent::applyToCart($cart);

        if (empty($this->pointData['id'])) {
            return;
        }

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

        $cart->delivery['firm'] = $this->pointData['name'];
        $cart->delivery['zip'] = $this->pointData['address']['zipCode'];
        $cart->delivery['street'] = $this->pointData['address']['street'].' '.$this->pointData['address']['number'];
        $cart->delivery['city'] = $this->pointData['address']['city'];
        $cart->delivery['country'] = $this->pointData['address']['countryCode'];

        // Je-li zvolena doprava do do vydejniho boxu (Packstation), zapisuju jeji nazev do pole 'street'
        if (str_contains($this->pointData['name'], 'Packstation')) {
            $cart->delivery['street'] = $this->pointData['name'];
            $cart->delivery['custom_address'] = $this->pointData['rec_id'] ?? '';
            $cart->delivery['firm'] = '';
        }
    }

    public function applyToOrder(&$data, $order)
    {
        parent::applyToOrder($data, $order);

        if (empty($this->pointData['id'])) {
            return 'Není zvolen ServicePoint!';
        }
        $data['delivery_firm'] = $this->pointData['name'];
        $data['delivery_zip'] = $this->pointData['address']['zipCode'];
        $data['delivery_street'] = $this->pointData['address']['street'].' '.$this->pointData['address']['number'];
        $data['delivery_city'] = $this->pointData['address']['city'];
        $data['delivery_country'] = $this->pointData['address']['countryCode'];

        // Je-li zvolena doprava do vydejniho boxu (Packstation), zapisuju jeji nazev do pole 'delivery_street'
        if (str_contains($this->pointData['name'], 'Packstation')) {
            $data['delivery_street'] = $this->pointData['name'];
            $data['delivery_custom_address'] = $this->pointData['rec_id'] ?? '';
            $data['delivery_firm'] = '';
        }

        return true;
    }

    public function check(Cart $cart)
    {
        if ($cart->hasData('delivery', false) && $this->pointData) {
            // parcel-first-mile - svozove misto odkud se baliky odesilaji
            // parcel-last-mile - misto pro vyzvednuti baliku
            // pokud tedy objednavam zbozi, tak pobocka musi podporovat "parcel-last-mile", aby tam balik bylo mozne vyzvednout
            // bohuzel to nyni nejde odfiltrovat ve widgetu, tak treba az to jednou pujde, tak bude moct jit tenhle if pryc
            if (!in_array('parcel-last-mile', $this->pointData['serviceTypes'] ?? [])) {
                throw new DeliveryException(
                    translate_shop('point_pickup_not_supported', 'delivery'),
                    translate_shop('point_pickup_not_supported', 'delivery'),
                );
            }
        }

        return parent::check($cart);
    }

    public function requiresDeliveryAddress(): bool
    {
        return false;
    }

    public function storeIds(array $pointData): array
    {
        if (!isset($pointData)) {
            return [];
        }

        // ulozim si Ids do pole a vyparsuju rec_id (Postnummer), pokud je predany v 'id'
        $pointIds['id'] = $pointData['id'] ?? '';
        $pointIds['harmonisedId'] = $pointData['harmonisedId'] ?? '';

        if (str_contains($pointIds['id'], '|')) {
            $pointIds['rec_id'] = substr(strchr($pointIds['id'], '|'), 1);
            $pointIds['id'] = strchr($pointIds['id'], '|', true);
        }

        return $pointIds;
    }
}
