<?php
/**
 * The Template for displaying a single manual auction.
 *
 * Override this template by copying it to yourtheme/auctionforge/single-manual_auction.php
 */

use auctionforge\inc\controllers\ManualAuctions;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;

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

get_header(); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php
    $post_id = get_the_ID();
    $prefix = ManualAuctions::META_PREFIX;

    $date = get_post_meta($post_id, $prefix . 'date', true);
    $time = get_post_meta($post_id, $prefix . 'time', true);
    $auction_type = get_post_meta($post_id, $prefix . 'auction_type', true);
    $auction_link = get_post_meta($post_id, $prefix . 'auction_link', true);
    $auction_status = get_post_meta($post_id, $prefix . 'status', true);
    $gallery_ids = get_post_meta($post_id, $prefix . 'gallery', true);

    if (!is_array($gallery_ids)) {
        $gallery_ids = !empty($gallery_ids) ? array_filter(array_map('intval', explode(',', $gallery_ids))) : array();
    }

    $featureImage = get_the_post_thumbnail_url($post_id, 'full');
    $auctionTitle = get_the_title();
    $auctionTypeLabel = ($auction_type === 'online') ? __('Online', 'auctionforge') : __('In Person', 'auctionforge');

    $dateDisplay = '';
    if (!empty($date)) {
        $dateDisplay = date_i18n('F d, Y', strtotime($date));
        if (!empty($time) && $time !== '00:00') {
            $dateDisplay .= ', ' . date_i18n('g:i A', strtotime($date . 'T' . $time));
        }
    }

    $hasExternalLink = !empty($auction_link);

    // Get auction list page for back link
    $auctionListKey = SettingsHelper::getOption('auction_list', 0);
    $backLink = $auctionListKey ? get_permalink($auctionListKey) : home_url('/');
    $bgImage = $auctionListKey ? get_the_post_thumbnail_url($auctionListKey, 'full') : '';
    ?>

    <style>
        .ma-single-auction { max-width: 960px; margin: 0 auto; padding: 30px 20px 60px; }
        .ma-single-auction .ma-back-link { display: inline-block; margin-bottom: 25px; text-decoration: none; font-size: 14px; color: #333; }
        .ma-single-auction .ma-back-link:hover { color: #000; text-decoration: underline; }
        .ma-single-auction .ma-auction-title { text-align: center; font-size: 28px; font-weight: 600; margin: 0 0 10px; text-transform: uppercase; letter-spacing: 1px; }
        .ma-single-auction .ma-auction-meta { text-align: center; margin-bottom: 25px; font-size: 15px; color: #444; }
        .ma-single-auction .ma-auction-meta span { display: inline; }
        .ma-single-auction .ma-auction-meta .ma-separator { margin: 0 8px; }
        .ma-single-auction .ma-status-ended { color: #a00; font-weight: 600; }
        .ma-single-auction .ma-external-link-wrap { text-align: center; margin-bottom: 30px; }
        .ma-single-auction .ma-description { margin-bottom: 40px; line-height: 1.7; font-size: 15px; }
        .ma-single-auction .ma-description p { margin-bottom: 1em; line-height: 1.7; }
        .ma-single-auction .ma-section-title { text-align: center; font-size: 20px; font-weight: 600; margin-bottom: 20px; text-transform: uppercase; letter-spacing: 0.5px; }

        .ma-gallery-grid { display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; }
        .ma-gallery-grid .ma-gallery-item { width: calc(25% - 8px); cursor: pointer; overflow: hidden; border-radius: 4px; }
        .ma-gallery-grid .ma-gallery-item img { width: 100%; height: 200px; object-fit: cover; display: block; transition: transform 0.3s ease; }
        .ma-gallery-grid .ma-gallery-item:hover img { transform: scale(1.05); }
        @media (max-width: 768px) { .ma-gallery-grid .ma-gallery-item { width: calc(50% - 5px); } .ma-gallery-grid .ma-gallery-item img { height: 150px; } }
        @media (max-width: 480px) { .ma-gallery-grid .ma-gallery-item { width: 100%; } }

        .ma-lightbox-overlay { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.92); z-index:99999; justify-content:center; align-items:center; }
        .ma-lightbox-overlay.active { display:flex; }
        .ma-lightbox-overlay img { max-width:90%; max-height:85vh; object-fit:contain; border-radius:4px; }
        .ma-lightbox-close { position:absolute; top:20px; right:30px; color:#fff; font-size:36px; cursor:pointer; background:none; border:none; z-index:100000; line-height:1; }
        .ma-lightbox-nav { position:absolute; top:50%; transform:translateY(-50%); color:#fff; font-size:48px; cursor:pointer; background:none; border:none; padding:20px; z-index:100000; line-height:1; }
        .ma-lightbox-prev { left:10px; }
        .ma-lightbox-next { right:10px; }
        .ma-lightbox-close:hover, .ma-lightbox-nav:hover { opacity:0.7; }
    </style>

    <div class="bp-container-fluid">
        <?php if (!empty($bgImage)) { ?>
            <div class="bp-header bp-row bp-single-page" style="background-image: url('<?= esc_url($bgImage) ?>')">
        <?php } elseif (!empty($featureImage)) { ?>
            <div class="bp-header bp-row bp-single-page" style="background-image: url('<?= esc_url($featureImage) ?>')">
        <?php } else { ?>
            <div class="bp-header bp-row bp-single-page">
        <?php } ?>
            <div class="bp-header__overlay"></div>
            <div class="bp-header__content">
                <p class="title"><?= esc_html($auctionTitle) ?></p>
                <p class="bp-header__time"><?= $dateDisplay ?></p>
            </div>
        </div>
    </div>

    <div id="bp-notice-block" class="bp-main-container"></div>

    <div class="ma-single-auction">

        <a href="<?= esc_url($backLink) ?>" class="ma-back-link">&larr; <?= __("Back to auctions", "auctionforge") ?></a>

        <h1 class="ma-auction-title"><?= esc_html($auctionTitle) ?></h1>

        <div class="ma-auction-meta">
            <?php if ($dateDisplay) { ?>
                <span><?= $dateDisplay ?></span>
            <?php } ?>
            <?php if ($auctionTypeLabel) { ?>
                <span class="ma-separator">&mdash;</span>
                <span><?= $auctionTypeLabel ?></span>
            <?php } ?>
            <?php if ($auction_status === 'ended') { ?>
                <span class="ma-separator">&mdash;</span>
                <span class="ma-status-ended"><?= __('Ended', 'auctionforge') ?></span>
            <?php } ?>
        </div>

        <?php if ($hasExternalLink) { ?>
            <div class="ma-external-link-wrap">
                <a href="<?= esc_url($auction_link) ?>" target="_blank" class="bp-btn bp-btn-default" style="display:inline-flex;"><?= __('View auction on external site', 'auctionforge') ?></a>
            </div>
        <?php } ?>

        <div class="ma-description">
            <?php the_content(); ?>
        </div>

        <?php if (!empty($gallery_ids)) { ?>
            <h2 class="ma-section-title"><?= __('Gallery', 'auctionforge') ?></h2>
            <div class="ma-gallery-grid">
                <?php foreach ($gallery_ids as $index => $img_id) {
                    $img_id = intval($img_id);
                    if ($img_id <= 0) continue;
                    $img_url = wp_get_attachment_image_url($img_id, 'medium_large');
                    $img_full = wp_get_attachment_image_url($img_id, 'full');
                    $img_alt = get_post_meta($img_id, '_wp_attachment_image_alt', true);
                    if (!$img_url) continue;
                    ?>
                    <div class="ma-gallery-item" data-index="<?= $index ?>" data-full="<?= esc_url($img_full) ?>">
                        <img src="<?= esc_url($img_url) ?>" alt="<?= esc_attr($img_alt ? $img_alt : $auctionTitle) ?>" />
                    </div>
                <?php } ?>
            </div>

            <div class="ma-lightbox-overlay" id="maLightbox">
                <button class="ma-lightbox-close" id="maLightboxClose">&times;</button>
                <button class="ma-lightbox-nav ma-lightbox-prev" id="maLightboxPrev">&#8249;</button>
                <img src="" alt="" id="maLightboxImg" />
                <button class="ma-lightbox-nav ma-lightbox-next" id="maLightboxNext">&#8250;</button>
            </div>

            <script>
            (function() {
                var items = document.querySelectorAll('.ma-gallery-item');
                var overlay = document.getElementById('maLightbox');
                var img = document.getElementById('maLightboxImg');
                var currentIndex = 0;
                var urls = [];

                items.forEach(function(item, i) {
                    urls.push(item.getAttribute('data-full'));
                    item.addEventListener('click', function() {
                        currentIndex = i;
                        img.src = urls[currentIndex];
                        overlay.classList.add('active');
                        document.body.style.overflow = 'hidden';
                    });
                });

                function closeLightbox() {
                    overlay.classList.remove('active');
                    document.body.style.overflow = '';
                }

                document.getElementById('maLightboxClose').addEventListener('click', closeLightbox);
                overlay.addEventListener('click', function(e) { if (e.target === overlay) closeLightbox(); });

                document.getElementById('maLightboxPrev').addEventListener('click', function(e) {
                    e.stopPropagation();
                    currentIndex = (currentIndex - 1 + urls.length) % urls.length;
                    img.src = urls[currentIndex];
                });
                document.getElementById('maLightboxNext').addEventListener('click', function(e) {
                    e.stopPropagation();
                    currentIndex = (currentIndex + 1) % urls.length;
                    img.src = urls[currentIndex];
                });

                document.addEventListener('keydown', function(e) {
                    if (!overlay.classList.contains('active')) return;
                    if (e.key === 'Escape') closeLightbox();
                    if (e.key === 'ArrowLeft') { currentIndex = (currentIndex - 1 + urls.length) % urls.length; img.src = urls[currentIndex]; }
                    if (e.key === 'ArrowRight') { currentIndex = (currentIndex + 1) % urls.length; img.src = urls[currentIndex]; }
                });
            })();
            </script>
        <?php } ?>

    </div>

<?php endwhile; ?>
<?php else: ?>
    <div class="bp-d-flex bp-mb-30 bp-padding-text">
        <p><?= __('Auction not found', 'auctionforge') ?>!</p>
    </div>
<?php endif; ?>

<?php get_footer(); ?>
