<?php

namespace auctionforge\inc\shortcodes;

use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\helpers\View;
use auctionforge\inc\model\LotAnalytics;

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

    /**
     * [bp_popular_lots limit="8" auction_id="" tmp="slider" mobile_cols="2"]
     */
    public function render_popular($atts)
    {
        $atts = shortcode_atts(array(
            'title'       => __('Most Popular Lots', 'auctionforge'),
            'limit'       => 8,
            'auction_id'  => '',
            'tmp'         => 'slider',
            'mobile_cols' => 2,
            'period'      => '',
            'loadmore'    => 0,
        ), $atts);

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

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

        return $this->renderLots($results, $atts);
    }

    /**
     * [bp_most_favorited limit="8" auction_id="" tmp="slider" mobile_cols="2"]
     */
    public function render_favorited($atts)
    {
        $atts = shortcode_atts(array(
            'title'       => __('Most Favorited Lots', 'auctionforge'),
            'limit'       => 8,
            'auction_id'  => '',
            'tmp'         => 'slider',
            'mobile_cols' => 2,
            'loadmore'    => 0,
        ), $atts);

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

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

        return $this->renderLots($results, $atts);
    }

    /**
     * [bp_trending_lots limit="8" days="7" tmp="slider" mobile_cols="2"]
     */
    public function render_trending($atts)
    {
        $atts = shortcode_atts(array(
            'title'       => __('Trending Lots', 'auctionforge'),
            'limit'       => 8,
            'days'        => 7,
            'tmp'         => 'slider',
            'mobile_cols' => 2,
            'loadmore'    => 0,
        ), $atts);

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

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

        return $this->renderLots($results, $atts);
    }

    /**
     * Convert analytics results to WP_Post objects and render via existing templates
     */
    private function renderLots($results, $atts)
    {
        if (empty($results)) return '';

        // Collect post IDs from analytics results
        $postIds = array();
        foreach ($results as $row) {
            $pid = isset($row->post_id) ? intval($row->post_id) : 0;
            if ($pid > 0) $postIds[] = $pid;
        }

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

        // Fetch WP_Post objects in the same order as analytics results
        $posts = get_posts(array(
            'post__in'       => $postIds,
            'post_type'      => 'lot',
            'post_status'    => 'publish',
            'posts_per_page' => count($postIds),
            'orderby'        => 'post__in',
        ));

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

        $showEstimatedPriceInItemsList = false;
        $showEstimatedPrice = SettingsHelper::isChecked('force_show_estimated_price');
        if ($showEstimatedPrice) {
            $showEstimatedPriceInItemsList = $showEstimatedPrice;
        }

        $limit = intval($atts['limit']);
        $title = $atts['title'];

        if ($atts['tmp'] === 'grid') {
            $template = 'shortcodes.lots';
        } else {
            $template = 'widgets.slider';
        }

        return View::render('templates.' . $template, array(
            'title'                         => $title,
            'lots'                          => $posts,
            'limit'                         => $limit,
            'hiddenPrice'                   => false,
            'showEstimatedPriceInItemsList' => $showEstimatedPriceInItemsList,
            'displayStartPriceInCatalog'    => true,
            'loadmore'                      => intval($atts['loadmore']),
            'mobile_cols'                   => intval($atts['mobile_cols']),
            'args'                          => array(
                'before_widget' => '',
                'after_widget'  => '',
                'before_title'  => '<h3 class="bt-main__title">',
                'after_title'   => '</h3>',
            ),
        ));
    }
}
