<?php
/**
 * Hyvä Themes - Custom Small Product Card
 */

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\CurrentProduct;
use Magento\Catalog\Helper\Image as ImageHelper;
use Magento\Framework\Escaper;
use Magento\Framework\Pricing\RenderInterface;
use Magento\Review\Block\Product\ReviewRenderer;
use Magento\Framework\View\Element\Template;

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


$currentProductViewModel = $viewModels->require(CurrentProduct::class);
$product = $block->hasData('product') ? $block->getData('product') : $currentProductViewModel->get();
$clickForPrice = $product->getData('click_for_price');
$callForPrice = $product->getData('call_for_price');

if (!$product || !$product->getId()) {
    return;
}

/** @var ReviewRenderer $reviewRenderer */
$reviewRenderer = $block->getLayout()->createBlock(ReviewRenderer::class);
$reviewRenderer->setProduct($product);
$ratingHtml   = $reviewRenderer->getReviewsSummaryHtml($product, ReviewRenderer::FULL_VIEW, true);
$ratingCount  = $reviewRenderer->getReviewsCount();

$imageUrl = $block->getViewFileUrl(
    'Magento_Catalog::images/product/placeholder/image.jpg'
);
try {
    /** @var ImageHelper $imageHelper */
    // $imageHelper = $block->helper(Magento\Catalog\Helper\Image::class);
    // $imageUrl = $imageHelper->init($product, 'product_thumbnail_image')->getUrl();

    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $imageHelper  = $_objectManager->get('\Magento\Catalog\Helper\Image');
    $image_url = $imageHelper->init($product, 'product_base_image')->setImageFile($product->getFile())->getUrl();

} catch (\Exception $e) {
    // fallback handled above
}

$productUrl = $product->getProductUrl();
$productName = $product->getName();

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$imageHelper  = $_objectManager->get('\Magento\Catalog\Helper\Image');
$image_url = $imageHelper->init($product, 'product_base_image')->setImageFile($product->getFile())->getUrl();

?>

<div class="bg-white border hover:shadow-md p-4 rounded-lg shadow sticky top-[19vh] w-full hidden sm:block">
    <a href="<?= $escaper->escapeUrl($productUrl) ?>">
        <img
            src="<?= $escaper->escapeUrl($image_url) ?>"
            alt="<?= $escaper->escapeHtmlAttr($productName) ?>"
            class="rounded w-full object-cover mb-3"
        />
    </a>

    <a href="<?= $escaper->escapeUrl($productUrl) ?>" class="font-sen block text-gray-900 font-semibold text-base mb-2 " title="<?= $escaper->escapeHtmlAttr($productName) ?>">
        <?= $escaper->escapeHtml($productName) ?>
    </a>
    <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    // Instance of Pricing Helper
    if($clickForPrice || $callForPrice){
        $priceHtml='';
    }else {
        $priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data');

        $priceHtml = $priceHelper->currency($product->getFinalPrice(), true, false);
    }?>    <div class="flex items-center justify-between mb-2">
        <div class="text-xl font-bold text-red-600">
            <?php  echo $priceHtml ?>
        </div>
        <div class="flex items-center text-yellow-400 text-sm">

            <?= $ratingHtml ?>

            <?php if (!empty($ratingCount)): ?>
                <span class="ml-1 text-gray-500">(<?= $escaper->escapeHtml($ratingCount) ?>)</span>
            <?php endif; ?>
        </div>
    </div>

    <!--   <a href="<?php /*= $escaper->escapeUrl($productUrl) */?>" class="block bg-blue-900 hover:bg-blue-950 text-white text-center font-semibold py-2 rounded">
        Add To Basket
    </a>-->

    <?php
    $isConfigurable = $product->getTypeId() === \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE;
    $hasRequiredOptions = $product->getTypeInstance()->hasRequiredOptions($product);
    ?>

    <?php
    $clickForPrice = $product->getData('click_for_price');
    $callForPrice = $product->getData('call_for_price');
    $revealPrice = $block->getRequest()->getParam('reveal_price');

    $storeConfig = $viewModels->require(Hyva\Theme\ViewModel\StoreConfig::class);
    $storePhone = $storeConfig->getStoreConfig('general/store_information/phone');

    $heroicons = $viewModels->require(Hyva\Theme\ViewModel\HeroiconsOutline::class);
    $isInStock = $product->isAvailable();

    ?>

    <?php if ((!$clickForPrice && !$callForPrice || $revealPrice) && $isInStock): ?>
        <!-- Default Add to Cart Form -->
        <?php if ($isConfigurable || $hasRequiredOptions): ?>
            <div x-data="{ showError: false }" class="w-full">
                <button @click="showError = true"
                        class="block w-full btn bg-primary-darker">
                    <?= $escaper->escapeHtml(__('Add to Basket')) ?>
                </button>
                <template x-if="showError">
                    <div class="text-red-600 text-sm mt-2 text-center">
                        <?= $escaper->escapeHtml(__('Please select options before adding to cart.')) ?>
                    </div>
                </template>
            </div>
        <?php else: ?>
            <form action="<?= $escaper->escapeUrl($block->getUrl('checkout/cart/add')) ?>" method="post">
                <input type="hidden" name="product" value="<?= (int)$product->getId() ?>" />

                <input type="hidden"
                       name="<?= $escaper->escapeHtmlAttr(\Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED) ?>"
                       value="<?= $escaper->escapeHtmlAttr(base64_encode($block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]))) ?>" />

                <input type="hidden"
                       name="form_key"
                       value="<?= $escaper->escapeHtmlAttr($block->getFormKey()) ?>" />

                <button type="submit"
                        class="hidden w-full btn bg-primary-darker hover:bg-primary-dark text-white text-center font-semibold py-2 rounded">
                    <?= $escaper->escapeHtml(__('Add to Basket')) ?>
                </button>
            </form>

        <?php endif; ?>

    <?php elseif ($clickForPrice): ?>
        <!-- Click for Price Redirect -->
        <a href="<?= $escaper->escapeUrl($block->getUrl('callprice/form/index', ['id' => $product->getId()])) ?>"
           class="block w-full btn bg-primary-darker hidden text-center text-white font-semibold py-2 rounded">
            <?= $escaper->escapeHtml(__('Click for Price')) ?>
        </a>

    <?php elseif ($callForPrice): ?>
        <!-- Call for Price Popup -->
        <div x-data="{ showPhonePopup: false }" class="w-full">
            <button type="button"
                    @click="showPhonePopup = true"
                    class="bt btn bg-primary-darker w-full text-white text-center font-semibold py-2 rounded hidden">
                <?= $escaper->escapeHtml(__('Call for Price')) ?>
            </button>

            <div x-show="showPhonePopup"
                 class="fixed inset-0 z-50 flex items-center justify-center"
                 x-cloak>
                <div class="absolute inset-0 bg-black opacity-50" @click="showPhonePopup = false"></div>
                <div class="relative bg-white p-6 rounded-lg shadow-lg max-w-md mx-auto">
                    <div class="absolute top-2 right-2 cursor-pointer" @click="showPhonePopup = false">
                        <?= $heroicons->xHtml('w-6 h-6'); ?>
                    </div>
                    <h3 class="text-lg font-bold mb-4"><?= __('Call Us for Pricing') ?></h3>
                    <p class="mb-4"><?= __('Please call us at:') ?></p>
                    <div class="text-xl font-bold text-center mb-4">
                        <a href="tel:<?= $escaper->escapeHtmlAttr(preg_replace('/[^0-9+]/', '', $storePhone)) ?>" class="text-primary-darker hover:underline">
                            <?= $escaper->escapeHtml($storePhone) ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>





</div>
