<?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 Generic.WhiteSpace.ScopeIndent
// phpcs:disable Magento2.Files.LineLength.MaxExceeded

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\ProductStockItem;
use Magento\Checkout\Block\Cart\Item\Renderer;
use Magento\Framework\Escaper;

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

$item = $block->getItem();
$product = $item->getProduct();
$isVisibleProduct = $product->isVisibleInSiteVisibility();

$stockItemViewModel = $viewModels->require(ProductStockItem::class);
$qty = $stockItemViewModel->isQtyDecimal($product)
    ? $block->getQty()
    : (int)$block->getQty();

// Generate related products data
$relatedProducts = [];
try {
    $relatedProductCollection = $product->getRelatedProductCollection()
        ->addAttributeToSelect('*')
        ->setPositionOrder()
        ->addStoreFilter();

    foreach ($relatedProductCollection as $relatedProduct) {
        $relatedProducts[] = [
            'id' => $relatedProduct->getId(),
            'name' => $relatedProduct->getName(),
            'image' => $block->getImage($relatedProduct, 'cart_page_product_thumbnail')->getImageUrl(),
            'price' => '£' . number_format($relatedProduct->getFinalPrice(), 2),
            'rating' => $relatedProduct->getRatingSummary() ? $relatedProduct->getRatingSummary() / 20 : 0
        ];
    }
} catch (\Exception $e) {
    $relatedProducts = [
        [
            'id' => 1,
            'name' => 'Sample Product 1',
            'image' => $block->getImage($product, 'cart_page_product_thumbnail')->getImageUrl(),
            'price' => '$29.99',
            'rating' => 4.5
        ],
        [
            'id' => 2,
            'name' => 'Sample Product 2',
            'image' => $block->getImage($product, 'cart_page_product_thumbnail')->getImageUrl(),
            'price' => '$19.99',
            'rating' => 4.0
        ]
    ];
}
$relatedProductsJson = json_encode($relatedProducts, JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS);
?>

<div class="cart item bg-white shadow-banyo-shadow mb-5 border-2">
    <div class="flex flex-col md:flex-row lg:gap-4 px-3 md:px-4 lg:items-center">
        <!-- Product Image -->
        <div class="w-24 flex-shrink-0 md:py-2 hidden md:block">
            <?= $block->getImage($block->getProductForThumbnail(), 'cart_page_product_thumbnail')
                ->setTemplate('Magento_Catalog::product/image.phtml')
                ->toHtml() ?>
        </div>

        <div class="flex-1 flex">
            <div class="md:hidden">
                <div class="w-24 h-auto flex-shrink-0 lg:py-2">
                    <?= $block->getImage($block->getProductForThumbnail(), 'cart_page_product_thumbnail')
                        ->setTemplate('Magento_Catalog::product/image.phtml')
                        ->toHtml() ?>
                </div>
                <div class="text-xl text-black font-bold lg:mt-2">
                    <?= $block->getRowTotalHtml($item) ?>
                </div>
                <div class="flex items-center justify-between mt-0 mb-3  md:hidden">
<!--                    <span  class="text-red text-sm font-medium ">You’ve saved </span>
                    <span  class="text-red text-sm font-medium "><?php
/*                        $product_orignalprice = $item->getProduct()->getPrice();
                        $discountedprice = $item->getPriceInclTax();
                        $todatlsaving = $product_orignalprice - $discountedprice;
                        $itemSaving = $todatlsaving * $qty;

                        if ($itemSaving > 0) {
                            echo $block->convertPrice($itemSaving, true);
                        } else {
                            echo $block->convertPrice(0, true);
                        }
                        */?></span>
-->
                </div>
            </div>

            <!-- Product Details -->
            <div class="flex-1">
                <div class="font-semibold text-sm lg:text-base 2xl:text-xl mb-1 pt-3 md:pt-6 lg:pt-0">
                    <?php if ($block->hasProductUrl()): ?>
                        <a href="<?= $escaper->escapeUrl($block->getProductUrl()) ?>" class="hover:underline">
                            <?= $escaper->escapeHtml($block->getProductName()) ?>
                        </a>
                    <?php else: ?>
                        <?= $escaper->escapeHtml($block->getProductName()) ?>
                    <?php endif; ?>
                </div>
                <div class="text-xs lg:text-sm font-inter mt-1">
                    Product code: <?= $escaper->escapeHtml($product->getSku()) ?>
                </div>

                <?php if ($options = $block->getOptionList()): ?>
                    <dl class="text-sm text-black">
                        <?php foreach ($options as $option): ?>
                            <?php $formatedOptionValue = $block->getFormatedOptionValue($option) ?>
                            <div class="flex">
                                <dt class="font-medium mr-2"><?= $escaper->escapeHtml($option['label']) ?>:</dt>
                                <dd>
                                    <?php if (isset($formatedOptionValue['full_view'])): ?>
                                        <?= $escaper->escapeHtml($formatedOptionValue['full_view']) ?>
                                    <?php else: ?>
                                        <?= $escaper->escapeHtml($formatedOptionValue['value'], ['span', 'a']) ?>
                                    <?php endif; ?>
                                </dd>
                            </div>
                        <?php endforeach; ?>
                    </dl>
                <?php endif; ?>

                <?php if ($messages = $block->getMessages()): ?>
                    <div class="mt-2">
                        <?php foreach ($messages as $message): ?>
                            <div class="text-sm text-red-600">
                                <?= $escaper->escapeHtml($message['text']) ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?>
                <?php if ($addInfoBlock): ?>
                    <div class="text-sm mt-2">
                        <?= $addInfoBlock->setItem($item)->toHtml() ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="hidden md:block">
            <svg xmlns="http://www.w3.org/2000/svg" width="2" height="167" viewBox="0 0 2 220" fill="none">
                <path d="M0.75 0L0.75001 220" stroke="#777A81"/>
            </svg>
        </div>

        <!-- Quantity + Price Column -->
        <div class="flex md:flex-col md:ml-3 items-center lg:items-end gap-2 w-full md:w-auto py-3">
            <div class="flex items-center gap-4">
                <div class="flex items-center justify-end gap-2">
                    <?= $block->getActions($item) ?>
                </div>

                <div x-data="{ qty: <?= (int)$qty ?> }"
                     class="flex items-center border rounded overflow-hidden justify-between">
                    <button type="button" @click="qty = Math.max(1, qty - 1)"
                            class="w-8 h-11 bg-gray-100 hover:bg-gray-200 text-black text-lg">−</button>
                    <input id="cart-<?= $escaper->escapeHtmlAttr($item->getId()) ?>-qty"
                           name="cart[<?= $escaper->escapeHtmlAttr($item->getId()) ?>][qty]"
                           x-model.number="qty"
                           :value="qty"
                           type="number"
                           min="1"
                           step="any"
                           class="w-12 text-center border-0 focus:ring-0 focus:outline-none font-medium text-black h-11"
                           required
                           data-role="cart-item-qty"/>
                    <button type="button" @click="qty++"
                            class="w-8 h-11 bg-gray-100 hover:bg-gray-200 text-black text-lg">+</button>
                </div>
            </div>



            <div class="text-xl text-black font-bold lg:mt-2 hidden md:block">
                <?= $block->getRowTotalHtml($item) ?>
            </div>


            <div class="flex items-center justify-between mt-0 mb-3 hidden md:block">
             <!--   <span  class="text-red text-base font-medium ">You’ve saved </span>
                <span  class="text-red text-base font-medium "><?php
/*                    $product_orignalprice = $item->getProduct()->getPrice();
                    $discountedprice = $item->getPriceInclTax();
                    $todatlsaving = $product_orignalprice - $discountedprice;
                    $itemSaving = $todatlsaving * $qty;

                    if ($itemSaving > 0) {
                        echo $block->convertPrice($itemSaving, true);
                    } else {
                        echo $block->convertPrice(0, true);
                    }
                    */?></span>
-->
            </div>

            <!-- Essential Items Popup Button + Logic -->
            <div x-data="{
                    showEssentialItems: false,
                    relatedProducts: [],
                    init() {
                        try {
                            this.relatedProducts = JSON.parse('<?= $escaper->escapeHtml($relatedProductsJson) ?>');
                        } catch (e) {
                            console.error('Parsing error:', e);
                            this.relatedProducts = [];
                        }
                    }
                }">
                <?php if (!empty($relatedProductsJson) && $relatedProductsJson !== '[]'): ?>
                    <button type="button"
                            @click="showEssentialItems = true"
                            class="btn btn-primary bg-header-darker text-primary-darker px-3 md:px-4 text-sm md:text-base rounded-none">
                        Add essential items
                    </button>
                <?php endif; ?>

                <!-- Essential Items Popup -->
                <div x-show="showEssentialItems"
                     class="fixed inset-0 z-50 flex items-center justify-center"
                     style="background-color: rgba(0,0,0,0.5);"
                     x-cloak>
                    <div class="bg-white p-6 rounded-lg shadow-lg max-w-4xl w-full max-h-[80vh] overflow-y-auto">
                        <div class="flex justify-between items-center mb-4">
                            <h3 class="text-xl font-bold">Don’t forget your essential Items</h3>
                            <button @click="showEssentialItems = false" class="text-gray-500 hover:text-gray-700">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <div>Before you continue, there are some essential items which we recommend you may need</div>

                        <!-- Related Products -->
                        <div x-show="relatedProducts.length > 0" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <template x-for="product in relatedProducts" :key="product.id">
                                <div class="border p-4 rounded">
                                    <div class="flex items-center space-x-4">
                                        <img :src="product.image" :alt="product.name" class="w-20 h-20 object-contain">
                                        <div>
                                            <h4 class="font-medium" x-text="product.name"></h4>
                                            <p class="text-red-600 font-bold" x-html="product.price"></p>
                                            <div class="flex items-center mt-2">
                                                <template x-for="i in 5">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4"
                                                         :class="i <= product.rating ? 'text-yellow-400' : 'text-gray-300'"
                                                         fill="currentColor" viewBox="0 0 24 24">
                                                        <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2
                                                        9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
                                                    </svg>
                                                </template>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <div x-show="relatedProducts.length === 0" class="text-center py-8">
                            <p class="text-lg text-gray-600">No essential items available for this product.</p>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
