<?php
/**
 * @var $list_active_auctions array
 * @var $manual_auctions array
 * @var $isArchived bool
 * @var $isAdmin bool
 * @var $userRules string
 * @var $featureImage string
 * Version: 2.0
 * Author: Lakhov Viktor
 * Author URI: https://smoothbyteit.dev
 **/

use auctionforge\inc\controllers\Settings;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\helpers\View;
use auctionforge\inc\ImageUploader;

if (!isset($manual_auctions)) {
    $manual_auctions = array();
}

$layoutStyle = SettingsHelper::getOption(Settings::LAYOUT_STYLE, 'classic');

get_header(); ?>

<?php  if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <div class="bp-container-fluid">

    <?php if ($layoutStyle === 'minimal') { ?>
        <div class="bp-header__content-minimal minimal-header-centered">
            <div class="minimal-header-left">
                <h1 class="title"><?php the_title(); ?></h1>
            </div>
        </div>
    <?php } else { ?>
        <?php if (!empty($featureImage)) { ?>
            <div class="bp-header bp-header-simple bp-row bp-single-page" style="background-image: url('<?= $featureImage ?>')">
        <?php } else { ?>
            <div class="bp-header bp-header-simple bp-row bp-single-page">
        <?php } ?>
        <div class="bp-header__overlay"></div>
        <div class="bp-header__content">
            <h1><?php the_title(); ?></h1>
        </div>
        </div>
    <?php } ?>

    </div>
    <div id="bp-notice-block" class="bp-main-container"></div>
    <?php do_action('bp_notice_action') ?>
    <?php do_action('bp_before_content_auction_list') ?>
    <div class="bp-container">
        <?php do_action('bp_before_inner_content_auction_list') ?>
        <div class="bp-content bp-content_archive bp-justify-between bp-row bp-no-margin">
            <div class="bp-col bp-content__text bp-center">
                <?php the_content(); ?>
            </div>
        </div>
        <div id="auction-list-section" class="bp-row <?= ($isArchived) ? "bp-archive-list" : "bp-upcoming-list" ?>">
            <div class="bp-col bp-lots bp-auctions bp-d-flex bp-f-wrap bp-f-center bp-no-margin">
                <?php
                /**
                 * Build a unified list of renderable auction items (Bidspirit + Manual)
                 * Each item has: 'type' => 'bidspirit'|'manual', 'sort_datetime', and render data
                 */
                $unifiedAuctionItems = array();
                $activeDayCounter = null;

                // --- Process Bidspirit auctions into renderable items ---
                if (!empty($list_active_auctions)) {
                    $viewPdf = SettingsHelper::getOption('view_pdf', 'on');
                    foreach ($list_active_auctions as $auction) {
                        $featureImage = '';
                        $auctionDocs = null;

                        $auctionDays = SettingsHelper::getTermOption($auction->term_id, 'auction_days');
                        $auctionDays = apply_filters('auctionforge_auction_days_filter', $auctionDays, $isArchived);

                        $auctionState = SettingsHelper::getTermOption($auction->term_id, 'auction_state');
                        $mainLinkToAuction = $linkToAuction = get_category_link($auction->term_id);

                        $target = null;
                        if ($viewPdf == 'on' && $isArchived) {
                            $auctionDocs = SettingsHelper::getTermOption($auction->term_id, 'auction_docs');
                            if (!empty($auctionDocs->catalog)) {
                                $linkToAuction = ImageUploader::HOST_FILES . $auctionDocs->catalog;
                                $target = 'target="_blank"';
                            } else {
                                $auctionDocs = null;
                            }
                        }

                        if (!empty($auctionDays)) {
                            $countDays = count($auctionDays);

                            if ($isArchived) {
                                $auctionDays = array_reverse($auctionDays);
                            }

                            foreach ($auctionDays as $index => $auctionDay) {
                                if (!empty($auctionDay->image)) {
                                    $featureImage = $auctionDay->image;
                                } else {
                                    $featureImage = LotHelper::getPlaceholderImage();
                                }

                                if (count($auctionDays) > 1 && $auctionDocs == null) {
                                    $uri = parse_url($linkToAuction);

                                    if (!empty($uri['query'])) {
                                        $uriParams = array();
                                        parse_str($uri['query'], $uriParams);
                                    }

                                    if (isset($auctionDay->index)) {
                                        $uriParams['part'] = $auctionDay->index;
                                    } else {
                                        if ($isArchived) {
                                            $uriParams['part'] = $countDays;
                                        } else {
                                            $uriParams['part'] = ($index + 1);
                                        }
                                    }

                                    $mainLinkToAuction = $uri['path'] . "part/" . $uriParams['part'] . "/";
                                } else {
                                    $activeDayCounter = 0;
                                }

                                if (!empty($auctionDay->unknownExactDate) && $auctionDay->unknownExactDate) {
                                    $dateTime = date_i18n('F Y', strtotime($auctionDay->date));
                                } else {
                                    $dateTime = date_i18n('F d, Y', strtotime($auctionDay->date . 'T' . $auctionDay->time));
                                }

                                $auction->name = apply_filters('auctionforge_auction_name_build', $auction->name, $auction);

                                if (!empty($uriParams['part'])) {
                                    $auctionTitle = $auction->name . ",&nbsp;" . __("part", "auctionforge") . "&nbsp;" .
                                        $uriParams['part'];
                                } else {
                                    $auctionTitle = $auction->name;
                                }

                                if ($isArchived) {
                                    if (isset($auctionDay->ended) && $auctionDay->ended == true) {
                                        $activeDayCounter++;
                                    } else {
                                        $countDays--;
                                        continue;
                                    }
                                } else {
                                    if (isset($auctionDay->ended) && $auctionDay->ended == true) {
                                        continue;
                                    } else {
                                        // TODO: Need test if we have 1 active auction
                                        if (is_null($activeDayCounter)) {
                                            $activeDayCounter = 0;
                                        }
                                        $activeDayCounter++;
                                    }
                                }

                                // Build sort datetime from auction day data
                                $sortDatetime = '';
                                if (!empty($auctionDay->auctionStarted)) {
                                    $sortDatetime = $auctionDay->auctionStarted;
                                } elseif (!empty($auctionDay->date)) {
                                    $sortDatetime = $auctionDay->date . ' ' . (!empty($auctionDay->time) ? $auctionDay->time : '00:00');
                                }

                                $auctionParams = array(
                                    'auction' => $auction,
                                    'auctionDay' => $auctionDay,
                                    'featureImage' => $featureImage,
                                    'auctionState' => $auctionState,
                                    'dateTime' => $dateTime,
                                    'isAdmin' => $isAdmin,
                                    'linkToAuction' => $mainLinkToAuction,
                                    'target' => $target,
                                    'auctionTitle' => $auctionTitle
                                );
                                $auctionParams = apply_filters('auctionforge_auction_params', $auctionParams);

                                $unifiedAuctionItems[] = array(
                                    'type' => 'bidspirit',
                                    'sort_datetime' => $sortDatetime,
                                    'params' => $auctionParams,
                                );

                                if ($isArchived) {
                                    $countDays--;
                                }
                            }
                            $uriParams = null;
                        }
                    }
                }

                // --- Process manual auctions into renderable items ---
                if (!empty($manual_auctions)) {
                    foreach ($manual_auctions as $manualAuction) {
                        if (is_null($activeDayCounter)) {
                            $activeDayCounter = 0;
                        }
                        $activeDayCounter++;

                        $unifiedAuctionItems[] = array(
                            'type' => 'manual',
                            'sort_datetime' => $manualAuction->datetime,
                            'manualAuction' => $manualAuction,
                        );
                    }
                }

                // --- Sort the unified list by date ---
                if (!empty($unifiedAuctionItems)) {
                    usort($unifiedAuctionItems, function($a, $b) use ($isArchived) {
                        $dtA = strtotime($a['sort_datetime']);
                        $dtB = strtotime($b['sort_datetime']);
                        if ($dtA == $dtB) return 0;
                        if ($isArchived) {
                            return ($dtA > $dtB) ? -1 : 1;
                        }
                        return ($dtA < $dtB) ? -1 : 1;
                    });
                }

                // --- Render the unified list ---
                if (!empty($unifiedAuctionItems)) {
                    foreach ($unifiedAuctionItems as $item) {
                        if ($item['type'] === 'manual') {
                            echo View::render('templates.parts.auction-ready-manual', array(
                                'manualAuction' => $item['manualAuction'],
                                'isAdmin' => $isAdmin,
                            ));
                        } else {
                            if ($isAdmin) {
                                echo View::render('templates.parts.auction-admin', $item['params']);
                            } else {
                                echo View::render('templates.parts.auction-ready', $item['params']);
                            }
                        }
                    }
                }

                if (empty($unifiedAuctionItems) || $activeDayCounter === null || $activeDayCounter == 0) {
                    do_action('bp_auction_list_not_found', [
                        'isArchived' => $isArchived
                    ]);
                }
                ?>
            </div>
        </div>
        <?php do_action('bp_after_inner_content_auction_list') ?>
    </div>
    <?php do_action('bp_after_content_auction_list') ?>
<?php endwhile; ?>
    <div class="wrp-navigation bp-d-flex bp-f-center bp-mb-30">
        <?php the_posts_pagination() ?>
    </div>
<?php else: ?>
    <div class="bp-d-flex bp-mb-30 bp-padding-text">
        <p><?= __('Auctions not found', 'auctionforge') ?>!</p>
    </div>
<?php endif;  ?>

<?php get_footer(); ?>
