<?php
/**
 * Copyright © MageMe. All rights reserved.
 * See LICENSE for license terms, or https://mageme.com/license.
 */
declare(strict_types=1);

/** @var \MageMe\EUWithdrawal\Block\Sales\Order\WithdrawalsSection $block */
/** @var \Magento\Framework\Escaper $escaper */

if (!$block->shouldRender()) {
    return;
}

$requests   = $block->getRequests();
$cancelUrl  = $block->getCancelUrl();
$formKey    = $block->getFormKeyValue();
?>
<section class="mm-eu-w-section" aria-label="<?= $escaper->escapeHtmlAttr(__('Withdrawal options for this order')) ?>">

    <?php $cardState = $block->getCardState(); ?>
    <?php if ($cardState !== null): ?>
        <div class="mm-eu-w-deadline-card mm-eu-w-deadline-card--<?= $escaper->escapeHtmlAttr($cardState) ?>">
            <div class="mm-eu-w-deadline-icon" aria-hidden="true">
                <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <rect x="4" y="11" width="16" height="9" rx="2" />
                    <path d="M8 11V7a4 4 0 1 1 8 0v4" />
                    <path d="m9.5 15 2 2 3.5-4" />
                </svg>
            </div>
            <div class="mm-eu-w-deadline-body">
                <h3><?= $escaper->escapeHtml($block->getCardHeading()) ?></h3>
                <?php if ($cardState === 'eligible'): ?>
                    <p>
                        <?php $iso = $block->getDeadlineIsoUtc();
                        $disp = $block->getDeadlineDisplay(); ?>
                        <?= /* @noEscape */ __(
                            'You can return this order until %1.',
                            '<time datetime="' . $escaper->escapeHtmlAttr((string) $iso) . '">' . $escaper->escapeHtml((string) $disp) . '</time>',
                        ) ?>
                        <span class="mm-eu-w-deadline-cite"><?= $escaper->escapeHtml(__('(Art. 11a Directive 2011/83/EU)')) ?></span>
                    </p>
                    <p class="mm-eu-w-deadline-hint">
                        <?= $escaper->escapeHtml(__('Submit a withdrawal request to start the refund process.')) ?>
                    </p>
                <?php elseif ($cardState === 'eligible_pending'): ?>
                    <p><?= $escaper->escapeHtml($block->getCardMessage()) ?>
                       <span class="mm-eu-w-deadline-cite"><?= $escaper->escapeHtml(__('(Art. 9(2)(b) Directive 2011/83/EU)')) ?></span>
                    </p>
                <?php else: ?>
                    <p><?= $escaper->escapeHtml($block->getCardMessage()) ?></p>
                <?php endif; ?>

                <?php $caveats = $block->getConditionalCaveats(); ?>
                <?php if ($caveats !== [] && in_array($cardState, ['eligible', 'eligible_pending'], true)): ?>
                    <ul class="mm-eu-w-caveats">
                        <?php foreach ($caveats as $caveat): ?>
                            <li class="mm-eu-w-caveat">
                                <span class="mm-eu-w-caveat-icon" aria-hidden="true">&#9888;</span>
                                <span class="mm-eu-w-caveat-text">
                                    <?= $escaper->escapeHtml($caveat['label']) ?>
                                    <span class="mm-eu-w-caveat-cite">(<?= $escaper->escapeHtml($caveat['basis']) ?>)</span>
                                </span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
            <?php if ($block->shouldShowStartButton()): ?>
                <div class="mm-eu-w-deadline-cta">
                    <a class="action primary mm-eu-w-start"
                       href="<?= $escaper->escapeUrl($block->getStartUrl()) ?>">
                        <?= $escaper->escapeHtml(__('Start withdrawal')) ?>
                    </a>
                </div>
            <?php endif; ?>
        </div>
    <?php endif; ?>

    <?php if ($requests !== []): ?>
        <div class="mm-eu-w-history">
            <header class="mm-eu-w-history-header">
                <span class="title"><?= $escaper->escapeHtml(__('Your withdrawal requests')) ?></span>
                <span class="count">(<?= (int) count($requests) ?>)</span>
            </header>
            <ul class="mm-eu-w-history-list">
                <?php foreach ($requests as $request): ?>
                    <?php $badge = $block->getStatusBadge($request->status); ?>
                    <?php if ($badge['hidden']) { continue;} ?>
                    <li class="mm-eu-w-history-row" data-request-id="<?= (int) $request->requestId ?>">
                        <div class="mm-eu-w-row-summary">
                            <span class="mm-eu-w-pill" style="background:<?= $escaper->escapeHtmlAttr($badge['bg']) ?>;color:<?= $escaper->escapeHtmlAttr($badge['fg']) ?>;">
                                <?= $escaper->escapeHtml($badge['label']) ?>
                            </span>
                            <span class="mm-eu-w-rid"><?= $escaper->escapeHtml($request->incrementId) ?></span>
                            <span class="mm-eu-w-when">
                                <?= $escaper->escapeHtml(__('Submitted %1', $block->getSubmittedAtDisplay($request))) ?>
                            </span>
                            <span class="mm-eu-w-meta">
                                <?= $escaper->escapeHtml($block->getRequestSubtitle($request)) ?>
                            </span>
                            <span class="mm-eu-w-row-actions">
                                <button type="button" class="mm-eu-w-toggle"
                                        aria-expanded="false"
                                        aria-controls="mm-eu-w-detail-<?= (int) $request->requestId ?>"
                                        aria-label="<?= $escaper->escapeHtmlAttr(__('Show items')) ?>">
                                    <svg viewBox="0 0 20 20" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="5 8 10 13 15 8"></polyline></svg>
                                </button>
                                <?php if ($request->cancellable): ?>
                                    <button type="button"
                                            class="action secondary mm-eu-w-cancel"
                                            data-request-id="<?= (int) $request->requestId ?>"
                                            data-confirm="<?= $escaper->escapeHtmlAttr($block->getCancelConfirmMessage($request)) ?>">
                                        <?= $escaper->escapeHtml(__('Cancel withdrawal')) ?>
                                    </button>
                                <?php endif; ?>
                            </span>
                        </div>
                        <div id="mm-eu-w-detail-<?= (int) $request->requestId ?>"
                             class="mm-eu-w-row-detail"
                             hidden>
                            <?php $statusReason = $block->getStatusReason($request); ?>
                            <?php if ($statusReason !== null): ?>
                                <div class="mm-eu-w-detail-reason-card">
                                    <div class="mm-eu-w-detail-reason-label">
                                        <?= $escaper->escapeHtml($statusReason['label']) ?>
                                    </div>
                                    <?php if ($statusReason['legal_basis'] !== ''): ?>
                                        <div class="mm-eu-w-detail-reason-text"><em><?= /* @noEscape */ nl2br($escaper->escapeHtml($statusReason['legal_basis'])) ?></em></div>
                                    <?php endif; ?>
                                    <?php if ($statusReason['note'] !== ''): ?>
                                        <div class="mm-eu-w-detail-reason-text<?= /* @noEscape */ ($statusReason['legal_basis'] !== '' ? ' is-secondary' : '') ?>"><?= /* @noEscape */ nl2br($escaper->escapeHtml($statusReason['note'])) ?></div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                            <ul class="mm-eu-w-detail-items">
                                <?php foreach ($request->items as $item): ?>
                                    <?php $imgUrl = $block->getProductImageUrl((int) $item['order_item_id']); ?>
                                    <li class="mm-eu-w-detail-item">
                                        <span class="mm-eu-w-detail-thumb">
                                            <?php if ($imgUrl !== null): ?>
                                                <img src="<?= $escaper->escapeUrl($imgUrl) ?>" alt="<?= $escaper->escapeHtmlAttr((string) $item['name']) ?>" />
                                            <?php endif; ?>
                                        </span>
                                        <span class="mm-eu-w-detail-name">
                                            <strong><?= $escaper->escapeHtml((string) $item['name']) ?></strong>
                                            <span class="mm-eu-w-detail-sku"><?= $escaper->escapeHtml(__('SKU')) ?>: <?= $escaper->escapeHtml((string) $item['sku']) ?></span>
                                        </span>
                                        <span class="mm-eu-w-detail-qty">
                                            <?= $escaper->escapeHtml(__('Qty %1', (int) $item['qty'])) ?>
                                        </span>
                                        <span class="mm-eu-w-detail-reason">
                                            <?= $escaper->escapeHtml($block->getItemReasonDisplay($item)) ?>
                                        </span>
                                        <span class="mm-eu-w-detail-refund">
                                            <?= $escaper->escapeHtml($block->formatItemRefund($item)) ?>
                                        </span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>

        <form id="mm-eu-w-cancel-form"
              method="post"
              action="<?= $escaper->escapeUrl($cancelUrl) ?>"
              style="display:none;">
            <input type="hidden" name="form_key" value="<?= $escaper->escapeHtmlAttr($formKey) ?>" />
            <input type="hidden" name="request_id" value="" id="mm-eu-w-cancel-rid" />
            <input type="hidden" name="return_url" value="<?= $escaper->escapeUrl($block->getCurrentPageUrl()) ?>" />
        </form>

        <script type="text/javascript">
        (function () {
            'use strict';
            var section = document.querySelector('.mm-eu-w-section');
            if (!section) { return; }
            section.addEventListener('click', function (e) {
                var toggle = e.target.closest('.mm-eu-w-toggle');
                if (toggle) {
                    var row = toggle.closest('.mm-eu-w-history-row');
                    var detail = row && row.querySelector('.mm-eu-w-row-detail');
                    if (!detail) { return; }
                    var isHidden = detail.hasAttribute('hidden');
                    if (isHidden) { detail.removeAttribute('hidden'); } else { detail.setAttribute('hidden', ''); }
                    toggle.setAttribute('aria-expanded', isHidden ? 'true' : 'false');
                    toggle.classList.toggle('is-open', isHidden);
                    return;
                }
                var cancel = e.target.closest('.mm-eu-w-cancel');
                if (cancel) {
                    var msg = cancel.getAttribute('data-confirm') || 'Cancel?';
                    if (window.confirm(msg)) {
                        var form = document.getElementById('mm-eu-w-cancel-form');
                        var rid = document.getElementById('mm-eu-w-cancel-rid');
                        if (form && rid) {
                            rid.value = cancel.getAttribute('data-request-id') || '';
                            form.submit();
                        }
                    }
                }
            });
        })();
        </script>
    <?php endif; ?>
</section>
