<?php

namespace auctionforge\inc\shortcodes;

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 AuctionList
{
    public function init()
    {
        add_shortcode('bp_auction_list', array($this, 'render_shortcode'));
    }

    public function render_shortcode($atts)
    {
        $atts = shortcode_atts(array(
            'type'         => 'upcoming',
            'layout'       => 'card',
            'category'     => '',
            'title'        => '',
            'limit'        => 0,
            'register_url' => '',
        ), $atts);

        $type = strtolower($atts['type']);
        $layout = strtolower($atts['layout']);
        $categoryFilter = strtoupper(trim($atts['category']));
        $title = $atts['title'];
        $limit = intval($atts['limit']);
        $registerUrl = $atts['register_url'];

        $hideEmptyAuctions = Model::toBoolean(SettingsHelper::getOption(Settings::HIDE_EMPTY_AUCTION, 'off'));

        $auctionCards = array();

        // --- Bidspirit auctions ---
        if ($type === 'past') {
            $bsAuctions = Auction::getArchiveAuction();
            $bsAuctions = Auction::filterByEndedDays($bsAuctions);
            if (!empty($bsAuctions)) {
                usort($bsAuctions, "sortAuctionDESC");
            }
        } else {
            $bsAuctions = 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'   => array('ARCHIVED', 'ENDED'),
                        'compare' => 'NOT IN'
                    )
                ),
                'order' => 'ASC'
            ), false);
            $bsAuctions = apply_filters('auctionforge_auction_list_filter', get_terms($bsAuctions));
            if (!empty($bsAuctions)) {
                usort($bsAuctions, "sortAuctionASC");
            }
        }

        if (!empty($bsAuctions)) {
            foreach ($bsAuctions as $key => $auction) {
                if ($categoryFilter !== '') {
                    $auctionNumber = SettingsHelper::getTermOption($auction->term_id, 'auction_number');
                    $firstLetter = strtoupper(substr(trim($auctionNumber), 0, 1));
                    if ($firstLetter !== $categoryFilter) {
                        continue;
                    }
                }

                $auctionDays = SettingsHelper::getTermOption($auction->term_id, 'auction_days');
                $auctionDays = apply_filters('auctionforge_auction_days_filter', $auctionDays, false);
                $auctionDays = \auctionforge\inc\controllers\CoverImageOverride::applyToDays($auctionDays, $auction->term_id);

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

                if ($type === 'past') {
                    $auctionDays = array_reverse($auctionDays);
                }

                $countDays = count($auctionDays);
                $auctionState = SettingsHelper::getTermOption($auction->term_id, 'auction_state');
                $mainLinkToAuction = $linkToAuction = get_category_link($auction->term_id);
                $isArchived = Auction::isAuctionArchived($auctionState);

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

                    if ($countDays > 1) {
                        $uri = parse_url($linkToAuction);
                        if (!empty($uri['query'])) {
                            $uriParams = array();
                            parse_str($uri['query'], $uriParams);
                        }
                        if ($type === 'past') {
                            $uriParams['part'] = $countDays - $index;
                        } else {
                            $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 ($type === 'upcoming' && isset($auctionDay->ended) && $auctionDay->ended == true) {
                        continue;
                    }

                    $auctionParams = array(
                        'index'           => $key . "-" . $index,
                        'auction'         => $auction,
                        'auctionDay'      => $auctionDay,
                        'featureImage'    => $featureImage,
                        'auctionState'    => $auctionState,
                        'dateTimeRaw'     => $dateTimeRaw,
                        'dateTime'        => $dateTime,
                        'linkToAuction'   => $mainLinkToAuction,
                        'auctionTitle'    => $auctionTitle,
                        'registerUrl'     => $registerUrl,
                        'isArchive'       => $isArchived,
                        'target'          => $linkToAuction,
                        'activeDayCounter' => 0,
                    );

                    $templateName = $this->getTemplateName($layout, $type, false);

                    $auctionCards[] = array(
                        'datetime' => $dateTimeRaw,
                        'html'     => View::render($templateName, $auctionParams)
                    );

                    $uriParams = null;
                }
            }
        }

        // --- Manual auctions ---
        if ($type === 'past') {
            $manualAuctions = ManualAuctions::getEndedManualAuctions();
        } else {
            $manualAuctions = ManualAuctions::getUpcomingManualAuctions();
        }

        if (!empty($manualAuctions)) {
            foreach ($manualAuctions as $mKey => $manualAuction) {
                if ($categoryFilter !== '') {
                    $manualCat = isset($manualAuction->category) ? strtoupper(trim($manualAuction->category)) : '';
                    if ($manualCat !== $categoryFilter) {
                        continue;
                    }
                }

                $manualDatetime = $manualAuction->date . ' ' . $manualAuction->time;
                $templateName = $this->getTemplateName($layout, $type, true);

                $auctionCards[] = array(
                    'datetime' => $manualDatetime,
                    'html'     => View::render($templateName, array(
                        'index'          => 'manual-' . $mKey,
                        'manualAuction'  => $manualAuction,
                        'registerUrl'    => $registerUrl,
                    ))
                );
            }
        }

        if (empty($auctionCards)) {
            return '';
        }

        if ($type === 'past') {
            usort($auctionCards, function ($a, $b) {
                return strtotime($b['datetime']) - strtotime($a['datetime']);
            });
        } else {
            usort($auctionCards, function ($a, $b) {
                return strtotime($a['datetime']) - strtotime($b['datetime']);
            });
        }

        if ($limit > 0) {
            $auctionCards = array_slice($auctionCards, 0, $limit);
        }

        if ($layout === 'wide') {
            return $this->renderWideLayout($auctionCards, $title);
        } else {
            return $this->renderCardLayout($auctionCards, $title);
        }
    }

    private function getTemplateName($layout, $type, $isManual)
    {
        if ($layout === 'wide') {
            return $isManual
                ? 'templates/shortcodes/upcoming-auction-wide-manual'
                : 'templates/shortcodes/upcoming-auction-wide';
        }

        if ($isManual) {
            return 'templates/shortcodes/upcoming-auction-manual';
        }

        if ($type === 'past') {
            return 'templates/shortcodes/past-auction';
        }

        return 'templates/shortcodes/upcoming-auction';
    }

    private function renderCardLayout($auctionCards, $title)
    {
        $html = '<div class="bp-row">';
        if ($title != '') {
            $html .= '<div class="bp-d-flex bp-f-center"><div class="bt-main__title">' . esc_html($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;
    }

    private function renderWideLayout($auctionCards, $title)
    {
        $html = '<div class="bpw-upcoming-wrap">';

        $html .= '<style>
            .bpw-upcoming-wrap { max-width: 80%; margin: 0 auto; padding: 0 15px; }
            .bpw-upcoming-title { text-align: center; font-size: 32px; font-weight: 400; margin: 0 0 5px; font-family: Georgia, "Times New Roman", serif; }
            .bpw-upcoming-title-line { width: 80px; height: 3px; background: #c8553d; margin: 0 auto 30px; }
            .bpw-auction-card { display: flex; gap: 35px; padding: 35px 0; border-bottom: 1px solid #ddd; align-items: stretch; }
            .bpw-auction-card:first-of-type { border-top: 1px solid #ddd; }
            .bpw-auction-img { flex: 0 0 320px; max-width: 320px; display: flex; align-items: center; }
            .bpw-auction-img a, .bpw-auction-img .bpw-img-wrap { display: block; }
            .bpw-auction-img img { width: 100%; height: auto; display: block; }
            .bpw-auction-body { flex: 1; min-width: 0; display: flex; flex-direction: column; justify-content: space-between; }
            .bpw-auction-body .bpw-title { font-size: 28px; font-weight: 400; margin: 0 0 8px; line-height: 1.3; font-family: Georgia, "Times New Roman", serif; }
            .bpw-auction-body .bpw-title a { color: inherit; text-decoration: none; }
            .bpw-auction-body .bpw-title a:hover { text-decoration: underline; }
            .bpw-auction-body .bpw-desc { font-size: 15px; line-height: 1.7; color: #333; margin-bottom: 0; flex: 1; }
            .bpw-auction-body .bpw-date { font-size: 16px; font-weight: 700; margin-bottom: 2px; margin-top: auto; }
            .bpw-auction-body .bpw-countdown-row { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; flex-wrap: wrap; background: none; padding: 0; }
            .bpw-auction-body .bpw-countdown-row .bp-countdown { background: none !important; padding: 0 !important; }
            .bpw-auction-body .bpw-countdown-label { font-size: 14px; color: #333; }
            .bpw-auction-body .bpw-cd-num { font-size: 15px; font-weight: 700; color: #c8553d; background: none; padding: 0; }
            .bpw-auction-body .bpw-cd-unit { font-size: 14px; font-weight: 600; color: #c8553d; margin-right: 4px; }
            .bpw-auction-body .bpw-buttons { display: flex; gap: 10px; flex-wrap: wrap; }
            .bpw-auction-body .bpw-buttons a,
            .bpw-auction-body .bpw-buttons span { display: block; flex: 1; padding: 14px 30px; font-size: 14px; font-weight: 700; text-transform: uppercase; text-align: center; text-decoration: none; letter-spacing: 1px; box-sizing: border-box; }
            .bpw-btn-primary { background: #333; color: #fff !important; border: 1px solid #333; }
            .bpw-btn-primary:hover { background: #555; border-color: #555; }
            .bpw-btn-secondary { background: #333; color: #fff !important; border: 1px solid #333; }
            .bpw-btn-secondary:hover { background: #555; border-color: #555; }
            .bpw-btn-disabled { background: #999; color: #fff !important; border: 1px solid #999; cursor: default; }
            .bpw-status-text { color: #c00; font-weight: 600; font-size: 14px; }
            .bpw-live-btn { display: block; background: #ff0000; color: #fff !important; padding: 14px 20px; text-align: center; text-decoration: none; font-weight: 700; text-transform: uppercase; animation: bpw-flash 1s infinite alternate; }
            @keyframes bpw-flash { from { opacity: 1; } to { opacity: 0.3; } }
            .bpw-live-btn:hover { background: #cc0000; animation: none; }
            @media (max-width: 768px) {
                .bpw-upcoming-wrap { max-width: 95%; }
                .bpw-auction-card { flex-direction: column; gap: 15px; }
                .bpw-auction-img { flex: none; max-width: 100%; }
                .bpw-auction-body .bpw-buttons a, .bpw-auction-body .bpw-buttons span { min-width: 140px; padding: 10px 20px; }
            }
            /* Hide Register button when user is logged in to BidSpirit */
            body.bp-login .bpw-btn-secondary[data-micromodal-trigger="modal-register"] { display: none !important; }
            body.bp-login .bpw-buttons .bpw-btn-primary,
            body.bp-login .bpw-buttons .bpw-btn-disabled { flex: 1 1 100%; }
        </style>
        <script>
        (function(){
            function applyLoggedInState(){
                if(!document.body.classList.contains("bp-login"))return;
                var w=document.querySelectorAll(".bpw-buttons");
                for(var i=0;i<w.length;i++){w[i].classList.add("bpw-buttons-single");}
            }
            applyLoggedInState();
            var obs=new MutationObserver(function(m){
                for(var i=0;i<m.length;i++){
                    if(m[i].attributeName==="class"){
                        applyLoggedInState();
                        if(document.body.classList.contains("bp-login")){obs.disconnect();}
                    }
                }
            });
            if(document.body){obs.observe(document.body,{attributes:true});}
        })();
        </script>';

        if ($title != '') {
            $html .= '<h2 class="bpw-upcoming-title">' . esc_html($title) . '</h2>';
            $html .= '<div class="bpw-upcoming-title-line"></div>';
        }

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

        $html .= '</div>';
        return $html;
    }
}
