<?php

namespace auctionforge\inc\shortcodes;

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

class CoolDownToSale
{
    public function init() {
        add_shortcode('bp_cooldown_sale', array($this, 'cooldown_sale'));
    }

    public function cooldown_sale($atts)
    {
        $atts = shortcode_atts( array(
            'title'            => '',
            'category'         => '',
            'exclude_category' => '',
        ), $atts );
        extract($atts);
        $title = $atts['title'];
        $categoryFilter = strtoupper(trim($atts['category']));
        $excludeCategories = array_filter(array_map(function($c) {
            return strtoupper(trim($c));
        }, explode(',', $atts['exclude_category'])));
        $allowStatus = array('ARCHIVED', 'ENDED');
        $hideEmptyAuctions = Model::toBoolean(SettingsHelper::getOption(Settings::HIDE_EMPTY_AUCTION, 'off'));

        // Collect all auction cards with their datetime for sorting
        $auctionCards = array();

        // --- Bidspirit auctions ---
        $auctions = 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' => 'NOT IN'
                )
            ),
            'order' => 'ASC'
        ), false);
        $auctions = apply_filters('auctionforge_auction_list_filter', get_terms($auctions));

        if (!empty($auctions)) {
            usort($auctions, "sortAuctionASC");

            foreach ($auctions as $key => $auction) {
                // Category filtering for Bidspirit auctions
                $auctionNumber = SettingsHelper::getTermOption($auction->term_id, 'auction_number');
                $firstLetter = strtoupper(substr(trim($auctionNumber), 0, 1));

                if ($categoryFilter !== '' && $firstLetter !== $categoryFilter) {
                    continue;
                }

                if (!empty($excludeCategories) && in_array($firstLetter, $excludeCategories, true)) {
                    continue;
                }
                $auctionDays = SettingsHelper::getTermOption($auction->term_id, 'auction_days');
                $auctionDays = apply_filters('auctionforge_auction_days_filter', $auctionDays, false);

                if (!is_array($auctionDays)) {
                    continue;
                }

                $countDays = count($auctionDays);

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

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

                    /**
                     * TODO: Test for $activeDayCounter
                     */
                    $activeDayCounter = 0;

                    if ($countDays > 1) {
                        $uri = parse_url($linkToAuction);

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

                        $uriParams['part'] = ($index + 1);
                        $mainLinkToAuction = $uri['path'] . "part/" . $uriParams['part'] . "/";
                    } else {
                        $uriParams = array();
                    }

                    $timeZone = "+00:00";
                    if (!empty($auctionDay->unknownExactDate)) {
                        $dateTime = date("Y-m-d H:i:s", strtotime($auctionDay->date . $timeZone));
                    } else {
                        $dateTime = date("Y-m-d H:i:s", strtotime($auctionDay->date . 'T' . $auctionDay->time . $timeZone));
                    }
                    $dateTimeRaw = $dateTime;
                    $dateTime = SettingsHelper::dateTimeFormat($dateTime);

                    $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 (isset($auctionDay->ended) && $auctionDay->ended == true) {
                        continue;
                    } else {
                        $activeDayCounter++;
                    }

                    $auctionParams = [
                        'index' => $key . "-" . $index,
                        'auction' => $auction,
                        'auctionDay' => $auctionDay,
                        'featureImage' => $featureImage,
                        'auctionState' => $auctionState,
                        'dateTimeRaw' => $dateTimeRaw,
                        'dateTime' => $dateTime,
                        'linkToAuction' => $mainLinkToAuction,
                        'auctionTitle' => $auctionTitle,
                        'activeDayCounter' => $activeDayCounter
                    ];

                    $auctionCards[] = array(
                        'datetime' => $dateTimeRaw,
                        'html' => View::render('templates/shortcodes/upcoming-auction', $auctionParams)
                    );

                    $uriParams = null;
                }
            }
        }

        // --- Manual auctions ---
        $manualAuctions = ManualAuctions::getUpcomingManualAuctions();
        if (!empty($manualAuctions)) {
            foreach ($manualAuctions as $mKey => $manualAuction) {
                // Category filtering for manual auctions
                $manualCat = isset($manualAuction->category) ? strtoupper(trim($manualAuction->category)) : '';

                if ($categoryFilter !== '' && $manualCat !== $categoryFilter) {
                    continue;
                }

                if (!empty($excludeCategories) && in_array($manualCat, $excludeCategories, true)) {
                    continue;
                }
                $manualDatetime = $manualAuction->date . ' ' . $manualAuction->time;

                $auctionCards[] = array(
                    'datetime' => $manualDatetime,
                    'html' => View::render('templates/shortcodes/upcoming-auction-manual', array(
                        'index' => 'manual-' . $mKey,
                        'manualAuction' => $manualAuction,
                    ))
                );
            }
        }

        // Sort all cards by datetime ASC
        if (!empty($auctionCards)) {
            usort($auctionCards, function($a, $b) {
                return strtotime($a['datetime']) - strtotime($b['datetime']);
            });

            $html = "<div class=\"bp-row\">";
            if ($title != "") {
                $html .= "<div class=\"bp-d-flex bp-f-center\"><div class=\"bt-main__title\">".$title."</div></div>";
            }
            $html .= "<div class=\"bp-col bp-lots bp-auctions bp-d-flex bp-f-wrap bp-f-center bp-no-margin\">";

            foreach ($auctionCards as $card) {
                $html .= $card['html'];
            }

            $html .= "</div></div>";

            return $html;
        }
    }
}
$cooldown = new CoolDownToSale();
$cooldown->init();
