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

use auctionforge\inc\abs\Model;
use auctionforge\inc\controllers\ManualAuctions;
use auctionforge\inc\controllers\PolylangSupport;
use auctionforge\inc\controllers\Settings;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\helpers\View;
use auctionforge\inc\model\Auction;

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

$auctionListKey = 'auction_list';
$archiveListKey = 'archive_list';
$pageAuctionListKey = SettingsHelper::getOption($auctionListKey, 0);
$pageArchiveListKey = SettingsHelper::getOption($archiveListKey, 0);
$hideEmptyAuctions = Model::toBoolean(SettingsHelper::getOption(Settings::HIDE_EMPTY_AUCTION, 'off'));
$archivePolylangId = 0;

if (PolylangSupport::isPolylangActive()) {
    $lang = pll_current_language();
    $auctionPolylangId = pll_get_post($pageAuctionListKey, $lang);
    $archivePolylangId = pll_get_post($pageArchiveListKey, $lang);
}

$cond = 'NOT IN';
$allowStatus = array('ARCHIVED', 'ENDED');
$isArchived = ($post->ID == $pageArchiveListKey || $post->ID == $archivePolylangId);
$order = 'ASC';
if ($isArchived) {
    $cond = 'IN';
    $order = 'DESC';
}

$queryAuctionParams = apply_filters('auctionforge_query_auction_params', array(
    'post_type'  => 'lot',
    'taxonomy'   => 'auction_number',
    'hide_empty' => intval($hideEmptyAuctions),
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => 'auction_state',
            'value' => $allowStatus,
            'compare' => $cond
        ),
        /*array(
            'key' => 'auction_state',
            'value' => 'PENDING',
            'compare' => '!='
        ),*/
    ),
    'order' => $order
), $isArchived);
$list_active_auctions = apply_filters('auctionforge_auction_list_filter', get_terms($queryAuctionParams));

// Filter out auctions that never actually ran (no ended days)
if ($isArchived) {
    $list_active_auctions = Auction::filterByEndedDays($list_active_auctions);
}

if ($isArchived) {
    usort($list_active_auctions, "sortAuctionDESC");
} else {
    usort($list_active_auctions, "sortAuctionASC");
}

// Fetch manual auctions based on page context
if ($isArchived) {
    $manual_auctions = ManualAuctions::getEndedManualAuctions();
} else {
    $manual_auctions = ManualAuctions::getUpcomingManualAuctions();
}

$userRule = wp_get_current_user();
$isAdmin = current_user_can('administrator');
$featureImage = get_the_post_thumbnail_url($post->ID, 'full');

echo View::render('templates.main.auction_list', compact('list_active_auctions', 'manual_auctions', 'isArchived', 'isAdmin', 'userRule', 'featureImage'));
