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

// =============================================================================
// 0. ATIVAR SHORTCODES EM WIDGETS (sidebar, footer, etc.)
// =============================================================================
add_filter('widget_text', 'do_shortcode');
add_filter('widget_text_content', 'do_shortcode');
add_filter('widget_block_content', 'do_shortcode');

// =============================================================================
// 1. TABELA DE RECOMENDAÇÕES
// =============================================================================

function imz_install_recommendations_table() {
    global $wpdb;
    $table = $wpdb->prefix . 'imz_recommendations';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        music_id bigint(20) NOT NULL,
        user_ip varchar(45) DEFAULT '' NOT NULL,
        reaction varchar(10) DEFAULT 'like' NOT NULL,
        reaction_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id),
        UNIQUE KEY unique_vote (music_id, user_ip),
        INDEX music_id (music_id),
        INDEX reaction (reaction)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(IMZ_DIR . 'impulsionamento-musicas.php', 'imz_install_recommendations_table');

// =============================================================================
// 2. FUNÇÃO PARA OBTER CONTAGENS
// =============================================================================

function imz_get_recommendation_counts($music_id) {
    global $wpdb;
    $table = $wpdb->prefix . 'imz_recommendations';

    // Auto-criar tabela
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
        imz_install_recommendations_table();
    }

    $likes = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $table WHERE music_id = %d AND reaction = 'like'", $music_id
    ));
    $dislikes = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $table WHERE music_id = %d AND reaction = 'dislike'", $music_id
    ));

    return ['likes' => $likes, 'dislikes' => $dislikes, 'total' => $likes + $dislikes];
}

function imz_get_user_reaction($music_id) {
    global $wpdb;
    $table = $wpdb->prefix . 'imz_recommendations';
    $ip = function_exists('imz_get_user_ip') ? imz_get_user_ip() : sanitize_text_field($_SERVER['REMOTE_ADDR']);
    
    return $wpdb->get_var($wpdb->prepare(
        "SELECT reaction FROM $table WHERE music_id = %d AND user_ip = %s", $music_id, $ip
    ));
}

// =============================================================================
// 3. HTML DOS BOTÕES LIKE/DISLIKE
// =============================================================================

function imz_render_recommendation_buttons($music_id, $context = 'post') {
    $counts = imz_get_recommendation_counts($music_id);
    $user_reaction = imz_get_user_reaction($music_id);

    $like_active = $user_reaction === 'like' ? ' active' : '';
    $dislike_active = $user_reaction === 'dislike' ? ' active' : '';

    ob_start();
    ?>
    <div class="imz-rec-container" data-music-id="<?php echo esc_attr($music_id); ?>">
        <p class="imz-rec-label">Gostou desta música?</p>
        <div class="imz-rec-buttons">
            <button class="imz-rec-btn imz-rec-like<?php echo $like_active; ?>" data-reaction="like" title="Gostei">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></svg>
                <span class="imz-rec-count" id="imz-like-count-<?php echo $music_id; ?>"><?php echo number_format($counts['likes']); ?></span>
            </button>
            <button class="imz-rec-btn imz-rec-dislike<?php echo $dislike_active; ?>" data-reaction="dislike" title="Não gostei">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17"/></svg>
                <span class="imz-rec-count" id="imz-dislike-count-<?php echo $music_id; ?>"><?php echo number_format($counts['dislikes']); ?></span>
            </button>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

// =============================================================================
// 4. SHORTCODE [imz_recomendacao]
// =============================================================================

add_shortcode('imz_recomendacao', 'imz_recommendation_shortcode');
function imz_recommendation_shortcode($atts) {
    $atts = shortcode_atts(['id' => 0], $atts);
    $music_id = absint($atts['id']);
    if ($music_id === 0) {
        global $post;
        $music_id = $post ? $post->ID : 0;
    }
    if ($music_id === 0) return '';
    return imz_render_recommendation_buttons($music_id);
}

// =============================================================================
// 5. AUTO-INSERIR ANTES DO BOTÃO IMPULSIONAR
// =============================================================================

add_filter('the_content', 'imz_auto_insert_recommendation', 4);
function imz_auto_insert_recommendation($content) {
    if (!is_singular('post') || !in_the_loop() || !is_main_query()) return $content;
    
    $post_id = get_the_ID();
    $is_not_music = get_post_meta($post_id, '_imz_nao_e_musica', true);
    if ($is_not_music === '1') return $content;

    $rec_html = imz_render_recommendation_buttons($post_id, 'post');
    return $content . $rec_html;
}

// =============================================================================
// 6. AJAX HANDLER
// =============================================================================

add_action('wp_ajax_imz_react_music', 'imz_ajax_react_music');
add_action('wp_ajax_nopriv_imz_react_music', 'imz_ajax_react_music');
function imz_ajax_react_music() {
    // Anti-CSRF: o nonce é gerado inline na página; em páginas servidas por cache
    // pode ter expirado — nesse caso degrada para um rate-limit apertado por IP
    // em vez de rejeitar (o dedupe por IP já impede votos duplicados).
    $nonce_ok = check_ajax_referer('imz_react_music_nonce', 'nonce', false);
    if (!$nonce_ok) {
        $ip_for_limit = function_exists('imz_get_user_ip') ? imz_get_user_ip() : sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? '');
        $limit_key = 'imz_react_rl_' . md5($ip_for_limit);
        $recent_count = (int) get_transient($limit_key);
        if ($recent_count >= 10) {
            wp_send_json_error(['message' => 'Demasiados pedidos. Tente novamente daqui a pouco.']);
            return;
        }
        set_transient($limit_key, $recent_count + 1, MINUTE_IN_SECONDS);
    }

    $music_id = absint($_POST['music_id'] ?? 0);
    $reaction = sanitize_key($_POST['reaction'] ?? '');

    if ($music_id === 0 || !in_array($reaction, ['like', 'dislike'])) {
        wp_send_json_error(['message' => 'Dados inválidos.']);
        return;
    }

    // Validar que o post existe
    $post = get_post($music_id);
    if (!$post || $post->post_type !== 'post') {
        wp_send_json_error(['message' => 'Música não encontrada.']);
        return;
    }

    global $wpdb;
    $table = $wpdb->prefix . 'imz_recommendations';
    $ip = function_exists('imz_get_user_ip') ? imz_get_user_ip() : sanitize_text_field($_SERVER['REMOTE_ADDR']);

    // Auto-criar tabela
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
        imz_install_recommendations_table();
    }

    // Verificar voto existente
    $existing = $wpdb->get_row($wpdb->prepare(
        "SELECT id, reaction FROM $table WHERE music_id = %d AND user_ip = %s", $music_id, $ip
    ));

    if ($existing) {
        if ($existing->reaction === $reaction) {
            // Mesmo voto — remover (toggle off)
            $wpdb->delete($table, ['id' => $existing->id], ['%d']);
        } else {
            // Voto diferente — atualizar
            $wpdb->update($table, ['reaction' => $reaction, 'reaction_date' => current_time('mysql')], ['id' => $existing->id], ['%s', '%s'], ['%d']);
        }
    } else {
        // Novo voto
        $wpdb->insert($table, [
            'music_id' => $music_id,
            'user_ip'  => $ip,
            'reaction' => $reaction,
        ], ['%d', '%s', '%s']);
    }

    // Retornar contagens atualizadas
    $counts = imz_get_recommendation_counts($music_id);
    $new_reaction = imz_get_user_reaction($music_id);

    wp_send_json_success([
        'likes'    => $counts['likes'],
        'dislikes' => $counts['dislikes'],
        'user_reaction' => $new_reaction ?: '',
    ]);
}

// =============================================================================
// 7. WIDGET / SHORTCODE DE MÚSICAS RECOMENDADAS
// =============================================================================

add_shortcode('imz_top_recomendadas', 'imz_render_top_recommended');
function imz_render_top_recommended($atts) {
    $atts = shortcode_atts([
        'max'    => 10,
        'titulo' => '👍 Músicas Mais Recomendadas',
        'periodo' => 'sempre',
    ], $atts);

    global $wpdb;
    $table = $wpdb->prefix . 'imz_recommendations';
    $current_post_id = get_the_ID();

    // =========================================================================
    // 1. BUSCAR MÚSICAS RECOMENDADAS (por likes)
    // =========================================================================
    $results = [];
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) === $table) {
        $date_filter = '';
        if ($atts['periodo'] === 'mes') {
            $date_filter = "AND reaction_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
        } elseif ($atts['periodo'] === 'semana') {
            $date_filter = "AND reaction_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
        }

        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT music_id, 
                    SUM(CASE WHEN reaction = 'like' THEN 1 ELSE 0 END) as likes
             FROM $table 
             WHERE reaction = 'like' $date_filter
             GROUP BY music_id 
             ORDER BY likes DESC 
             LIMIT %d",
            absint($atts['max'])
        ));
    }

    // =========================================================================
    // 2. BUSCAR 2 MÚSICAS PROMOVIDAS (impulsionadas com boost ativo)
    // =========================================================================
    $promoted_slides = [];
    $recommended_ids = array_map(function($r) { return $r->music_id; }, $results);

    $boosted_query = new WP_Query([
        'post_type'      => 'impulsionamento',
        'post_status'    => 'publish',
        'posts_per_page' => 10,
        'orderby'        => 'rand',
        'meta_query'     => [
            'relation' => 'AND',
            ['key' => 'status', 'value' => 'aprovado'],
            [
                'relation' => 'OR',
                ['key' => '_boost_data_fim', 'value' => current_time('Y-m-d H:i:s'), 'compare' => '>=', 'type' => 'DATETIME'],
                ['key' => '_boost_data_fim', 'value' => '', 'compare' => '='],
                ['key' => '_boost_data_fim', 'compare' => 'NOT EXISTS'],
            ],
        ],
    ]);

    $shown_promo_ids = [];
    if ($boosted_query->have_posts()) {
        while ($boosted_query->have_posts() && count($promoted_slides) < 2) {
            $boosted_query->the_post();
            $boost_id = get_the_ID();
            if (function_exists('imz_boost_is_active') && !imz_boost_is_active($boost_id, 'recommendations')) continue;
            $music_id = get_post_meta($boost_id, 'post_id_original', true);
            if (empty($music_id) || in_array($music_id, $shown_promo_ids) || $music_id == $current_post_id) continue;
            $music_post = get_post($music_id);
            if (!$music_post || $music_post->post_status !== 'publish') continue;

            $shown_promo_ids[] = $music_id;
            $thumbnail = get_the_post_thumbnail_url($music_id, 'thumbnail');
            $link = get_permalink($music_id);
            remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
            $title = get_the_title($music_id);
            add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

            $promoted_slides[] = [
                'music_id'  => $music_id,
                'thumbnail' => $thumbnail,
                'link'      => $link,
                'title'     => $title,
                'is_promo'  => true,
            ];
        }
        wp_reset_postdata();
    }

    // =========================================================================
    // 3. MONTAR ARRAY DE SLIDES (recomendadas + promovidas misturadas)
    // =========================================================================
    $all_slides = [];

    // Adicionar recomendadas
    foreach ($results as $row) {
        $music = get_post($row->music_id);
        if (!$music || $music->post_status !== 'publish') continue;
        if ($row->music_id == $current_post_id) continue;

        $thumbnail = get_the_post_thumbnail_url($row->music_id, 'thumbnail');
        $link = get_permalink($row->music_id);
        remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
        $title = get_the_title($row->music_id);
        add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

        $all_slides[] = [
            'music_id'  => $row->music_id,
            'thumbnail' => $thumbnail,
            'link'      => $link,
            'title'     => $title,
            'likes'     => $row->likes,
            'is_promo'  => false,
        ];
    }

    if (empty($all_slides) && empty($promoted_slides)) return '';

    // Inserir promovidas nas posições 3 e 7 (ou no fim se não houver tantas)
    $insert_positions = [2, 6]; // índices 0-based
    foreach ($promoted_slides as $i => $promo) {
        $pos = isset($insert_positions[$i]) ? min($insert_positions[$i], count($all_slides)) : count($all_slides);
        // Evitar duplicado se a promovida já está nas recomendadas
        $already_in = false;
        foreach ($all_slides as $s) {
            if ($s['music_id'] == $promo['music_id']) { $already_in = true; break; }
        }
        if (!$already_in) {
            array_splice($all_slides, $pos, 0, [$promo]);
        }
    }

    // =========================================================================
    // 4. RENDERIZAR SLIDER
    // =========================================================================
    $slider_id = 'imz-rec-slider-' . wp_rand(1000, 9999);

    ob_start();
    ?>
    <style>
    .imz-rec-widget { background: var(--imz-color-background-soft, #1a1a1a); border: 1px solid var(--imz-border-color, #2a2a2a); border-radius: 14px; overflow: hidden; margin: 20px 0; }
    .imz-rec-widget-title { font-size: 16px; font-weight: 700; color: var(--imz-color-text, #fff); margin: 0; padding: 16px 18px 12px; }
    .imz-rec-slider-wrap { position: relative; overflow: hidden; padding: 0 18px 18px; }
    .imz-rec-slider {
        display: flex;
        gap: 12px;
        overflow-x: auto;
        scroll-behavior: smooth;
        scrollbar-width: none;
        -ms-overflow-style: none;
        scroll-snap-type: x mandatory;
    }
    .imz-rec-slider::-webkit-scrollbar { display: none; }
    .imz-rec-slide {
        flex: 0 0 140px;
        scroll-snap-align: start;
        text-decoration: none !important;
        color: inherit !important;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
        padding: 12px 8px;
        border-radius: 12px;
        background: var(--imz-color-background, #141414);
        border: 1px solid var(--imz-border-color, #2a2a2a);
        transition: border-color 0.2s, box-shadow 0.2s;
        text-align: center;
        position: relative;
    }
    .imz-rec-slide:hover { border-color: #10b981; box-shadow: 0 0 0 1px #10b981; }
    .imz-rec-slide-cover {
        width: 80px; height: 80px; border-radius: 10px; object-fit: cover;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    }
    .imz-rec-slide-placeholder {
        width: 80px; height: 80px; border-radius: 10px;
        background: linear-gradient(135deg, #374151, #1f2937);
        display: flex; align-items: center; justify-content: center; color: #6b7280;
    }
    .imz-rec-slide-placeholder svg { width: 28px; height: 28px; }
    .imz-rec-slide-name {
        font-size: 12px; font-weight: 600; color: var(--imz-color-text, #fff);
        line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2;
        -webkit-box-orient: vertical; overflow: hidden; max-width: 100%;
    }
    .imz-rec-slide-likes { font-size: 11px; font-weight: 600; color: #10b981; }
    /* Promoted slide */
    .imz-rec-slide.promo { border-color: rgba(245,158,11,0.3); background: linear-gradient(135deg, #141414, rgba(245,158,11,0.05)); }
    .imz-rec-slide.promo:hover { border-color: #f59e0b; }
    .imz-rec-slide-promo-badge {
        position: absolute; top: 6px; right: 6px;
        background: rgba(245,158,11,0.85); color: #fff;
        font-size: 8px; font-weight: 700; padding: 2px 6px;
        border-radius: 4px; text-transform: uppercase; letter-spacing: 0.3px;
    }
    @media (max-width: 480px) {
        .imz-rec-slide { flex: 0 0 120px; }
        .imz-rec-slide-cover, .imz-rec-slide-placeholder { width: 64px; height: 64px; }
    }
    </style>
    <div class="imz-rec-widget">
        <h3 class="imz-rec-widget-title"><?php echo esc_html($atts['titulo']); ?></h3>
        <div class="imz-rec-slider-wrap">
            <div class="imz-rec-slider" id="<?php echo $slider_id; ?>">
                <?php foreach ($all_slides as $slide) : ?>
                <a href="<?php echo esc_url($slide['link']); ?>" class="imz-rec-slide<?php echo $slide['is_promo'] ? ' promo' : ''; ?>">
                    <?php if ($slide['is_promo']) : ?>
                        <span class="imz-rec-slide-promo-badge">🔥 Destaque</span>
                    <?php endif; ?>
                    <?php if (!empty($slide['thumbnail'])) : ?>
                        <img src="<?php echo esc_url($slide['thumbnail']); ?>" alt="" class="imz-rec-slide-cover" loading="lazy">
                    <?php else : ?>
                        <div class="imz-rec-slide-placeholder">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
                        </div>
                    <?php endif; ?>
                    <span class="imz-rec-slide-name"><?php echo esc_html($slide['title']); ?></span>
                    <?php if (!$slide['is_promo'] && isset($slide['likes'])) : ?>
                        <span class="imz-rec-slide-likes">👍 <?php echo number_format($slide['likes']); ?></span>
                    <?php elseif ($slide['is_promo']) : ?>
                        <span class="imz-rec-slide-likes" style="color:#f59e0b;">🔥 Promovida</span>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <script>
    (function(){
        var slider = document.getElementById('<?php echo $slider_id; ?>');
        if (!slider || slider.children.length < 3) return;
        var scrollAmount = 152;
        var direction = 1;
        setInterval(function() {
            var maxScroll = slider.scrollWidth - slider.clientWidth;
            if (slider.scrollLeft >= maxScroll - 5) direction = -1;
            else if (slider.scrollLeft <= 5) direction = 1;
            slider.scrollLeft += scrollAmount * direction;
        }, 3000);
    })();
    </script>
    <?php
    return ob_get_clean();
}

// =============================================================================
// 8. JS PARA INTERAÇÃO (INLINE NO FOOTER)
// =============================================================================

add_action('wp_footer', 'imz_recommendation_inline_script');
function imz_recommendation_inline_script() {
    if (!is_singular('post') && !is_page()) return;
    ?>
    <script>
    (function() {
        document.addEventListener('click', function(e) {
            var btn = e.target.closest('.imz-rec-btn');
            if (!btn) return;
            e.preventDefault();

            var container = btn.closest('.imz-rec-container');
            if (!container) return;
            
            var musicId = container.getAttribute('data-music-id');
            var reaction = btn.getAttribute('data-reaction');
            var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';

            // Desabilitar botões temporariamente
            container.querySelectorAll('.imz-rec-btn').forEach(function(b) { b.disabled = true; });

            var fd = new FormData();
            fd.append('action', 'imz_react_music');
            fd.append('music_id', musicId);
            fd.append('reaction', reaction);
            fd.append('nonce', '<?php echo wp_create_nonce('imz_react_music_nonce'); ?>');

            fetch(ajaxUrl, { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(result) {
                    if (result.success) {
                        // Atualizar contagens (todos os containers com este music_id)
                        document.querySelectorAll('.imz-rec-container[data-music-id="' + musicId + '"]').forEach(function(c) {
                            var likeCount = c.querySelector('[id^="imz-like-count-"]');
                            var dislikeCount = c.querySelector('[id^="imz-dislike-count-"]');
                            if (likeCount) likeCount.textContent = result.data.likes.toLocaleString();
                            if (dislikeCount) dislikeCount.textContent = result.data.dislikes.toLocaleString();

                            // Atualizar estados activos
                            c.querySelectorAll('.imz-rec-btn').forEach(function(b) { b.classList.remove('active'); });
                            if (result.data.user_reaction) {
                                var activeBtn = c.querySelector('.imz-rec-' + result.data.user_reaction);
                                if (activeBtn) activeBtn.classList.add('active');
                            }
                        });
                    }
                })
                .finally(function() {
                    container.querySelectorAll('.imz-rec-btn').forEach(function(b) { b.disabled = false; });
                });
        });
    })();
    </script>
    <?php
}
