<?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
 */

declare(strict_types=1);

// phpcs:disable Magento2.Templates.ThisInTemplate

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\Cart\ItemOutput;
use Hyva\Theme\ViewModel\Modal;
use Magento\Checkout\Block\Cart\Grid;
use Magento\Checkout\ViewModel\Cart as CartViewModel;
use Magento\Framework\Escaper;
use Magento\Framework\App\ObjectManager;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Catalog\Api\CategoryRepositoryInterface;

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

/** @var CartViewModel $cartViewModel */
$cartViewModel = $viewModels->require(CartViewModel::class);

/** @var Modal $modalViewModel */
$modalViewModel = $viewModels->require(Modal::class);

/** @var ItemOutput $cartItemOutputViewModel */
$cartItemOutputViewModel = $viewModels->require(ItemOutput::class);

// Get the checkout session and category repository
$checkoutSession = ObjectManager::getInstance()->get(CheckoutSession::class);
$categoryRepository = ObjectManager::getInstance()->get(CategoryRepositoryInterface::class);

// Get the quote from the checkout session
$quote = $checkoutSession->getQuote();

// Initialize category URL
$continueShoppingUrl = null;

// Get the first item from the cart
$items = $quote->getAllItems();
if (!empty($items)) {
    $firstItem = reset($items);
    $product = $firstItem->getProduct();

    // Get the first category ID of the product
    $categoryIds = $product->getCategoryIds();
    if (!empty($categoryIds)) {
        try {
            // Get the category and its URL
            $category = $categoryRepository->get($categoryIds[0]);
            $continueShoppingUrl = $category->getUrl();
        } catch (\Exception $e) {
            // If there's an error, don't show the link
        }
    }
}
?>
<?php $mergedCells = ($cartItemOutputViewModel->isItemPriceDisplayBoth() ? 2 : 1); ?>
<?= $block->getChildHtml('form_before') ?>
<form action="<?= $escaper->escapeUrl($block->getUrl('checkout/cart/updatePost')) ?>"
      x-data="{}"
      @submit.prevent="hyva.postCart($event.target)"
      method="post"
      id="form-validate"
      class="form form-cart w-full float-left"
>
    <?= $block->getBlockHtml('formkey') ?>
    <div class="cart table-wrapper<?= $mergedCells == 2 ? ' detailed' : '' ?>">
        <?php if ($block->getPagerHtml()): ?>
            <div class="cart-products-toolbar cart-products-toolbar-top toolbar">
                <?= $block->getPagerHtml() ?>
            </div>
        <?php endif ?>
        <table id="shopping-cart-table"
               class="cart items data table w-full table-row-items"
        >
            <caption class="table-caption sr-only">
                <?= $escaper->escapeHtml(__('Shopping Cart Items')) ?>
            </caption>
            <thead class="hidden ">
            <tr class="text-right">
                <th class="col item text-left pt-4 px-4 pb-2" scope="col">
                    <?= $escaper->escapeHtml(__('Item')) ?>
                </th>
                <th class="col price pt-4 px-4 pb-2" scope="col">
                    <?= $escaper->escapeHtml(__('Price')) ?>
                </th>
                <th class="col qty pt-4 px-4 pb-2" scope="col">
                    <?= $escaper->escapeHtml(__('Qty')) ?>
                </th>
                <th class="col subtotal pt-4 px-4 pb-2" scope="col">
                    <?= $escaper->escapeHtml(__('Subtotal')) ?>
                </th>
            </tr>
            </thead>
            <?php foreach ($block->getItems() as $item): ?>
                <?= $block->getItemHtml($item) ?>
            <?php endforeach ?>
        </table>
        <?php if ($block->getPagerHtml()): ?>
            <div class="cart-products-toolbar cart-products-toolbar-bottom toolbar">
                <?= $block->getPagerHtml() ?>
            </div>
        <?php endif ?>
    </div>
    <div class="cart actions flex flex-col lg:flex-row justify-between gap-4 items-center mt-4 md:my-4">
        <?php if ($cartViewModel->isClearShoppingCartEnabled()): ?>
            <script>
                function initClearShoppingCartModal() {
                    return Object.assign(
                        hyva.modal(),
                        {
                            postData: {
                                action: '<?= $escaper->escapeUrl($block->getUrl('checkout/cart/updatePost')) ?>',
                                data: {update_cart_action: 'empty_cart'}
                            }
                        }
                    );
                }
            </script>
            <div x-data="initClearShoppingCartModal()">
                <?= /** @noEscape */ ($confirmation = $modalViewModel
                    ->confirm(__('Are you sure?'))
                    ->withDetails(__('Are you sure you want to remove all items from your shopping cart?'))
                ) ?>
                <button @click="<?= /** @noEscape */ $confirmation->getShowJs() ?>.then(result => result && hyva.postForm(postData))"
                        type="button" title="<?= $escaper->escapeHtmlAttr(__('Clear Shopping Cart')) ?>"
                        class="action clear btn" id="empty_cart_button">
                    <span><?= $escaper->escapeHtml(__('Clear Shopping Cart')) ?></span>
                </button>
            </div>

        <?php endif ?>
        <?php if ($continueShoppingUrl): ?>
            <a href="<?= $escaper->escapeUrl($continueShoppingUrl) ?>"
               title="<?= $escaper->escapeHtmlAttr(__('Continue Shopping')) ?>"
               class="action text-red underline decoration-solid flex items-center gap-2 font-sen"
            >
                <svg xmlns="http://www.w3.org/2000/svg" width="7" height="14" viewBox="0 0 7 14" fill="none">
                    <path d="M0.000200272 6.79115C0.000200272 7.02039 0.0800924 7.24961 0.239541 7.42439L5.25958 12.9243C5.57891 13.2742 6.09666 13.2742 6.41587 12.9243C6.73508 12.5746 6.73508 12.0074 6.41587 11.6576L1.97386 6.79115L6.41571 1.92472C6.73492 1.57486 6.73492 1.00778 6.41571 0.658081C6.09651 0.308044 5.57876 0.308044 5.25942 0.658081L0.239386 6.15791C0.0799112 6.33278 0.000200272 6.56199 0.000200272 6.79115Z" fill="#B3261E"/>
                </svg>
                <span><?= $escaper->escapeHtml(__('Continue Shopping')) ?></span>
            </a>
        <?php endif; ?>
        <button type="submit"
                name="update_cart_action"
                data-cart-item-update=""
                value="update_qty"
                title="<?= $escaper->escapeHtmlAttr(__('Update Cart')) ?>"
                class="action update btn btn-primary w-full md:w-auto rounded-none font-sen"
        >
            <?= $escaper->escapeHtml(__('Update Cart')) ?>
        </button>
    </div>
</form>
<?= $block->getChildHtml('checkout.cart.order.actions') ?>
<?= $block->getChildHtml('shopping.cart.table.after') ?>
