<?php
/**
 * @var $title string
 * @var $lots array
 * @var $args array
 * @var $random_mode bool
 */

use auctionforge\inc\controllers\BidspiritLots;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\model\Auction;
use auctionforge\inc\BidSpiritRequest;

$hash = "-" . rand(1000, 9999);
$isRandomMode = !empty($random_mode);

if (!empty($args['before_widget'])) {
    echo $args['before_widget'];
}
echo "<div class=\"bp-widget-block\">";

if ((!empty($lots) && is_array($lots)) && !empty($title)) {
    echo "<div class=\"bt-main__title\">{$title}</div>";
}

if (!empty($lots) && is_array($lots)) {

    // --- Pre-fetch live bid data from BidSpirit API ---
    $liveBidData = array();
    $postAuctionMap = array();
    $auctionBsIds = array();

    foreach ($lots as $lot) {
        $terms = get_the_terms($lot->ID, BidspiritLots::TAX_AUCTION_TYPE);
        if ($terms && !is_wp_error($terms)) {
            $term = reset($terms);
            $term = apply_filters('auctionforge_prepare_auction_object', $term);
            $bsId = SettingsHelper::getTermOption($term->term_id, 'auction_id');
            if ($bsId) {
                $lotHelper_tmp = new LotHelper($lot->ID);
                $itemIdx = $lotHelper_tmp->getOptionValue('lot_itemIndex', 0);
                if ($itemIdx !== false && $itemIdx !== 0) {
                    $postAuctionMap[$lot->ID] = array('bsId' => $bsId, 'itemIndex' => $itemIdx);
                    $auctionBsIds[$bsId] = true;
                }
            }
        }
    }

    $auctionBidCache = array();
    foreach (array_keys($auctionBsIds) as $bsId) {
        $cacheKey = 'af_widget_bids_' . $bsId;
        $cached = get_transient($cacheKey);
        if ($cached !== false) {
            $auctionBidCache[$bsId] = $cached;
            continue;
        }

        $data = array('auctionId' => $bsId, 'language' => 'en');
        $response = BidSpiritRequest::send('items/getAllItemsInfoForAuction.api', $data);
        $auctionItems = array();
        if (!empty($response['response'])) {
            $decoded = json_decode($response['response']);
            if (isset($decoded->response->itemsInfo)) {
                foreach ($decoded->response->itemsInfo as $idx => $info) {
                    $bidPrice = 0;
                    $soldPrice = 0;
                    if (!empty($info->leadingBid) && isset($info->leadingBid->price)) {
                        $bidPrice = $info->leadingBid->price;
                    }
                    if (!empty($info->soldBid) && isset($info->soldBid->price)) {
                        $soldPrice = $info->soldBid->price;
                    }
                    if ($bidPrice > 0 || $soldPrice > 0) {
                        $auctionItems[$idx] = array('leadingBid' => $bidPrice, 'soldBid' => $soldPrice);
                    }
                }
            }
        }
        set_transient($cacheKey, $auctionItems, 120);
        $auctionBidCache[$bsId] = $auctionItems;
    }

    foreach ($postAuctionMap as $postId => $info) {
        $bsId = $info['bsId'];
        $itemIdx = (string)$info['itemIndex'];
        if (isset($auctionBidCache[$bsId][$itemIdx])) {
            $liveBidData[$postId] = $auctionBidCache[$bsId][$itemIdx];
        }
    }
    // --- End pre-fetch ---

    $mCols = isset($mobile_cols) ? intval($mobile_cols) : 2;
    // In random mode, use a different outer class so the default Swiper init
    // (see app.js metaSlider: `.bt-wi-slider .swiper-container`) skips these
    // sliders — this lets us init our own instance with loop:true below.
    if ($isRandomMode) {
        echo "<div class=\"bt-wi-slider-loop bt-wi-slider-random bt-wi-slider_swiper\">";
    } else {
        echo "<div class=\"bt-wi-slider bt-wi-slider_swiper\">";
    }
    if ($mCols === 1) {
        echo "<span class=\"bp-lotlist-arrow arrow-left\">&#8249;</span>";
        echo "<span class=\"bp-lotlist-arrow arrow-right\">&#8250;</span>";
        echo "<style>@media(max-width:768px){.bt-wi-slider{position:relative}.bp-lotlist-arrow{display:flex;align-items:center;justify-content:center;position:absolute;top:0;width:30px;height:30px;background:rgba(0,0,0,0.25);border-radius:50%;color:#fff;font-size:18px;font-weight:bold;z-index:10;cursor:pointer;line-height:1}.bp-lotlist-arrow.arrow-left{left:2px}.bp-lotlist-arrow.arrow-right{right:2px}}@media(min-width:769px){.bp-lotlist-arrow{display:none!important}}</style>";
        echo "<script>(function(){function posArrows(){var img=document.querySelector('.bt-wi-slider .bp-lot__wrp-image');var arrows=document.querySelectorAll('.bp-lotlist-arrow');if(img&&arrows.length){var r=img.getBoundingClientRect();var p=img.closest('.bt-wi-slider').getBoundingClientRect();var center=r.top-p.top+(r.height/2)-15;arrows.forEach(function(a){a.style.top=center+'px'})}}if(document.readyState==='complete'){setTimeout(posArrows,300)}else{window.addEventListener('load',function(){setTimeout(posArrows,300)})}window.addEventListener('resize',posArrows)})();</script>";
    }
    echo "<div class=\"swiper-container bt-wi-lots_wrp\" data-mobile-cols=\"" . $mCols . "\">
            <div class=\"swiper-wrapper bp-lots bt-wi-lots\" data-hash=\"" . $hash . "\">";
    /** @var WP_Post $lot */
    $limitWords = apply_filters('auctionforge_lot_title_words', 8);
    foreach ($lots as $lot) { ?>
        <?php
        $lotHelper = new LotHelper($lot->ID);
        $featureImage = $lotHelper->getFeatureImage();

        $auctions = get_the_terms($lot->ID, BidspiritLots::TAX_AUCTION_TYPE);
        $auction = 0;
        if (!empty($auctions)) {
            $auctions[0] = apply_filters('auctionforge_prepare_auction_object', $auctions[0]);
            $auction = $auctions[0];
            $auctionId = SettingsHelper::getTermOption($auction->term_id, 'auction_id');
        } else {
            $auctionId = 0;
        }

        $title = $lotHelper->getOptionValue('lot_name', '');
        $content = $lot->post_content;
        $title = LotHelper::getLotTitle($title, $content);
        $lotIndex = $lotHelper->getOptionValue('lot_itemIndex', 0);
        $estimatedPrice = $lotHelper->getOptionValue('lot_estimatedPrice', 0);
        $hasEstimate = !empty($estimatedPrice) && $estimatedPrice != '' && $estimatedPrice != '0';

        $startPrice = $lotHelper->getOptionValue('lot_start_price', 0);
        $leadingBid = $lotHelper->getOptionValue('lot_leadingBid', 0);
        $soldBid = $lotHelper->getOptionValue('lot_soldBid', 0);

        // Override with live bid data from API if available
        if (isset($liveBidData[$lot->ID])) {
            if ($liveBidData[$lot->ID]['leadingBid'] > 0) {
                $leadingBid = $liveBidData[$lot->ID]['leadingBid'];
            }
            if ($liveBidData[$lot->ID]['soldBid'] > 0) {
                $soldBid = $liveBidData[$lot->ID]['soldBid'];
            }
        }

        // Get auction state
        $auctionState = '';
        if (!empty($auctions) && !is_wp_error($auctions)) {
            $auctionState = get_term_meta($auctions[0]->term_id, 'auction_state', true);
        }

        // Determine price display
        $priceClass = '';
        if ($soldBid != 0 && $soldBid > 0) {
            $priceDesc = __('Sold for', 'auctionforge');
            $price = LotHelper::formattedPrice($soldBid);
            $priceClass = 'bp-lead bp-bg-blue';
        } elseif ($leadingBid != 0 && $leadingBid > 0) {
            $priceDesc = __('Highest bid', 'auctionforge');
            $price = LotHelper::formattedPrice($leadingBid);
            $priceClass = 'bp-lead';
        } elseif ($auctionState === 'ENDED') {
            $priceDesc = '';
            $price = __('Unsold', 'auctionforge');
            $priceClass = '';
        } else {
            $priceDesc = __('Start price', 'auctionforge');
            $price = LotHelper::formattedPrice($startPrice);
        }

        $itemData = new stdClass();
        $itemData->title = $title;
        $itemData->content = $content;
        ?>
        <div id="single-lot-<?= $auctionId ?>-<?= $lotIndex ?><?= $hash ?>"
             class="bp-lot swiper-slide"
             data-lot-index="<?= $lotIndex ?>"
             data-auction-id="<?= $auctionId ?>"
             data-estimated-price="<?= $estimatedPrice ?>"
             data-content="<?= urlencode(json_encode($itemData)) ?>"
        >
            <a href="<?= get_the_permalink($lot->ID) ?>" class="bp-lot__wrp-image">
                <div class="bp-lot__image" style="background-image:url(<?= $featureImage ?>);"></div>
            </a>
            <div id="single-lot-<?= $auctionId ?>-<?= $lotIndex ?><?= $hash ?>-content" class="bp-lot__content">
                <div class="bp-lot__title">
                    <a href="<?= get_the_permalink($lot->ID) ?>"><span class="bp-title">
                                    <?= LotHelper::printTranslateLot($lotIndex) ?>:</span><?= $title ?>
                    </a>
                </div>
                <div class="bp-lot__message">
                    <?php if ($hasEstimate && !$isRandomMode) { ?>
                        <p class="bp-lot__message-inner bp-text-grey"><?= __('Estimated price', 'auctionforge') ?>: <strong><?= $estimatedPrice ?></strong></p>
                    <?php } ?>
                </div>
                <div class="bp-lot__tool <?= $priceClass ?>">
                    <?php if ($priceDesc) { ?>
                        <p class="bp-subtitle"><?= $priceDesc ?>:</p>
                    <?php } ?>
                    <p class="bp-price"><?= $price ?></p>
                </div>
            </div>
        </div>
    <?php }
    echo "</div>";
    echo "</div>";
    echo "</div>";

    if ($isRandomMode) {
        ?>
        <style>
            .bt-wi-slider-random { width: 100%; }
            .bt-wi-slider-random .swiper-wrapper { align-items: stretch; }
            .bt-wi-slider-random .bp-lot {
                height: auto;
                display: flex;
                flex-direction: column;
            }
            .bt-wi-slider-random .bp-lot__wrp-image { flex: 0 0 auto; }
            .bt-wi-slider-random .bp-lot__content {
                flex: 1;
                display: flex;
                flex-direction: column;
            }
            .bt-wi-slider-random .bp-lot__title a {
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
                text-overflow: ellipsis;
            }
            /* Hide the "LOT 106:" prefix only in random mode */
            .bt-wi-slider-random .bp-title { display: none; }
            .bt-wi-slider-random .bp-lot__tool { margin-top: auto; }
        </style>
        <script>
            (function () {
                function init() {
                    if (typeof SwiperBP === 'undefined') { return false; }
                    var nodes = document.querySelectorAll('.bt-wi-slider-loop .swiper-container');
                    if (!nodes.length) { return true; }
                    nodes.forEach(function (el) {
                        if (el.dataset.bpLoopInited === '1') { return; }
                        el.dataset.bpLoopInited = '1';
                        new SwiperBP(el, {
                            slidesPerView: 1,
                            loop: true,
                            breakpoints: {
                                320:  { slidesPerView: 2 },
                                640:  { slidesPerView: 3, spaceBetween: 10 },
                                990:  { slidesPerView: 4, spaceBetween: 15 },
                                1200: { slidesPerView: 5, spaceBetween: 20 }
                            },
                            autoplay: {
                                delay: 4000,
                                disableOnInteraction: false
                            }
                        });
                    });
                    return true;
                }
                if (!init()) {
                    // SwiperBP not loaded yet — retry on DOM ready / window load
                    if (document.readyState === 'loading') {
                        document.addEventListener('DOMContentLoaded', init);
                    }
                    window.addEventListener('load', init);
                }
            })();
        </script>
        <?php
    }
}
echo "</div>";
if (!empty($args['after_widget'])) {
    echo $args['after_widget'];
}
