<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes. All rights reserved.
 * See COPYING.txt for license details.
 */

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Magento\Framework\Data\Helper\PostHelper;
use Magento\Framework\Escaper;
use Magento\Sales\Block\Order\Recent;
use Magento\Sales\Helper\Reorder;
use Magento\Sales\Model\Order;

// phpcs:disable Magento2.Templates.ThisInTemplate.FoundThis
// phpcs:disable Magento2.Templates.ThisInTemplate.FoundHelper

/** @var Escaper $escaper */
/** @var Recent $block */
/** @var ViewModelRegistry $viewModels */

/** @var HeroiconsOutline $heroicons */
$heroicons = $viewModels->require(HeroiconsOutline::class);
/** @var Order[] $orders */
$orders = $block->getOrders();
$count  = count($orders);

$extraActions = [];
if ($extraActionTitleBlocks = $block->getLayout()->getChildBlocks('order-list-extra-action-titles')) {
    foreach ($extraActionTitleBlocks as $alias => $extraActionTitleBlock) {
        $extraActions[$alias] = $extraActionTitleBlock->toHtml();
    }
    $extraActions = array_filter($extraActions, function ($output, string $alias) use ($block): bool {
        return trim($output) && $block->getLayout()->getChildBlock('order-list-extra-action-buttons', $alias);
    }, ARRAY_FILTER_USE_BOTH);
}

?>
<div
    class="block block-dashboard-orders card mt-4"
    x-data="{ tabIndex: -1 }"
>
    <div class="block-title order my-4 flex justify-between items-center">
        <h2
            id="recentOrders"
            class="text-2xl block"
            @focus="tabIndex = 0;"
            @blur="tabIndex = -1"
            :tabindex="tabIndex"
        ><?= $escaper->escapeHtml(__('Recent Orders')) ?></h2>
        <?php if ($count > 0): ?>
            <a
                class="action view inline-block underline"
                href="<?= $escaper->escapeUrl($block->getUrl('sales/order/history')) ?>"
                aria-label="<?= $escaper->escapeHtmlAttr(__('View all orders')) ?>"
            ><?= $escaper->escapeHtml(__('View All')) ?></a>
        <?php endif; ?>
    </div>
    <div class="overflow-x-auto">
        <?= $block->getChildHtml() ?>
        <?php if ($count > 0): ?>
            <table
                id="my-orders-table"
                class="block-content w-full sm:table-fixed lg:table-auto"
                aria-labelledby="recentOrders"
            >
                <thead class="text-sm">
                    <tr>
                        <th class="p-2 text-start">
                            <?= $escaper->escapeHtml(__('Order #')) ?>
                        </th>
                        <th class="p-2 text-start hidden lg:table-cell">
                            <?= $escaper->escapeHtml(__('Date')) ?>
                        </th>
                        <th class="p-2 text-start">
                            <?= $escaper->escapeHtml(__('Ship To')) ?>
                        </th>
                        <th class="p-2 text-start hidden lg:table-cell">
                            <?= $escaper->escapeHtml(__('Order Total')) ?>
                        </th>
                        <th class="p-2 text-start hidden lg:table-cell">
                            <?= $escaper->escapeHtml(__('Status')) ?>
                        </th>
                        <th class="p-2 text-center">
                            <?= $escaper->escapeHtml(__('View')) ?>
                            <?php if ($this->helper(Reorder::class)->isAllow()): ?>
                                / <?= $escaper->escapeHtml(__('Reorder')) ?>
                            <?php endif; ?>
                            <?php foreach ($extraActions as $extraActionTitle): ?>
                                / <?= /** @noEscape  */ $extraActionTitle ?>
                            <?php endforeach; ?>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order): ?>
                        <tr class="align-top even:bg-gray-100">
                            <th
                                id="order<?= $escaper->escapeHtmlAttr($order->getRealOrderId()) ?>"
                                class="p-2 text-start font-normal"
                            >
                                <?= $escaper->escapeHtml($order->getRealOrderId()) ?>
                                <p class="lg:hidden text-sm">
                                    <?= $escaper->escapeHtml($block->formatDate($order->getCreatedAt())) ?>
                                </p>
                            </th>
                            <td class="p-2 hidden lg:table-cell">
                                <?php
                                    $date = $order->getCreatedAt();
                                    $format = $block->getDateFormat() ?: \IntlDateFormatter::SHORT;
                                    $formatLong = $block->getDateFormat() ?: \IntlDateFormatter::LONG;
                                ?>
                                <span aria-hidden="true">
                                    <?= $escaper->escapeHtmlAttr($block->formatDate($date, $format)); ?>
                                </span>
                                <span class="sr-only">
                                    <?= $escaper->escapeHtml($block->formatDate($date, $formatLong)); ?>
                                </span>
                            </td>
                            <td class="p-2">
                                <?= $order->getShippingAddress() ? $escaper->escapeHtml($order->getShippingAddress()->getName()) : '&nbsp;' ?>
                            </td>
                            <td class="p-2 hidden lg:table-cell">
                                <?= /* @noEscape */ $order->formatPrice($order->getGrandTotal()) ?>
                            </td>
                            <td class="p-2 hidden lg:table-cell">
                                <?= $escaper->escapeHtml($order->getStatusLabel()) ?>
                            </td>
                            <td class="p-2">
                                <?php // 'received' is an order status added in Magento_AsyncOrder in Adobe Commerce ?>
                                <?php // The condition will always return 'true' in Magento Open Source ?>
                                <?php if ($order->getStatus() !== 'received'): ?>
                                    <div class="flex items-center justify-evenly">
                                        <a
                                            href="<?= $escaper->escapeUrl($block->getViewUrl($order)) ?>"
                                            class="inline-block text-sm underline"
                                            title="<?= $escaper->escapeHtmlAttr(__('View Order')) ?>"
                                            aria-label="<?= $escaper->escapeHtmlAttr(__('View order') . ' ' . ltrim($order->getRealOrderId(), '0')) ?>"
                                        >
                                            <?= $heroicons->eyeHtml('', 24, 24, ['aria-hidden' => 'true']) ?>
                                        </a>
                                        <?php if ($this->helper(Reorder::class)->canReorder($order->getEntityId())): ?>
                                            <?php $formData = json_decode(
                                                $this->helper(PostHelper::class)->getPostData(
                                                    $block->getReorderUrl($order)
                                                ),
                                                true
                                            ) ?>
                                            <form
                                                action="<?= $escaper->escapeUrl($formData['action']) ?>"
                                                method="post"
                                                class="inline-flex items-center"
                                            >
                                                <?= $block->getBlockHtml('formkey'); ?>
                                                <input type="hidden" name="data" value='<?= /* @noEscape */ json_encode($formData['data']) ?>'>
                                                <button
                                                    title="<?= $escaper->escapeHtmlAttr(__('Reorder')) ?>"
                                                    type="submit"
                                                    class="inline-block text-sm"
                                                    aria-label="<?= $escaper->escapeHtmlAttr(__('Reorder') . ' ' . ltrim($order->getRealOrderId(), '0')) ?>"
                                                >
                                                    <?= $heroicons->refreshHtml('', 24, 24, ['aria-hidden' => 'true']) ?>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <?= $heroicons->refreshHtml('text-gray-300', 24, 24, ['aria-hidden' => 'true']) ?>
                                        <?php endif ?>
                                        <?php foreach (array_keys($extraActions) as $alias): ?>
                                            <?php $button = $block->getLayout()->getChildBlock('order-list-extra-action-buttons', $alias) ?>
                                            <?= $button->assign('order', $order)->setData('order', $order)->toHtml() ?>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="message info empty">
                <span><?= $escaper->escapeHtml(__('You have placed no orders.')) ?></span>
            </div>
        <?php endif; ?>
    </div>
</div>
