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

/**
 * Calcula e exibe o quadro de líderes para um post específico.
 */
function imz_get_leaderboard_html($post_id) {
    // Cache por música: evita uma query sem limite a cada visualização da página
    $cache_key = 'imz_leaderboard_' . absint($post_id);
    $cached_html = get_transient($cache_key);
    if (false !== $cached_html) {
        return $cached_html;
    }

    $query_args = [
        'post_type'      => 'impulsionamento',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'meta_query'     => [
            'relation' => 'AND',
            ['key' => 'post_id_original', 'value' => $post_id],
            ['key' => 'status', 'value' => 'aprovado'],
            ['key' => 'nome', 'value' => '', 'compare' => '!='],
            ['key' => 'nome', 'value' => 'Admin', 'compare' => '!='],
            ['key' => 'metodo_pagamento', 'value' => 'Admin', 'compare' => '!='],
        ]
    ];
    $boosts = new WP_Query($query_args);
    $leaderboard = [];
    if ($boosts->have_posts()) {
        while ($boosts->have_posts()) {
            $boosts->the_post();
            $name = get_post_meta(get_the_ID(), 'nome', true);
            $amount = (int) get_post_meta(get_the_ID(), 'valor', true);
            if ($amount <= 0) continue; // Ignorar boosts sem valor (admin)
            if (isset($leaderboard[$name])) {
                $leaderboard[$name] += $amount;
            } else {
                $leaderboard[$name] = $amount;
            }
        }
    }
    wp_reset_postdata();
    if (empty($leaderboard)) {
        set_transient($cache_key, '', 15 * MINUTE_IN_SECONDS);
        return '';
    }
    arsort($leaderboard);
    $top_contributors = array_slice($leaderboard, 0, 5, true);

    $html = '<div class="imz-leaderboard-container">';
    $html .= '<h3>🏆 Top Impulsionadores desta Música</h3>';
    $html .= '<ol class="imz-leaderboard-list">';
    
    $i = 0;
    foreach ($top_contributors as $name => $total_amount) {
        $medals = ['🥇', '🥈', '🥉'];
        // --- LÓGICA DE RANKING MELHORADA ---
        if (isset($medals[$i])) {
            $rank_display = $medals[$i];
        } else {
            $rank_display = '<span class="imz-leaderboard-rank">' . ($i + 1) . '</span>';
        }

        $html .= '<li>';
        $html .= '<span class="imz-leaderboard-medal">' . $rank_display . '</span>';
        $html .= '<span class="imz-leaderboard-name">' . esc_html($name) . '</span>';
        $html .= '<span class="imz-leaderboard-amount">' . esc_html($total_amount) . ' MT</span>';
        $html .= '</li>';
        $i++;
    }

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

    set_transient($cache_key, $html, 15 * MINUTE_IN_SECONDS);
    return $html;
}

/**
 * Invalida os caches de leaderboard (da música e global) quando um boost muda.
 * Chamar sempre que um impulsionamento é aprovado/alterado/removido.
 */
function imz_invalidate_leaderboard_cache($boost_id) {
    if (get_post_type($boost_id) !== 'impulsionamento') return;
    $music_id = get_post_meta($boost_id, 'post_id_original', true);
    if ($music_id) {
        delete_transient('imz_leaderboard_' . absint($music_id));
    }
    delete_transient('imz_global_leaderboard_data');
}
add_action('save_post_impulsionamento', 'imz_invalidate_leaderboard_cache', 10, 1);
add_action('before_delete_post', 'imz_invalidate_leaderboard_cache', 10, 1);
add_action('wp_trash_post', 'imz_invalidate_leaderboard_cache', 10, 1);


add_shortcode('top_impulsionadores_geral', 'imz_render_global_leaderboard');
/**
 * Renderiza o shortcode para exibir o quadro de líderes global de todo o site.
 */
function imz_render_global_leaderboard($atts) {
    $atts = shortcode_atts(['limite' => 10], $atts);
    $limit = absint($atts['limite']);

    $cache_key = 'imz_global_leaderboard_data';
    $leaderboard_data = get_transient($cache_key);

    if (false === $leaderboard_data) {
        // ... (código de query inalterado) ...
        $leaderboard_data = [];
        $query_args = [
            'post_type'      => 'impulsionamento',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_query'     => [
                'relation' => 'AND',
                ['key' => 'status', 'value' => 'aprovado'],
                ['key' => 'nome', 'value' => '', 'compare' => '!='],
                ['key' => 'nome', 'value' => 'Admin', 'compare' => '!='],
                ['key' => 'metodo_pagamento', 'value' => 'Admin', 'compare' => '!='],
            ]
        ];
        $all_boosts = new WP_Query($query_args);
        if ($all_boosts->have_posts()) {
            while ($all_boosts->have_posts()) {
                $all_boosts->the_post();
                $name = get_post_meta(get_the_ID(), 'nome', true);
                $amount = (int) get_post_meta(get_the_ID(), 'valor', true);
                if ($amount <= 0) continue; // Ignorar boosts sem valor (admin)
                if (isset($leaderboard_data[$name])) {
                    $leaderboard_data[$name] += $amount;
                } else {
                    $leaderboard_data[$name] = $amount;
                }
            }
        }
        wp_reset_postdata();
        arsort($leaderboard_data);
        set_transient($cache_key, $leaderboard_data, HOUR_IN_SECONDS);
    }

    if (empty($leaderboard_data)) {
        return '<p>Ainda não há impulsionamentos suficientes para gerar um ranking. Seja o primeiro!</p>';
    }

    $top_contributors = array_slice($leaderboard_data, 0, $limit, true);

    ob_start();
    ?>
    <div class="imz-leaderboard-container imz-global-leaderboard">
        <h3>🌟 Hall da Fama: Top <?php echo $limit; ?> Impulsionadores do Site</h3>
        <p style="text-align: center; margin-top: -15px; margin-bottom: 25px; color: #6b7280;">Este ranking é atualizado de hora a hora.</p>
        <ol class="imz-leaderboard-list">
            <?php 
            $i = 0;
            foreach ($top_contributors as $name => $total_amount) :
                $medals = ['🥇', '🥈', '🥉'];
                // --- LÓGICA DE RANKING MELHORADA ---
                if (isset($medals[$i])) {
                    $rank_display = $medals[$i];
                } else {
                    $rank_display = '<span class="imz-leaderboard-rank">' . ($i + 1) . '</span>';
                }
            ?>
                <li>
                    <span class="imz-leaderboard-medal"><?php echo $rank_display; ?></span>
                    <span class="imz-leaderboard-name"><?php echo esc_html($name); ?></span>
                    <span class="imz-leaderboard-amount"><?php echo esc_html(number_format($total_amount)); ?> MT</span>
                </li>
            <?php 
                $i++;
            endforeach; 
            ?>
        </ol>
    </div>
    <?php
    return ob_get_clean();
}