<?php

namespace auctionforge\inc\shortcodes;

use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\model\LotAnalytics;
use auctionforge\inc\abs\ImageModel;
use auctionforge\inc\model\LotImage;

class PopularLots
{
    public function init()
    {
        add_shortcode('bp_popular_lots', array($this, 'render_popular'));
        add_shortcode('bp_most_favorited', array($this, 'render_favorited'));
        add_shortcode('bp_trending_lots', array($this, 'render_trending'));
    }

    /**
     * [af_popular_lots limit="8" auction_id="" columns="4"]
     */
    public function render_popular($atts)
    {
        $atts = shortcode_atts(array(
            'title'      => __('Most Popular Lots', 'auctionforge'),
            'limit'      => 8,
            'auction_id' => '',
            'columns'    => 4,
            'period'     => '',
        ), $atts);

        if (SettingsHelper::getOption('enable_lot_analytics', 'off') !== 'on') {
            return '';
        }

        $termId = !empty($atts['auction_id']) ? intval($atts['auction_id']) : 0;
        $lots = LotAnalytics::getMostViewed(intval($atts['limit']), $termId, $atts['period']);

        if (empty($lots)) return '';

        return $this->renderGrid($lots, $atts['title'], intval($atts['columns']), 'views');
    }

    /**
     * [af_most_favorited limit="8" auction_id="" columns="4"]
     */
    public function render_favorited($atts)
    {
        $atts = shortcode_atts(array(
            'title'      => __('Most Favorited Lots', 'auctionforge'),
            'limit'      => 8,
            'auction_id' => '',
            'columns'    => 4,
        ), $atts);

        if (SettingsHelper::getOption('enable_lot_analytics', 'off') !== 'on') {
            return '';
        }

        $termId = !empty($atts['auction_id']) ? intval($atts['auction_id']) : 0;
        $lots = LotAnalytics::getMostFavorited(intval($atts['limit']), $termId);

        if (empty($lots)) return '';

        return $this->renderGrid($lots, $atts['title'], intval($atts['columns']), 'favorites');
    }

    /**
     * [af_trending_lots limit="8" days="7" columns="4"]
     */
    public function render_trending($atts)
    {
        $atts = shortcode_atts(array(
            'title'   => __('Trending Lots', 'auctionforge'),
            'limit'   => 8,
            'days'    => 7,
            'columns' => 4,
        ), $atts);

        if (SettingsHelper::getOption('enable_lot_analytics', 'off') !== 'on') {
            return '';
        }

        $lots = LotAnalytics::getTrending(intval($atts['limit']), intval($atts['days']));

        if (empty($lots)) return '';

        return $this->renderGrid($lots, $atts['title'], intval($atts['columns']), 'trending');
    }

    /**
     * Render the lot grid HTML
     */
    private function renderGrid($lots, $title, $columns, $type)
    {
        $currency = SettingsHelper::getOption('currency', '$');
        $server = SettingsHelper::getOption('server', '');
        $prefix = '';
        if (preg_match('/:\/\/([\w\-]+)\./', $server, $m)) {
            $prefix = $m[1];
        }

        $html = '<div class="af-lot-analytics-grid">';
        if (!empty($title)) {
            $html .= '<h3 class="af-lag-title">' . esc_html($title) . '</h3>';
        }
        $html .= '<div class="af-lag-items" style="grid-template-columns: repeat(' . $columns . ', 1fr);">';

        foreach ($lots as $lot) {
            $postId = isset($lot->post_id) ? $lot->post_id : 0;
            $permalink = get_permalink($postId);
            $lotName = '';
            if (!empty($lot->lot_name)) {
                $lotName = $lot->lot_name;
            } elseif (!empty($lot->post_title)) {
                $lotName = $lot->post_title;
            }

            $lotIndex = isset($lot->itemIndex) ? $lot->itemIndex : '';
            $auctionName = isset($lot->auction_name) ? $lot->auction_name : '';

            // Build thumbnail
            $thumbnail = '';
            if (!empty($lot->imagesBase) && !empty($lot->imagesListStr)) {
                $imagesList = explode(',', $lot->imagesListStr);
                if (!empty($imagesList[0])) {
                    $image = $imagesList[0];
                    if (!empty($lot->imagesCloned) && $lot->imagesCloned) {
                        $imgIndex = preg_replace('/\D+/', '', $image);
                        $thumbnail = ImageModel::IMAGE_HOST_CLONED . $prefix . '/cloned-images/' . $lot->imagesBase . '/' . $imgIndex . '/' . $image;
                    } else {
                        $thumbnail = ImageModel::IMAGE_HOST . 'w_300/' . $prefix . '_' . $lot->imagesBase . '_' . $image;
                    }
                }
            }

            if (empty($thumbnail)) {
                $thumbnail = plugins_url('img/not_found.jpg', dirname(dirname(__FILE__)));
            }

            // Stat badge
            $badge = '';
            if ($type === 'views' || $type === 'trending') {
                $count = isset($lot->view_count) ? $lot->view_count : (isset($lot->recent_views) ? $lot->recent_views : 0);
                $badge = '<span class="af-lag-badge af-lag-badge-views">' . number_format($count) . ' ' . _n('view', 'views', $count, 'auctionforge') . '</span>';
            } elseif ($type === 'favorites') {
                $count = isset($lot->favorite_count) ? $lot->favorite_count : 0;
                $badge = '<span class="af-lag-badge af-lag-badge-favs">&#9829; ' . number_format($count) . '</span>';
            }

            // Price
            $price = '';
            if (!empty($lot->soldBid) && $lot->soldBid > 0) {
                $price = '<span class="af-lag-price">' . __('Sold', 'auctionforge') . ': ' . $currency . number_format($lot->soldBid) . '</span>';
            } elseif (!empty($lot->startPrice) && $lot->startPrice > 0) {
                $price = '<span class="af-lag-price">' . $currency . number_format($lot->startPrice) . '</span>';
            }

            $html .= '<a href="' . esc_url($permalink) . '" class="af-lag-item">';
            $html .= '<div class="af-lag-thumb" style="background-image:url(\'' . esc_url($thumbnail) . '\')"></div>';
            $html .= '<div class="af-lag-info">';
            if (!empty($lotIndex)) {
                $html .= '<span class="af-lag-lot-num">' . LotHelper::printTranslateLot($lotIndex) . '</span>';
            }
            $html .= '<span class="af-lag-name">' . esc_html($lotName) . '</span>';
            if (!empty($auctionName)) {
                $html .= '<span class="af-lag-auction">' . esc_html($auctionName) . '</span>';
            }
            if (!empty($price)) $html .= $price;
            $html .= $badge;
            $html .= '</div>';
            $html .= '</a>';
        }

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

        // Inline CSS (only once)
        static $cssOutput = false;
        if (!$cssOutput) {
            $cssOutput = true;
            $html .= '<style>
.af-lot-analytics-grid { margin: 20px 0; }
.af-lag-title { font-size: 1.3em; font-weight: 600; margin-bottom: 12px; }
.af-lag-items { display: grid; gap: 16px; }
@media (max-width: 768px) { .af-lag-items { grid-template-columns: repeat(2, 1fr) !important; } }
@media (max-width: 480px) { .af-lag-items { grid-template-columns: 1fr !important; } }
.af-lag-item { display: block; border: 1px solid #e0e0e0; border-radius: 6px; overflow: hidden; text-decoration: none; color: inherit; background: #fff; transition: box-shadow 0.2s; }
.af-lag-item:hover { box-shadow: 0 2px 12px rgba(0,0,0,0.12); text-decoration: none; color: inherit; }
.af-lag-thumb { width: 100%; aspect-ratio: 1; background-size: contain; background-position: center; background-repeat: no-repeat; background-color: #f5f5f5; }
.af-lag-info { padding: 10px; display: flex; flex-direction: column; gap: 3px; }
.af-lag-lot-num { font-size: 0.8em; color: #e67e22; font-weight: 600; }
.af-lag-name { font-size: 0.9em; font-weight: 500; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.af-lag-auction { font-size: 0.78em; color: #888; }
.af-lag-price { font-size: 0.85em; font-weight: 600; color: #333; }
.af-lag-badge { display: inline-block; font-size: 0.75em; padding: 2px 6px; border-radius: 3px; margin-top: 2px; }
.af-lag-badge-views { background: #e3f2fd; color: #1565c0; }
.af-lag-badge-favs { background: #fce4ec; color: #c62828; }
</style>';
        }

        return $html;
    }
}
