<?php
if (!defined('ABSPATH')) exit;

// =============================================================================
// TOP MÚSICAS — ranking público por reproduções (tabela wp_imz_plays)
// Shortcode: [imz_top_musicas periodo="7" limite="10" titulo="..."]
//
// Os plays são credíveis: mínimo de 30s de escuta e limites por IP
// (ver imz_ajax_track_play no ficheiro principal). Resultado cacheado 30 min.
// =============================================================================

add_shortcode('imz_top_musicas', 'imz_render_top_musicas');
function imz_render_top_musicas($atts) {
    $atts = shortcode_atts([
        'periodo' => 7,
        'limite'  => 10,
        'titulo'  => '',
    ], $atts, 'imz_top_musicas');

    $days  = max(1, min(90, absint($atts['periodo'])));
    $limit = max(1, min(50, absint($atts['limite'])));
    $title = $atts['titulo'] !== '' ? $atts['titulo'] : sprintf('🔥 Top Músicas dos Últimos %d Dias', $days);

    $cache_key = "imz_top_musicas_{$days}_{$limit}";
    $rows = get_transient($cache_key);

    if (false === $rows) {
        global $wpdb;
        $table = $wpdb->prefix . 'imz_plays';
        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
            return '';
        }
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT p.music_id, COUNT(*) as plays
             FROM $table p
             INNER JOIN {$wpdb->posts} po ON po.ID = p.music_id AND po.post_status = 'publish' AND po.post_type = 'post'
             WHERE p.play_date >= DATE_SUB(NOW(), INTERVAL %d DAY)
             GROUP BY p.music_id
             ORDER BY plays DESC
             LIMIT %d",
            $days, $limit
        ));
        set_transient($cache_key, $rows, 30 * MINUTE_IN_SECONDS);
    }

    if (empty($rows)) {
        return '<p class="imz-top-musicas-empty">Ainda não há reproduções suficientes para gerar o ranking.</p>';
    }

    ob_start();
    ?>
    <div class="imz-leaderboard-container imz-top-musicas">
        <h3><?php echo esc_html($title); ?></h3>
        <ol class="imz-leaderboard-list">
            <?php
            $medals = ['🥇', '🥈', '🥉'];
            foreach ($rows as $i => $row) :
                $music_title = get_the_title($row->music_id);
                if (!$music_title) continue;
                $rank_display = $medals[$i] ?? '<span class="imz-leaderboard-rank">' . ($i + 1) . '</span>';
                $plays_fmt = function_exists('imz_format_number_short') ? imz_format_number_short((int) $row->plays) : number_format_i18n((int) $row->plays);
            ?>
                <li>
                    <span class="imz-leaderboard-medal"><?php echo $rank_display; ?></span>
                    <span class="imz-leaderboard-name"><a href="<?php echo esc_url(get_permalink($row->music_id)); ?>"><?php echo esc_html($music_title); ?></a></span>
                    <span class="imz-leaderboard-amount"><?php echo esc_html($plays_fmt); ?> plays</span>
                </li>
            <?php endforeach; ?>
        </ol>
    </div>
    <?php
    return ob_get_clean();
}
