<?php

namespace Autogedal\AutogedalHelper\Block;
use AllowDynamicProperties;
use Eadesigndev\Awb\Model\OrderAwb;
use Eadesigndev\Awb\Model\ResourceModel\Collection\Collection;
use Eadesigndev\Awb\Model\Sources\PickupId;

#[AllowDynamicProperties] class MShippingDescription
{
    public function __construct(
        \Eadesigndev\Awb\Helper\TrackingUrl $trackingUrl,
        Collection $collection,
        PickupId $pickupId,
        OrderAwb $orderAwb
    )
    {
        $this->awbCollection = $collection;
        $this->trackingUrl = $trackingUrl;
        $this->pickupId = $pickupId;
        $this->orderAwb = $orderAwb;
    }

    public function afterGetOrder(\Magento\Sales\Block\Order\Info $order, $result)
    {
        $awbDocuments = $this->orderAwb->getInfo(true);

        $shippingInfo = [];
        if (!empty($awbDocuments)) {
            foreach ($awbDocuments as $awb) {
                if (empty($awb['carrier_id']) || empty($awb['awb_number'])) {
                    continue;
                }
                $shippingInfo = array_merge($shippingInfo, [
                    $awb['carrier_name']->getText(),
                    $awb['awb_number'],
                ]);

                $shippingInfo[] = '<a target="_blank" href="' . $this->trackingUrl->getTrackingUrl($awb['carrier_id'], $awb['awb_number']) . '">' . __('Track the order') . '</a>';
            }
        }
        $result->setShippingDescription(implode("<br>", $shippingInfo));
        return $result;
    }
}