<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

use Hyva\Theme\Model\LocaleFormatter;
use Magento\Catalog\Helper\Product as ProductHelper;
use Magento\Framework\Escaper;
use Magento\Sales\Block\Order\Item\Renderer\DefaultRenderer;

/** @var DefaultRenderer $block */
/** @var Escaper $escaper */
/** @var LocaleFormatter $localeFormatter */
/** @var ProductHelper $productHelper */
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productHelper = $objectManager->get(\Magento\Catalog\Helper\Product::class);
$localeDate = $objectManager->get(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class);
$helper = $objectManager->get(\Meetanshi\OrderTracking\Helper\Data::class)->getAllCarriers();

$item = $block->getItem();
$itemId = $item->getId();
$cols = $block->getData('is_context_shipment') ? 3 : ($block->getData('is_context_creditmemo') ? 7 : 5);

$order = $block->getOrderItem()->getOrder();
$itemTrackingInfo = [];
$shipments = $order->getShipmentsCollection();

// Collect tracking info
foreach ($shipments as $shipment) {
    $shipmentItems = $shipment->getItemsCollection();
    $tracks = $shipment->getTracksCollection();

    $trackingData = [];
    foreach ($tracks as $track) {
        $trackingData[] = [
            'number' => $track->getTrackNumber(),
            'title' => $track->getTitle(),
            'carrier_code' => $track->getCarrierCode()
        ];
    }

    foreach ($shipmentItems as $shipmentItem) {
        if ($shipmentItem->getOrderItemId() == $itemId) {
            foreach ($trackingData as $trackInfo) {
                $itemTrackingInfo[$itemId][] = $trackInfo;
            }
        }
    }
}

$firstname = '';
$lastname = '';
$countryCode = '';
$postCode = '';
$orderId = $order->getEntityId();
$trackingDate = $localeDate->scopeDate();

if ($shipAddress = $order->getShippingAddress()) {
    $firstname = $shipAddress->getFirstname();
    $lastname = $shipAddress->getLastname();
    $countryCode = $shipAddress->getCountryId();
    $postCode = $shipAddress->getPostcode();
}
?>

<div class="bg-white py-2">
    <div class="flex">
        <div class="w-24 flex-shrink-0">
            <?php $product = $item->getProduct(); ?>
            <?php if ($product): ?>
                <?php $imageUrl = $productHelper->getImageUrl($product); ?>
                <img src="<?= $escaper->escapeUrl($imageUrl) ?>"
                     alt="<?= $escaper->escapeHtml($product->getName()) ?>"
                     class="w-full h-auto" />
            <?php else: ?>
                <div class="product-image-placeholder w-full h-24 bg-gray-100 flex items-center justify-center">
                    <span class="text-gray-400 text-xs">No image</span>
                </div>
            <?php endif; ?>
        </div>
        <div class="w-full">
            <div class="px-2 col-span-2">
                <span class="font-semibold text-sm md:text-base"><?= $escaper->escapeHtml($item->getName()) ?></span>
            </div>
            <div class="md:flex justify-between">
                <div class="item-options mt-2 hidden">
                    <div class="text-sm flex">
                        <span><?= $escaper->escapeHtml(__('SKU')) ?>:</span>
                        <span class="text-sm ml-1"><?= /* @noEscape */ $block->prepareSku($block->getSku()) ?></span>
                    </div>
                    <?php if ($options = $block->getItemOptions()): ?>
                        <?php foreach ($options as $option): ?>
                            <div class="text-sm flex mt-1">
                                <span><?= $escaper->escapeHtml($option['label']) ?>:</span>
                                <?php $formatedOptionValue = $block->getFormatedOptionValue($option) ?>
                                <span class="ml-1">
                                    <?= $escaper->escapeHtml($formatedOptionValue['value'], ['a']) ?>
                                </span>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <div class="px-2 flex justify-between lg:block">
                    <div class="text-left">
                        <?php if ($block->getData('is_context_order')): ?>
                            <div class="text-base font-sen">
                                <div class="title text-sm md:text-base font-sen"><?= $escaper->escapeHtml(__('Quantity')) ?></div>
                                <div class="text-sm md:text-base font-sen"><?= /** @noEscape */ $localeFormatter->formatNumber((float)$block->getItem()->getQtyOrdered()) ?></div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="px-2 md:w-1/2">
                    <div class="font-sen font-medium text-sm md:text-base">Status</div>
                    <?php
                    $orderStatus = $order->getStatus();
                    $hasTracking = !empty($itemTrackingInfo[$itemId]);
                    $statusLabel = match ($orderStatus) {
                        'processing' => __('Processing'),
                        'processed' => __('Confirmed'),
                        'RFD'       => $hasTracking ? __('Shipped') : __('Confirmed'),
                        'completed' => __('Delivered'),
                        default     => __('Processed'),
                    };
                    ?>

                    <div class="text-xs lg:text-sm mt-1 font-sen font-semibold text-primary">
                        <?= $escaper->escapeHtml($statusLabel) ?>
                    </div>

                    <?php if (!empty($itemTrackingInfo[$itemId])): ?>
                        <div class="tracking-info mt-2 text-sm">
                            <div class="text-xs lg:text-base font-sen font-medium"><?= $escaper->escapeHtml(__('Tracking Information:')) ?></div>
                            <?php foreach ($itemTrackingInfo[$itemId] as $trackInfo): ?>
                                <?php
            $url = '';
                                foreach ($helper as $data) {
                                    if ($data->getTitle() === $trackInfo['title']) {
                                        $url = $data->getUrl();
                                    }
                                }

                                $trackNumber = $trackInfo['number'];
                                $url = preg_replace(
                                    [
                                        "/#TRACKINGCODE#/i", "/#POSTCODE#/i", "/#ORDERID#/i",
                                        "/#FIRSTNAME#/i", "/#LASTNAME#/i", "/#COUNTRYCODE#/i",
                                        "/#d#/i", "/#m#/i", "/#y#/", "/#Y#/"
                                    ],
                                    [
                                        urlencode($trackNumber), urlencode($postCode), urlencode($orderId),
                                        urlencode($firstname), urlencode($lastname), urlencode($countryCode),
                                        $trackingDate->format('j'), $trackingDate->format('n'),
                                        $trackingDate->format('Y'), $trackingDate->format('y')
                                    ],
                                    $url
                                );
                                ?>
                                <div class="flex flex-col md:flex-row mt-1">
                                    <div>
                                        <span class="font-sen font-medium text-xs lg:text-sm mr-1"><?= $escaper->escapeHtml(__('Carrier/Service:')) ?></span>
                                        <a href="<?= $url ?>" class="font-sen font-medium text-xs lg:text-sm mr-3 text-primary"><?= $escaper->escapeHtml($trackInfo['title']) ?></a>
                                    </div>
                                    <div>
                                        <span class="font-sen font-medium text-xs lg:text-sm mr-1"><?= $escaper->escapeHtml(__('Tracking ID:')) ?></span>
                                        <span class="font-sen font-medium text-xs lg:text-sm"><?= $escaper->escapeHtml($trackInfo['number']) ?></span>
                                    </div>

                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>
