<?php
/**
 * IMZ Boost Analytics — Painel de Campanha para Impulsionamentos
 *
 * Adiciona:
 * - Vista detalhada de cada impulsionamento (impressões, cliques, CTR, dispositivos, regiões)
 * - Métricas exclusivas de música (downloads e likes durante o período de boost)
 * - Score de performance com alertas e sugestões
 * - Subpágina admin integrada no Gestor de Anúncios
 */

if (!defined('ABSPATH')) exit;

// =============================================================================
// 1. FUNÇÕES DE DADOS — Métricas do Boost
// =============================================================================

/**
 * Retorna todas as métricas de um impulsionamento.
 */
function imz_get_boost_metrics($boost_id) {
    global $wpdb;
    $stats_table = $wpdb->prefix . 'imz_ad_stats';
    $analytics_table = $wpdb->prefix . 'imz_analytics';
    $rec_table = $wpdb->prefix . 'imz_recommendations';

    $has_stats = ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $stats_table)) === $stats_table);
    $has_analytics = ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $analytics_table)) === $analytics_table);
    $has_recs = ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $rec_table)) === $rec_table);

    // Dados básicos do boost
    $music_id = get_post_meta($boost_id, 'post_id_original', true);
    $start_date = get_post_meta($boost_id, '_boost_data_inicio', true);
    $end_date = get_post_meta($boost_id, '_boost_data_fim', true);
    $boost_format = get_post_meta($boost_id, '_boost_format', true) ?: '—';
    $boost_days = get_post_meta($boost_id, '_boost_duracao_dias', true) ?: 0;
    $valor = get_post_meta($boost_id, 'valor', true) ?: 0;
    $status_boost = get_post_meta($boost_id, 'status', true) ?: 'pendente';

    // Status temporal
    $is_active = ($status_boost === 'aprovado' && !empty($end_date) && strtotime($end_date) > current_time('timestamp'));
    $is_expired = ($status_boost === 'aprovado' && !empty($end_date) && strtotime($end_date) <= current_time('timestamp'));

    $metrics = [
        'boost_id'    => $boost_id,
        'music_id'    => $music_id,
        'start_date'  => $start_date,
        'end_date'    => $end_date,
        'format'      => $boost_format,
        'days'        => $boost_days,
        'valor'       => $valor,
        'status'      => $is_active ? 'ativo' : ($is_expired ? 'expirado' : $status_boost),
        'impressions' => 0,
        'clicks'      => 0,
        'ctr'         => 0,
        'devices'     => ['mobile' => 0, 'desktop' => 0, 'tablet' => 0],
        'countries'   => [],
        'regions'     => [],
        'downloads_during' => 0,
        'likes_during'     => 0,
        'downloads_before' => 0,
        'likes_before'     => 0,
        'performance_score' => 0,
        'alerts'      => [],
    ];

    if (!$music_id) return $metrics;

    // --- Impressões e Cliques (da tabela ad_stats com source_type = 'boost') ---
    if ($has_stats) {
        // Verificar se coluna source_type existe
        $has_source = $wpdb->get_var("SHOW COLUMNS FROM $stats_table LIKE 'source_type'");

        if ($has_source) {
            $metrics['impressions'] = (int) $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $stats_table WHERE ad_id = %d AND source_type = 'boost' AND event_type = 'impression'", $boost_id
            ));
            $metrics['clicks'] = (int) $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $stats_table WHERE ad_id = %d AND source_type = 'boost' AND event_type = 'click'", $boost_id
            ));

            // Dispositivos
            $devices = $wpdb->get_results($wpdb->prepare(
                "SELECT device_type, COUNT(*) as cnt FROM $stats_table WHERE ad_id = %d AND source_type = 'boost' GROUP BY device_type", $boost_id
            ));
            foreach ($devices as $d) {
                $key = $d->device_type ?: 'desktop';
                if (isset($metrics['devices'][$key])) $metrics['devices'][$key] = (int) $d->cnt;
            }

            // Países
            $metrics['countries'] = $wpdb->get_results($wpdb->prepare(
                "SELECT country, COUNT(*) as cnt FROM $stats_table WHERE ad_id = %d AND source_type = 'boost' AND country != '' GROUP BY country ORDER BY cnt DESC LIMIT 10", $boost_id
            ));

            // Regiões
            $metrics['regions'] = $wpdb->get_results($wpdb->prepare(
                "SELECT region, COUNT(*) as cnt FROM $stats_table WHERE ad_id = %d AND source_type = 'boost' AND region != '' GROUP BY region ORDER BY cnt DESC LIMIT 10", $boost_id
            ));
        }
    }

    $metrics['ctr'] = $metrics['impressions'] > 0 ? round(($metrics['clicks'] / $metrics['impressions']) * 100, 1) : 0;

    // --- Downloads durante o período de boost ---
    if ($has_analytics && $start_date) {
        $end_for_query = $end_date ?: current_time('mysql');
        $metrics['downloads_during'] = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $analytics_table WHERE music_id = %d AND download_date BETWEEN %s AND %s",
            $music_id, $start_date, $end_for_query
        ));

        // Downloads nos mesmos dias ANTES do boost (para comparação)
        $days_diff = max(1, (int) $boost_days);
        $before_start = date('Y-m-d H:i:s', strtotime($start_date . " -{$days_diff} days"));
        $metrics['downloads_before'] = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $analytics_table WHERE music_id = %d AND download_date BETWEEN %s AND %s",
            $music_id, $before_start, $start_date
        ));
    }

    // --- Likes durante o período de boost ---
    if ($has_recs && $start_date) {
        $end_for_query = $end_date ?: current_time('mysql');
        $metrics['likes_during'] = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $rec_table WHERE music_id = %d AND reaction = 'like' AND reaction_date BETWEEN %s AND %s",
            $music_id, $start_date, $end_for_query
        ));

        $days_diff = max(1, (int) $boost_days);
        $before_start = date('Y-m-d H:i:s', strtotime($start_date . " -{$days_diff} days"));
        $metrics['likes_before'] = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $rec_table WHERE music_id = %d AND reaction = 'like' AND reaction_date BETWEEN %s AND %s",
            $music_id, $before_start, $start_date
        ));
    }

    // --- Score de Performance (0-100) ---
    $score = 0;
    $alerts = [];

    // CTR (0-40 pontos)
    if ($metrics['ctr'] >= 5) { $score += 40; }
    elseif ($metrics['ctr'] >= 3) { $score += 30; }
    elseif ($metrics['ctr'] >= 1.5) { $score += 20; }
    elseif ($metrics['ctr'] >= 0.5) { $score += 10; }
    else {
        if ($metrics['impressions'] > 50) {
            $alerts[] = ['type' => 'warning', 'msg' => 'CTR muito baixo (' . $metrics['ctr'] . '%). Considere mudar a imagem de capa da música para algo mais chamativo.'];
        }
    }

    // Downloads (0-30 pontos)
    if ($metrics['downloads_during'] > 0) {
        $dl_growth = $metrics['downloads_before'] > 0
            ? (($metrics['downloads_during'] - $metrics['downloads_before']) / $metrics['downloads_before']) * 100
            : 100;

        if ($dl_growth >= 50) { $score += 30; }
        elseif ($dl_growth >= 20) { $score += 20; }
        elseif ($dl_growth >= 0) { $score += 10; }
        else {
            $alerts[] = ['type' => 'danger', 'msg' => 'Downloads diminuíram durante o boost. O conteúdo pode não estar a ressoar com o público.'];
        }
    } elseif ($metrics['impressions'] > 100) {
        $alerts[] = ['type' => 'warning', 'msg' => 'Muitas impressões mas zero downloads. Verifique se o botão de download está funcional.'];
    }

    // Likes (0-20 pontos)
    if ($metrics['likes_during'] > 0) {
        $like_growth = $metrics['likes_before'] > 0
            ? (($metrics['likes_during'] - $metrics['likes_before']) / $metrics['likes_before']) * 100
            : 100;

        if ($like_growth >= 30) { $score += 20; }
        elseif ($like_growth >= 0) { $score += 10; }
    }

    // Engagement diversity (0-10 pontos)
    $total_devices = array_sum($metrics['devices']);
    if ($total_devices > 0) {
        $device_types_used = count(array_filter($metrics['devices']));
        if ($device_types_used >= 2) $score += 5;
        if (count($metrics['regions']) >= 3) $score += 5;
    }

    // Alertas positivos
    if ($score >= 70) {
        $alerts[] = ['type' => 'success', 'msg' => 'Excelente performance! Esta campanha está a correr muito bem.'];
    } elseif ($score >= 40 && $metrics['impressions'] > 20) {
        $alerts[] = ['type' => 'info', 'msg' => 'Performance razoável. Pode melhorar com uma capa mais atrativa ou um período mais longo.'];
    }

    if ($metrics['impressions'] < 10 && $is_active) {
        $alerts[] = ['type' => 'info', 'msg' => 'Campanha recente — ainda a recolher dados. Volte mais tarde para ver resultados.'];
    }

    $metrics['performance_score'] = min(100, $score);
    $metrics['alerts'] = $alerts;

    return $metrics;
}


// =============================================================================
// 2. PÁGINA DE DETALHES DO BOOST (Admin)
// =============================================================================

/**
 * Renderiza a página de detalhes de um impulsionamento.
 * Chamada quando view=boost_detail&boost_id=X
 */
function imz_render_boost_detail_page($boost_id) {
    $m = imz_get_boost_metrics($boost_id);
    if (!$m['music_id']) {
        echo '<div class="notice notice-error"><p>Impulsionamento não encontrado.</p></div>';
        return;
    }

    $music_post = get_post($m['music_id']);
    remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
    $music_title = $music_post ? get_the_title($m['music_id']) : '(Música apagada)';
    add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

    $music_link = $music_post ? get_permalink($m['music_id']) : '#';
    $thumbnail = $music_post ? get_the_post_thumbnail_url($m['music_id'], 'medium') : '';

    // Artista
    $artist_name = '';
    $artista_cpt_id = get_post_meta($m['music_id'], '_imz_artista_id', true);
    if ($artista_cpt_id) $artist_name = get_post_field('post_title', $artista_cpt_id);
    if (!$artist_name && $music_post) $artist_name = get_the_author_meta('display_name', $music_post->post_author);

    // Formatos
    $formats = function_exists('imz_get_ad_formats') ? imz_get_ad_formats() : [];
    $format_name = isset($formats[$m['format']]) ? $formats[$m['format']]['name'] . ' (' . $formats[$m['format']]['label'] . ')' : $m['format'];

    // Score styling
    $score = $m['performance_score'];
    if ($score >= 70) { $score_color = '#059669'; $score_label = 'Excelente'; }
    elseif ($score >= 40) { $score_color = '#f59e0b'; $score_label = 'Razoável'; }
    else { $score_color = '#ef4444'; $score_label = 'Fraco'; }

    // Status badge
    $status_colors = ['ativo' => '#059669', 'expirado' => '#6b7280', 'aprovado' => '#059669', 'pendente' => '#f59e0b'];
    $status_color = $status_colors[$m['status']] ?? '#6b7280';

    // Crescimento downloads
    $dl_growth = $m['downloads_before'] > 0
        ? round((($m['downloads_during'] - $m['downloads_before']) / $m['downloads_before']) * 100)
        : ($m['downloads_during'] > 0 ? 100 : 0);
    $dl_growth_icon = $dl_growth > 0 ? '↑' : ($dl_growth < 0 ? '↓' : '→');
    $dl_growth_color = $dl_growth > 0 ? '#059669' : ($dl_growth < 0 ? '#ef4444' : '#6b7280');

    // Crescimento likes
    $like_growth = $m['likes_before'] > 0
        ? round((($m['likes_during'] - $m['likes_before']) / $m['likes_before']) * 100)
        : ($m['likes_during'] > 0 ? 100 : 0);
    $like_growth_icon = $like_growth > 0 ? '↑' : ($like_growth < 0 ? '↓' : '→');
    $like_growth_color = $like_growth > 0 ? '#059669' : ($like_growth < 0 ? '#ef4444' : '#6b7280');

    // Dispositivos percentagens
    $total_device = array_sum($m['devices']);
    $pct_m = $total_device > 0 ? round($m['devices']['mobile'] / $total_device * 100) : 0;
    $pct_d = $total_device > 0 ? round($m['devices']['desktop'] / $total_device * 100) : 0;
    $pct_t = $total_device > 0 ? round($m['devices']['tablet'] / $total_device * 100) : 0;

    $back_url = admin_url('edit.php?post_type=impulsionamento&page=imz_ads_manager&view=boosts_list');
    ?>
    <style>
    .imz-bd { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
    .imz-bd-back { font-size: 13px; color: #6b7280; text-decoration: none; display: inline-flex; align-items: center; gap: 4px; margin-bottom: 16px; }
    .imz-bd-back:hover { color: #111; }
    .imz-bd-header { display: flex; gap: 20px; align-items: flex-start; margin-bottom: 24px; }
    .imz-bd-thumb { width: 80px; height: 80px; border-radius: 12px; object-fit: cover; box-shadow: 0 4px 12px rgba(0,0,0,0.15); flex-shrink: 0; }
    .imz-bd-thumb-placeholder { width: 80px; height: 80px; border-radius: 12px; background: #e5e7eb; display: flex; align-items: center; justify-content: center; color: #9ca3af; flex-shrink: 0; }
    .imz-bd-title-section h2 { margin: 0 0 4px; font-size: 22px; }
    .imz-bd-artist { color: #6b7280; font-size: 14px; margin: 0 0 8px; }
    .imz-bd-tags { display: flex; gap: 6px; flex-wrap: wrap; }
    .imz-bd-tag { padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 700; display: inline-block; }

    .imz-bd-score-ring { width: 100px; height: 100px; border-radius: 50%; display: flex; flex-direction: column; align-items: center; justify-content: center; margin: 0 auto 8px; position: relative; }
    .imz-bd-score-ring .score-num { font-size: 28px; font-weight: 800; line-height: 1; }
    .imz-bd-score-ring .score-label { font-size: 11px; font-weight: 600; }

    .imz-bd-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; margin-bottom: 24px; }
    .imz-bd-kpi { background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; padding: 18px; text-align: center; }
    .imz-bd-kpi .kpi-val { font-size: 28px; font-weight: 800; color: #111; line-height: 1.2; }
    .imz-bd-kpi .kpi-label { font-size: 11px; text-transform: uppercase; color: #6b7280; letter-spacing: 0.5px; margin-top: 4px; }
    .imz-bd-kpi .kpi-change { font-size: 12px; font-weight: 600; margin-top: 4px; }

    .imz-bd-sections { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 24px; }
    @media (max-width: 900px) { .imz-bd-sections { grid-template-columns: 1fr; } }
    .imz-bd-section { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 20px; }
    .imz-bd-section h3 { margin: 0 0 14px; font-size: 15px; font-weight: 700; }

    .imz-bd-alert { padding: 12px 16px; border-radius: 8px; margin-bottom: 10px; font-size: 13px; display: flex; gap: 8px; align-items: flex-start; }
    .imz-bd-alert-success { background: #d1fae5; color: #065f46; border: 1px solid #a7f3d0; }
    .imz-bd-alert-info { background: #dbeafe; color: #1e40af; border: 1px solid #93c5fd; }
    .imz-bd-alert-warning { background: #fef3c7; color: #92400e; border: 1px solid #fcd34d; }
    .imz-bd-alert-danger { background: #fee2e2; color: #991b1b; border: 1px solid #fca5a5; }

    .imz-bd-bar { display: flex; height: 10px; border-radius: 5px; overflow: hidden; margin: 8px 0; background: #f3f4f6; }
    .imz-bd-legend { display: flex; gap: 14px; font-size: 12px; color: #6b7280; flex-wrap: wrap; margin-top: 4px; }
    .imz-bd-legend span::before { content: ''; display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 4px; vertical-align: middle; }
    .imz-bd-legend .l-mobile::before { background: #3b82f6; }
    .imz-bd-legend .l-desktop::before { background: #10b981; }
    .imz-bd-legend .l-tablet::before { background: #f59e0b; }

    .imz-bd-region-list { list-style: none; padding: 0; margin: 0; }
    .imz-bd-region-list li { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px solid #f3f4f6; font-size: 13px; }
    .imz-bd-region-list li:last-child { border-bottom: none; }
    .imz-bd-region-list .r-name { color: #374151; font-weight: 500; }
    .imz-bd-region-list .r-count { color: #6b7280; }

    .imz-bd-compare { display: flex; align-items: center; gap: 20px; padding: 14px; background: #f9fafb; border-radius: 8px; margin-bottom: 10px; }
    .imz-bd-compare .compare-period { flex: 1; text-align: center; }
    .imz-bd-compare .compare-period .val { font-size: 22px; font-weight: 800; color: #111; }
    .imz-bd-compare .compare-period .lbl { font-size: 11px; color: #6b7280; text-transform: uppercase; }
    .imz-bd-compare .compare-arrow { font-size: 20px; color: #d1d5db; }
    </style>

    <div class="imz-bd">
        <a href="<?php echo $back_url; ?>" class="imz-bd-back">← Voltar à lista</a>

        <!-- Header: Música + Status + Score -->
        <div class="imz-bd-header">
            <?php if ($thumbnail): ?>
                <img src="<?php echo esc_url($thumbnail); ?>" class="imz-bd-thumb">
            <?php else: ?>
                <div class="imz-bd-thumb-placeholder">♪</div>
            <?php endif; ?>
            <div class="imz-bd-title-section" style="flex:1;">
                <h2><?php echo esc_html($music_title); ?></h2>
                <p class="imz-bd-artist"><?php echo esc_html($artist_name); ?></p>
                <div class="imz-bd-tags">
                    <span class="imz-bd-tag" style="background:<?php echo $status_color; ?>20; color:<?php echo $status_color; ?>;"><?php echo ucfirst($m['status']); ?></span>
                    <span class="imz-bd-tag" style="background:#eff6ff; color:#1e40af;"><?php echo esc_html($format_name); ?></span>
                    <span class="imz-bd-tag" style="background:#f3f4f6; color:#374151;">
                        <?php echo $m['start_date'] ? date('d/m/Y', strtotime($m['start_date'])) : '—'; ?> → <?php echo $m['end_date'] ? date('d/m/Y', strtotime($m['end_date'])) : '∞'; ?>
                    </span>
                    <?php if ($m['valor'] > 0): ?>
                    <span class="imz-bd-tag" style="background:#fef3c7; color:#92400e;"><?php echo number_format($m['valor']); ?> MT</span>
                    <?php endif; ?>
                </div>
            </div>
            <!-- Score -->
            <div style="text-align:center; flex-shrink:0;">
                <div class="imz-bd-score-ring" style="border: 4px solid <?php echo $score_color; ?>;">
                    <span class="score-num" style="color:<?php echo $score_color; ?>;"><?php echo $score; ?></span>
                    <span class="score-label" style="color:<?php echo $score_color; ?>;"><?php echo $score_label; ?></span>
                </div>
                <span style="font-size:11px; color:#6b7280;">Performance</span>
            </div>
        </div>

        <!-- Alertas -->
        <?php foreach ($m['alerts'] as $alert): ?>
        <div class="imz-bd-alert imz-bd-alert-<?php echo $alert['type']; ?>">
            <?php
            $icons = ['success' => '✓', 'info' => 'ℹ', 'warning' => '⚠', 'danger' => '✕'];
            echo '<strong>' . ($icons[$alert['type']] ?? '') . '</strong>';
            ?>
            <span><?php echo esc_html($alert['msg']); ?></span>
        </div>
        <?php endforeach; ?>

        <!-- KPIs principais -->
        <div class="imz-bd-grid">
            <div class="imz-bd-kpi">
                <div class="kpi-val"><?php echo number_format($m['impressions']); ?></div>
                <div class="kpi-label">Impressões</div>
            </div>
            <div class="imz-bd-kpi">
                <div class="kpi-val"><?php echo number_format($m['clicks']); ?></div>
                <div class="kpi-label">Cliques</div>
            </div>
            <div class="imz-bd-kpi">
                <div class="kpi-val"><?php echo $m['ctr']; ?>%</div>
                <div class="kpi-label">CTR</div>
            </div>
            <div class="imz-bd-kpi">
                <div class="kpi-val"><?php echo number_format($m['downloads_during']); ?></div>
                <div class="kpi-label">Downloads (período)</div>
                <?php if ($dl_growth !== 0): ?>
                <div class="kpi-change" style="color:<?php echo $dl_growth_color; ?>;">
                    <?php echo $dl_growth_icon . ' ' . abs($dl_growth); ?>% vs período anterior
                </div>
                <?php endif; ?>
            </div>
            <div class="imz-bd-kpi">
                <div class="kpi-val"><?php echo number_format($m['likes_during']); ?></div>
                <div class="kpi-label">Likes (período)</div>
                <?php if ($like_growth !== 0): ?>
                <div class="kpi-change" style="color:<?php echo $like_growth_color; ?>;">
                    <?php echo $like_growth_icon . ' ' . abs($like_growth); ?>% vs período anterior
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Comparação Antes vs Durante -->
        <div class="imz-bd-sections">
            <div class="imz-bd-section">
                <h3>Downloads: Antes vs Durante</h3>
                <div class="imz-bd-compare">
                    <div class="compare-period">
                        <div class="val"><?php echo number_format($m['downloads_before']); ?></div>
                        <div class="lbl">Antes do boost</div>
                    </div>
                    <span class="compare-arrow">→</span>
                    <div class="compare-period">
                        <div class="val" style="color:<?php echo $dl_growth_color; ?>;"><?php echo number_format($m['downloads_during']); ?></div>
                        <div class="lbl">Durante o boost</div>
                    </div>
                </div>
                <div class="imz-bd-compare">
                    <div class="compare-period">
                        <div class="val"><?php echo number_format($m['likes_before']); ?></div>
                        <div class="lbl">Likes antes</div>
                    </div>
                    <span class="compare-arrow">→</span>
                    <div class="compare-period">
                        <div class="val" style="color:<?php echo $like_growth_color; ?>;"><?php echo number_format($m['likes_during']); ?></div>
                        <div class="lbl">Likes durante</div>
                    </div>
                </div>
            </div>

            <!-- Dispositivos -->
            <div class="imz-bd-section">
                <h3>Dispositivos</h3>
                <?php if ($total_device > 0): ?>
                <div class="imz-bd-bar">
                    <?php if ($pct_m > 0): ?><div style="width:<?php echo $pct_m; ?>%; background:#3b82f6;"></div><?php endif; ?>
                    <?php if ($pct_d > 0): ?><div style="width:<?php echo $pct_d; ?>%; background:#10b981;"></div><?php endif; ?>
                    <?php if ($pct_t > 0): ?><div style="width:<?php echo $pct_t; ?>%; background:#f59e0b;"></div><?php endif; ?>
                </div>
                <div class="imz-bd-legend">
                    <span class="l-mobile">Mobile <?php echo $pct_m; ?>% (<?php echo number_format($m['devices']['mobile']); ?>)</span>
                    <span class="l-desktop">Desktop <?php echo $pct_d; ?>% (<?php echo number_format($m['devices']['desktop']); ?>)</span>
                    <span class="l-tablet">Tablet <?php echo $pct_t; ?>% (<?php echo number_format($m['devices']['tablet']); ?>)</span>
                </div>
                <?php else: ?>
                <p style="color:#9ca3af; font-size:13px;">Sem dados de dispositivos ainda.</p>
                <?php endif; ?>

                <h3 style="margin-top:20px;">Províncias</h3>
                <?php if (!empty($m['regions'])): ?>
                <ul class="imz-bd-region-list">
                    <?php foreach ($m['regions'] as $r): ?>
                    <li><span class="r-name"><?php echo esc_html($r->region); ?></span><span class="r-count"><?php echo number_format($r->cnt); ?></span></li>
                    <?php endforeach; ?>
                </ul>
                <?php else: ?>
                <p style="color:#9ca3af; font-size:13px;">Sem dados de regiões.</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Ações -->
        <div style="display:flex; gap:10px; flex-wrap:wrap;">
            <a href="<?php echo esc_url($music_link); ?>" target="_blank" class="button">Ver Música</a>
            <a href="<?php echo admin_url('edit.php?post_type=impulsionamento&page=imz_ads_manager&view=boost'); ?>" class="button button-primary">Criar Novo Boost</a>
        </div>
    </div>
    <?php
}


// =============================================================================
// 3. LISTA DE TODOS OS BOOSTS (Admin)
// =============================================================================

function imz_render_boosts_list_page() {
    global $wpdb;
    $stats_table = $wpdb->prefix . 'imz_ad_stats';
    $has_stats = ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $stats_table)) === $stats_table);
    $has_source = $has_stats ? (bool) $wpdb->get_var("SHOW COLUMNS FROM $stats_table LIKE 'source_type'") : false;
    $base_url = admin_url('edit.php?post_type=impulsionamento&page=imz_ads_manager');

    $boosts = new WP_Query([
        'post_type' => 'impulsionamento',
        'post_status' => 'publish',
        'posts_per_page' => 30,
        'orderby' => 'date',
        'order' => 'DESC',
        'meta_query' => [['key' => 'status', 'value' => 'aprovado']],
        'paged' => max(1, absint($_GET['paged'] ?? 1)),
    ]);
    ?>
    <h2 style="font-size:18px; margin-bottom:16px;">📊 Todos os Impulsionamentos</h2>
    <table class="imz-ads-table" style="background:#fff; border:1px solid #e5e7eb; border-radius:10px; overflow:hidden;">
        <thead>
            <tr>
                <th>Música</th>
                <th>Formato</th>
                <th>Período</th>
                <th>Status</th>
                <th>Impressões</th>
                <th>Cliques</th>
                <th>CTR</th>
                <th>Downloads</th>
                <th>Score</th>
                <th>Ações</th>
            </tr>
        </thead>
        <tbody>
        <?php if ($boosts->have_posts()): while ($boosts->have_posts()): $boosts->the_post();
            $bid = get_the_ID();
            $music_id = get_post_meta($bid, 'post_id_original', true);
            $end_date = get_post_meta($bid, '_boost_data_fim', true);
            $start_date = get_post_meta($bid, '_boost_data_inicio', true);
            $boost_fmt = get_post_meta($bid, '_boost_format', true);
            $is_active = !empty($end_date) && strtotime($end_date) > current_time('timestamp');
            $is_expired = !empty($end_date) && strtotime($end_date) <= current_time('timestamp');
            $status = $is_active ? 'ativo' : ($is_expired ? 'expirado' : 'pendente');

            remove_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);
            $mtitle = $music_id ? get_the_title($music_id) : '—';
            add_filter('the_title', 'imz_add_verified_badge_to_title', 10, 2);

            // Stats rápidas
            $imp = 0; $clk = 0;
            if ($has_stats && $has_source) {
                $imp = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $stats_table WHERE ad_id=%d AND source_type='boost' AND event_type='impression'", $bid));
                $clk = (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $stats_table WHERE ad_id=%d AND source_type='boost' AND event_type='click'", $bid));
            }
            $ctr = $imp > 0 ? round(($clk / $imp) * 100, 1) : 0;

            // Downloads durante
            $dl_during = 0;
            $analytics_table = $wpdb->prefix . 'imz_analytics';
            if ($music_id && $start_date && $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $analytics_table)) === $analytics_table) {
                $end_q = $end_date ?: current_time('mysql');
                $dl_during = (int) $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM $analytics_table WHERE music_id=%d AND download_date BETWEEN %s AND %s",
                    $music_id, $start_date, $end_q
                ));
            }

            // Score rápido
            $score_q = 0;
            if ($ctr >= 3) $score_q = 70;
            elseif ($ctr >= 1) $score_q = 40;
            elseif ($imp > 0) $score_q = 15;
            if ($dl_during > 0) $score_q = min(100, $score_q + 20);

            $score_color = $score_q >= 70 ? '#059669' : ($score_q >= 40 ? '#f59e0b' : '#ef4444');
            $status_badge = ['ativo' => 'imz-badge-ativo', 'expirado' => 'imz-badge-expirado', 'pendente' => 'imz-badge-pendente'];

            $formats = function_exists('imz_get_ad_formats') ? imz_get_ad_formats() : [];
            $fmt_display = isset($formats[$boost_fmt]) ? $formats[$boost_fmt]['icon'] . ' ' . $formats[$boost_fmt]['label'] : '—';
        ?>
        <tr>
            <td><a href="<?php echo $base_url . '&view=boost_detail&boost_id=' . $bid; ?>" style="font-weight:700; text-decoration:none;"><?php echo esc_html($mtitle); ?></a></td>
            <td style="font-size:12px;"><?php echo $fmt_display; ?></td>
            <td style="font-size:12px;"><?php echo $start_date ? date('d/m', strtotime($start_date)) : '—'; ?> → <?php echo $end_date ? date('d/m', strtotime($end_date)) : '∞'; ?></td>
            <td><span class="imz-badge <?php echo $status_badge[$status] ?? ''; ?>"><?php echo ucfirst($status); ?></span></td>
            <td><?php echo number_format($imp); ?></td>
            <td><?php echo number_format($clk); ?></td>
            <td><?php echo $ctr; ?>%</td>
            <td><?php echo number_format($dl_during); ?></td>
            <td><strong style="color:<?php echo $score_color; ?>;"><?php echo $score_q; ?></strong></td>
            <td><a href="<?php echo $base_url . '&view=boost_detail&boost_id=' . $bid; ?>" class="button button-small">Detalhes</a></td>
        </tr>
        <?php endwhile; wp_reset_postdata(); else: ?>
        <tr><td colspan="10" style="text-align:center; color:#9ca3af; padding:20px;">Nenhum impulsionamento encontrado.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    <?php
}
