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

    public function render_shortcode($atts)
    {
        $atts = shortcode_atts(array(
            'title' => '',
            'register_url' => '',
        ), $atts);

        $title = $atts['title'];
        $registerUrl = $atts['register_url'];
        $allowStatus = array('ARCHIVED', 'ENDED');
        $hideEmptyAuctions = Model::toBoolean(SettingsHelper::getOption(Settings::HIDE_EMPTY_AUCTION, 'off'));

        $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) {
                $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;
                }

                $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();
                    }

                    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;
                    }

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

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

                    $uriParams = null;
                }
            }
        }

        // --- Manual auctions ---
        $manualAuctions = ManualAuctions::getUpcomingManualAuctions();
        if (!empty($manualAuctions)) {
            foreach ($manualAuctions as $mKey => $manualAuction) {
                $manualDatetime = $manualAuction->date . ' ' . $manualAuction->time;

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

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

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

        $html = '<div class="bpw-upcoming-wrap">';

        // Self-contained CSS
        $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;
    }
}

$upcomingWide = new UpcomingAuctionWide();
$upcomingWide->init();
