<?php
/** @var WP_Term $auction */
/** @var WP_Post $post */

use auctionforge\inc\controllers\Settings;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\helpers\View;
use auctionforge\inc\ImageUploader;
use auctionforge\inc\model\Auction;
use auctionforge\inc\model\Lot;
use auctionforge\inc\model\LotMetaData;

if (!defined('ABSPATH')) {
    exit;
}

$auction = get_queried_object();

$usePagination = SettingsHelper::getOption('use_pagination', 'off');
$auctionDays = SettingsHelper::getTermOption($auction->term_id, 'auction_days');
// Normalise: auctions with no auction_days meta return null, which fataled the
// count()/foreach below under PHP 8 (count(null)) — white-screening the page.
if (!is_array($auctionDays)) {
    $auctionDays = [];
}
$auctionState = SettingsHelper::getTermOption($auction->term_id, 'auction_state');
$timeZoneName = SettingsHelper::getOption(Settings::OPTIONS_TIMEZONES, "");
$possibleBids = SettingsHelper::getOption('bids_in_catalog', 'off');
$catalogLayout = SettingsHelper::getOption(Settings::CATALOG_LAYOUT, 'standard');

$isArchived = Auction::isAuctionArchived($auctionState);

$auctionCatalog = null;
//$viewPdf = SettingsHelper::getOption('view_pdf', 'on');
$hiddenPdfInAuction = SettingsHelper::getTermOption($auction->term_id, 'auction_pdf', 'off');
$auctionDocs = SettingsHelper::getTermOption($auction->term_id, 'auction_docs');
if (!empty($auctionDocs->catalog) && $hiddenPdfInAuction == 'off') {
    $auctionCatalog = ImageUploader::HOST_FILES . $auctionDocs->catalog;
}

$showEstimatedPrice = SettingsHelper::isChecked('force_show_estimated_price');
if ($showEstimatedPrice) {
    $showEstimatedPriceInItemsList = $showEstimatedPrice;
} else {
    $showEstimatedPriceInItemsList = SettingsHelper::getTermOption($auction->term_id, 'auction_showEstimatedPriceInItemsList', false);
}
$displayStartPriceInCatalog = SettingsHelper::getTermOption($auction->term_id, 'auction_displayStartPriceInCatalog');

$categoryList = json_decode(SettingsHelper::getTermOption($auction->term_id, Auction::META_FIELD_TAGS, ''), true);

if (!empty($categoryList)) {
    global $wpdb;
    $tableName = $wpdb->prefix . LotMetaData::TABLE_LOT_META;
    $counts = $wpdb->get_results($wpdb->prepare(
        "SELECT categoryId, COUNT(*) as lot_count FROM {$tableName}
         WHERE termId = %d AND categoryId IS NOT NULL AND categoryId > 0
         GROUP BY categoryId",
        $auction->term_id
    ), OBJECT_K);

    $filteredList = array();
    foreach ($categoryList as $catId => $catName) {
        if (isset($counts[$catId]) && $counts[$catId]->lot_count > 0) {
            $filteredList[$catId] = $catName . ' (' . $counts[$catId]->lot_count . ')';
        }
    }
    $categoryList = $filteredList;
}

$auctionBg = SettingsHelper::getTermOption($auction->term_id, 'auction_bg');

$linksDays = [];
if (count($auctionDays) > 1) {
    $auctionLink = get_term_link($auction);
    foreach ($auctionDays as $key => $auctionDay) {
        $index = $key + 1;
        $linksDays[$index] = LotHelper::getAuctionLink($auction->term_id, $index);
    }
}

$part = get_query_var('part');
if (!empty($part) && !empty($auctionDays[intval($part) - 1])) {
    $auctionDay = $auctionDays[intval($part) - 1];
} else {
    //$auctionDay = null;
    //$query->set_404();
    //status_header(404);
    $auctionDay = $auctionDays[0];
}

$hiddenPrice = LotHelper::isHiddenLots($auctionDay);
$postAuctionSaleOpenedUntil = false;
if (isset($auctionDay->postAuctionSaleOpenedUntil)) {
    $postAuctionSaleOpenedUntil = LotHelper::isOpenedUntil($auctionDay->postAuctionSaleOpenedUntil);
}

if (!empty($auctionDay->unknownExactDate) && $auctionDay->unknownExactDate) {
    $dateTime = $auctionDay->date;
} else {
    $dateTime = $auctionDay->date . 'T' . $auctionDay->time;
}

$customDateFormat = SettingsHelper::getOption('custom_format_display_time', '');
$timeZoneLabel = SettingsHelper::getOption('time_zone_label', '');
if ($timeZoneLabel != '') {
    $timeZoneLabel = "(" . $timeZoneLabel . ")";
}
try {
    $newDateTime = new DateTime($dateTime);
} catch (Exception $e) {
    $newDateTime = new DateTime();
}
$dateTime = SettingsHelper::dateTimeFormat($dateTime);

$bgStyle = 'style="background-color: #ffffff"';
if ($auctionBg != '') {
    $bgStyle = 'style="background-color: ' . $auctionBg . ';"';
} else {
    $auctionBg = "#ffffff";
}
$part = get_query_var('part');
$part = (!empty($part)) ? $part : 0;

$auctionListKey = 'auction_list';
$pageAuctionListKey = SettingsHelper::getOption($auctionListKey, 0);
$bgImage = get_the_post_thumbnail_url($pageAuctionListKey, 'full');

global $wp_query;

$countLots = $wp_query->found_posts;

echo View::render('templates.main.auction', compact(
        'auction',
        'auctionDay',
        'auctionDays',
        'customDateFormat',
        'newDateTime',
        'timeZoneLabel',
        'auctionCatalog',
        'postAuctionSaleOpenedUntil',
        'part',
        'hiddenPrice',
        'countLots',
        'auctionBg',
        'showEstimatedPriceInItemsList',
        'displayStartPriceInCatalog',
        'bgImage',
        'bgStyle',
        'dateTime',
        'usePagination',
        'categoryList',
        'possibleBids',
        'isArchived',
        'timeZoneName',
        'linksDays',
        'catalogLayout'
));
