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

// Adiciona o menu
add_action('admin_menu', function() {
    add_submenu_page(
        '',
        'Estatísticas da Plataforma',
        '📊 Estatísticas',
        'manage_options',
        'imz_statistics',
        'imz_render_statistics_page'
    );
    // Logs de download — acessível via URL direta mas não no menu
    add_submenu_page(
        '', // menu pai vazio = não aparece no menu (substitui null deprecated em PHP 8.1+)
        'Logs de Download (DB)',
        'Logs de Download',
        'manage_options',
        'imz_analytics_logs',
        'imz_render_analytics_logs_page'
    );
});

function imz_render_statistics_page() {
    if ( function_exists( 'rmbz_render_admin_analytics_page' ) ) {
        rmbz_render_admin_analytics_page();
        return;
    }

    global $wpdb;
    $analytics = $wpdb->prefix . 'imz_analytics';
    $plays_table = $wpdb->prefix . 'imz_plays';
    $purchases = $wpdb->prefix . 'imz_purchases';
    $reports = $wpdb->prefix . 'imz_reports';
    $ad_stats = $wpdb->prefix . 'imz_ad_stats';

    // Helper: verificar se tabela existe
    $has_table = function($t) use ($wpdb) { return $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $t)) === $t; };

    // --- FILTRO DE DATA PERSONALIZADA ---
    $date_from = isset($_GET['date_from']) ? sanitize_text_field($_GET['date_from']) : '';
    $date_to = isset($_GET['date_to']) ? sanitize_text_field($_GET['date_to']) : '';
    $has_custom_filter = !empty($date_from) && !empty($date_to);

    // SQL clauses para filtro
    $dl_date_where = '';
    $pl_date_where = '';
    if ($has_custom_filter) {
        $dl_date_where = $wpdb->prepare(" AND download_date >= %s AND download_date < DATE_ADD(%s, INTERVAL 1 DAY)", $date_from, $date_to);
        $pl_date_where = $wpdb->prepare(" AND play_date >= %s AND play_date < DATE_ADD(%s, INTERVAL 1 DAY)", $date_from, $date_to);
    }

    // =========================================================================
    // DADOS GERAIS
    // =========================================================================
    $total_downloads = $has_table($analytics) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $analytics WHERE 1=1 $dl_date_where") : 0;
    $total_plays = $has_table($plays_table) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $plays_table WHERE 1=1 $pl_date_where") : 0;
    $total_musics = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");
    $total_artists = (int) $wpdb->get_var("SELECT COUNT(DISTINCT post_author) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");
    $total_boosts = (int) wp_count_posts('impulsionamento')->publish;
    $total_sales = $has_table($purchases) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $purchases WHERE status = 'usado'") : 0;
    $total_revenue_sales = $has_table($purchases) ? (float) $wpdb->get_var("SELECT COALESCE(SUM(price),0) FROM $purchases WHERE status = 'usado'") : 0;
    $total_reports_open = $has_table($reports) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $reports WHERE status = 'novo'") : 0;

    // Downloads hoje / esta semana / este mês (sempre sem filtro)
    $dl_today = $has_table($analytics) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $analytics WHERE DATE(download_date) = CURDATE()") : 0;
    $dl_week = $has_table($analytics) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $analytics WHERE download_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)") : 0;
    $dl_month = $has_table($analytics) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $analytics WHERE download_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)") : 0;

    // Plays hoje / semana / mês (sempre sem filtro)
    $pl_today = $has_table($plays_table) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $plays_table WHERE DATE(play_date) = CURDATE()") : 0;
    $pl_week = $has_table($plays_table) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $plays_table WHERE play_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)") : 0;
    $pl_month = $has_table($plays_table) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $plays_table WHERE play_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)") : 0;

    // =========================================================================
    // TOP MÚSICAS — DOWNLOADS (24h / 7 Dias / Mês / Ano / Sempre / Personalizado)
    // =========================================================================
    $top_dl_24h = $has_table($analytics) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $analytics WHERE download_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR) GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_dl_week = $has_table($analytics) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $analytics WHERE download_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_dl_month = $has_table($analytics) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $analytics WHERE download_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_dl_year = $has_table($analytics) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $analytics WHERE download_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_dl_alltime = $has_table($analytics) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $analytics GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_dl_custom = ($has_custom_filter && $has_table($analytics)) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $analytics WHERE 1=1 $dl_date_where GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];

    // =========================================================================
    // TOP MÚSICAS — REPRODUÇÕES (24h / 7 Dias / Mês / Ano / Sempre / Personalizado)
    // =========================================================================
    $top_pl_24h = $has_table($plays_table) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $plays_table WHERE play_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR) GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_pl_week = $has_table($plays_table) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $plays_table WHERE play_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_pl_month = $has_table($plays_table) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $plays_table WHERE play_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_pl_year = $has_table($plays_table) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $plays_table WHERE play_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_pl_alltime = $has_table($plays_table) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $plays_table GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];
    $top_pl_custom = ($has_custom_filter && $has_table($plays_table)) ? $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $plays_table WHERE 1=1 $pl_date_where GROUP BY music_id ORDER BY total DESC LIMIT 10") : [];

    // =========================================================================
    // TOP PROVÍNCIAS
    // =========================================================================
    $top_regions = $has_table($analytics) ? $wpdb->get_results("SELECT region, COUNT(*) as total FROM $analytics WHERE region != '' AND region != 'N/A' $dl_date_where GROUP BY region ORDER BY total DESC LIMIT 10") : [];

    // =========================================================================
    // TOP PAÍSES
    // =========================================================================
    $top_countries = $has_table($analytics) ? $wpdb->get_results("SELECT country, COUNT(*) as total FROM $analytics WHERE country != '' $dl_date_where GROUP BY country ORDER BY total DESC LIMIT 10") : [];

    // =========================================================================
    // DOWNLOADS POR DIA (últimos 30 dias ou período personalizado) — para gráfico
    // =========================================================================
    $chart_days = 30;
    $chart_start = date('Y-m-d', strtotime('-29 days'));
    $chart_end = date('Y-m-d');

    if ($has_custom_filter) {
        $chart_start = $date_from;
        $chart_end = $date_to;
        $chart_days = max(1, (strtotime($date_to) - strtotime($date_from)) / 86400 + 1);
    }

    $dl_per_day = $has_table($analytics) ? $wpdb->get_results($wpdb->prepare("SELECT DATE(download_date) as day, COUNT(*) as total FROM $analytics WHERE download_date >= %s AND download_date < DATE_ADD(%s, INTERVAL 1 DAY) GROUP BY DATE(download_date) ORDER BY day ASC", $chart_start, $chart_end)) : [];
    $pl_per_day = $has_table($plays_table) ? $wpdb->get_results($wpdb->prepare("SELECT DATE(play_date) as day, COUNT(*) as total FROM $plays_table WHERE play_date >= %s AND play_date < DATE_ADD(%s, INTERVAL 1 DAY) GROUP BY DATE(play_date) ORDER BY day ASC", $chart_start, $chart_end)) : [];

    // Preparar dados para Chart.js
    $chart_labels = [];
    $chart_downloads = [];
    $chart_plays = [];
    $dl_map = []; foreach ($dl_per_day as $r) $dl_map[$r->day] = (int)$r->total;
    $pl_map = []; foreach ($pl_per_day as $r) $pl_map[$r->day] = (int)$r->total;
    for ($i = $chart_days - 1; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime($chart_end . " -{$i} days"));
        if ($date < $chart_start) continue;
        $chart_labels[] = date('d/m', strtotime($date));
        $chart_downloads[] = $dl_map[$date] ?? 0;
        $chart_plays[] = $pl_map[$date] ?? 0;
    }

    // TOP ARTISTAS (por downloads, com filtro)
    $top_artists = $has_table($analytics) ? $wpdb->get_results("SELECT p.post_author as artist_id, COUNT(a.id) as total FROM $analytics a INNER JOIN $wpdb->posts p ON a.music_id = p.ID WHERE 1=1 $dl_date_where GROUP BY p.post_author ORDER BY total DESC LIMIT 10") : [];

    // Anúncios stats
    $ad_impressions = $has_table($ad_stats) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $ad_stats WHERE event_type = 'impression'") : 0;
    $ad_clicks = $has_table($ad_stats) ? (int) $wpdb->get_var("SELECT COUNT(*) FROM $ad_stats WHERE event_type = 'click'") : 0;
    $ad_ctr = $ad_impressions > 0 ? round(($ad_clicks / $ad_impressions) * 100, 1) : 0;

    ?>
    <style>
    .imz-stats-wrap { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
    .imz-stats-wrap h1 { font-size: 28px; font-weight: 700; margin-bottom: 4px; }
    .imz-stats-wrap .imz-stats-subtitle { color: #6b7280; margin-top: 0; font-size: 14px; }

    /* Date filter */
    .imz-date-filter { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; padding: 14px 20px; margin-bottom: 24px; }
    .imz-date-filter label { font-size: 13px; font-weight: 600; color: #374151; white-space: nowrap; }
    .imz-date-filter input[type="date"] { padding: 6px 10px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 13px; color: #374151; }
    .imz-date-filter .button { margin-left: 4px; }
    .imz-date-filter .imz-filter-active { display: inline-flex; align-items: center; gap: 6px; background: #eff6ff; color: #1d4ed8; padding: 4px 12px; border-radius: 50px; font-size: 12px; font-weight: 600; }
    .imz-date-filter .imz-filter-clear { color: #ef4444; text-decoration: none; font-size: 12px; font-weight: 600; margin-left: 6px; }

    /* KPI Cards */
    .imz-kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 30px; }
    .imz-kpi-card { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 20px; position: relative; overflow: hidden; }
    .imz-kpi-card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px; }
    .imz-kpi-card.blue::before { background: #3b82f6; }
    .imz-kpi-card.green::before { background: #10b981; }
    .imz-kpi-card.purple::before { background: #8b5cf6; }
    .imz-kpi-card.amber::before { background: #f59e0b; }
    .imz-kpi-card.red::before { background: #ef4444; }
    .imz-kpi-card.pink::before { background: #ec4899; }
    .imz-kpi-label { font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; font-weight: 600; margin: 0 0 8px; }
    .imz-kpi-value { font-size: 32px; font-weight: 800; color: #111827; margin: 0; line-height: 1; }
    .imz-kpi-sub { font-size: 12px; color: #9ca3af; margin-top: 8px; }
    .imz-kpi-sub strong { color: #374151; }

    /* Sections */
    .imz-stats-section { margin-bottom: 30px; }
    .imz-stats-section h2 { font-size: 18px; font-weight: 700; margin: 0 0 16px; padding-bottom: 8px; border-bottom: 2px solid #f3f4f6; display: flex; align-items: center; gap: 8px; }
    .imz-stats-section h2 span.emoji { font-size: 20px; }

    /* Two-column layout */
    .imz-stats-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
    .imz-stats-grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; }
    @media (max-width: 1024px) { .imz-stats-grid-2, .imz-stats-grid-3 { grid-template-columns: 1fr; } }

    /* Tables */
    .imz-rank-table { width: 100%; border-collapse: collapse; background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; overflow: hidden; }
    .imz-rank-table th { background: #f9fafb; text-align: left; padding: 10px 14px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; font-weight: 600; border-bottom: 1px solid #e5e7eb; }
    .imz-rank-table td { padding: 10px 14px; border-bottom: 1px solid #f3f4f6; font-size: 13px; color: #374151; }
    .imz-rank-table tr:last-child td { border-bottom: none; }
    .imz-rank-table .rank { font-weight: 800; color: #9ca3af; width: 40px; text-align: center; }
    .imz-rank-table .rank-1 { color: #f59e0b; }
    .imz-rank-table .rank-2 { color: #9ca3af; }
    .imz-rank-table .rank-3 { color: #cd7f32; }
    .imz-rank-table .count { font-weight: 700; color: #111827; text-align: right; }
    .imz-rank-table .music-link { color: #3b82f6; text-decoration: none; font-weight: 500; }
    .imz-rank-table .music-link:hover { text-decoration: underline; }

    /* Chart container */
    .imz-chart-box { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; padding: 20px; margin-bottom: 20px; }
    .imz-chart-box h3 { margin: 0 0 16px; font-size: 15px; font-weight: 600; color: #374151; }
    .imz-chart-canvas-wrap { position: relative; height: 300px; }

    /* Tab switcher */
    .imz-tab-group { display: flex; gap: 0; margin-bottom: 16px; background: #f3f4f6; border-radius: 8px; padding: 3px; display: inline-flex; }
    .imz-tab-btn { padding: 6px 16px; border: none; background: transparent; font-size: 12px; font-weight: 600; color: #6b7280; cursor: pointer; border-radius: 6px; transition: all 0.2s; }
    .imz-tab-btn.active { background: #fff; color: #111827; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    .imz-tab-content { display: none; }
    .imz-tab-content.active { display: block; }
    </style>

    <div class="wrap imz-stats-wrap">
        <h1>📊 Estatísticas da Plataforma</h1>
        <p class="imz-stats-subtitle">Visão geral de toda a actividade na plataforma 1MusicMoz. Dados actualizados em tempo real.</p>

        <!-- FILTRO DE DATA PERSONALIZADA -->
        <div class="imz-date-filter">
            <label>📅 Período personalizado:</label>
            <form method="get" style="display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin:0;">
                <input type="hidden" name="post_type" value="impulsionamento">
                <input type="hidden" name="page" value="imz_statistics">
                <label>De: <input type="date" name="date_from" value="<?php echo esc_attr($date_from); ?>"></label>
                <label>Até: <input type="date" name="date_to" value="<?php echo esc_attr($date_to); ?>"></label>
                <button type="submit" class="button button-primary">Filtrar</button>
                <?php if ($has_custom_filter) : ?>
                    <span class="imz-filter-active">
                        Filtro ativo: <?php echo esc_html(date('d/m/Y', strtotime($date_from)) . ' → ' . date('d/m/Y', strtotime($date_to))); ?>
                    </span>
                    <a href="<?php echo admin_url('edit.php?post_type=impulsionamento&page=imz_statistics'); ?>" class="imz-filter-clear">✕ Limpar filtro</a>
                <?php endif; ?>
            </form>
        </div>

        <!-- ============================================================= -->
        <!-- KPI CARDS                                                      -->
        <!-- ============================================================= -->
        <div class="imz-kpi-grid">
            <div class="imz-kpi-card blue">
                <p class="imz-kpi-label">Downloads Totais</p>
                <p class="imz-kpi-value"><?php echo number_format($total_downloads); ?></p>
                <p class="imz-kpi-sub">Hoje: <strong><?php echo number_format($dl_today); ?></strong> · Semana: <strong><?php echo number_format($dl_week); ?></strong> · Mês: <strong><?php echo number_format($dl_month); ?></strong></p>
            </div>
            <div class="imz-kpi-card purple">
                <p class="imz-kpi-label">Reproduções (Player)</p>
                <p class="imz-kpi-value"><?php echo number_format($total_plays); ?></p>
                <p class="imz-kpi-sub">Hoje: <strong><?php echo number_format($pl_today); ?></strong> · Semana: <strong><?php echo number_format($pl_week); ?></strong> · Mês: <strong><?php echo number_format($pl_month); ?></strong></p>
            </div>
            <div class="imz-kpi-card green">
                <p class="imz-kpi-label">Impulsionamentos</p>
                <p class="imz-kpi-value"><?php echo number_format($total_boosts); ?></p>
            </div>
            <div class="imz-kpi-card amber">
                <p class="imz-kpi-label">Vendas Concluídas</p>
                <p class="imz-kpi-value"><?php echo number_format($total_sales); ?></p>
                <p class="imz-kpi-sub">Receita: <strong><?php echo number_format($total_revenue_sales, 0); ?> MT</strong></p>
            </div>
            <div class="imz-kpi-card pink">
                <p class="imz-kpi-label">Músicas · Artistas</p>
                <p class="imz-kpi-value"><?php echo number_format($total_musics); ?> <span style="font-size:16px;color:#9ca3af;">/ <?php echo number_format($total_artists); ?></span></p>
            </div>
            <div class="imz-kpi-card red">
                <p class="imz-kpi-label">Reportes Abertos</p>
                <p class="imz-kpi-value"><?php echo number_format($total_reports_open); ?></p>
            </div>
        </div>

        <!-- ============================================================= -->
        <!-- GRÁFICO DE ACTIVIDADE (30 DIAS)                                -->
        <!-- ============================================================= -->
        <div class="imz-chart-box">
            <h3>Actividade <?php echo $has_custom_filter ? '(' . date('d/m/Y', strtotime($date_from)) . ' — ' . date('d/m/Y', strtotime($date_to)) . ')' : 'dos Últimos 30 Dias'; ?></h3>
            <div class="imz-chart-canvas-wrap">
                <canvas id="imz-admin-chart"></canvas>
            </div>
        </div>

        <!-- ============================================================= -->
        <!-- TOP MÚSICAS — DOWNLOADS                                        -->
        <!-- ============================================================= -->
        <div class="imz-stats-section">
            <h2><span class="emoji">⬇️</span> Top Músicas — Downloads</h2>
            <div class="imz-tab-group" data-group="downloads">
                <button class="imz-tab-btn active" data-tab="dl-24h">24 Horas</button>
                <button class="imz-tab-btn" data-tab="dl-week">7 Dias</button>
                <button class="imz-tab-btn" data-tab="dl-month">Este Mês</button>
                <button class="imz-tab-btn" data-tab="dl-year">Este Ano</button>
                <button class="imz-tab-btn" data-tab="dl-alltime">Todos os Tempos</button>
                <?php if ($has_custom_filter) : ?><button class="imz-tab-btn" data-tab="dl-custom">📅 Personalizado</button><?php endif; ?>
            </div>
            <?php
            $dl_tabs = ['dl-24h' => $top_dl_24h, 'dl-week' => $top_dl_week, 'dl-month' => $top_dl_month, 'dl-year' => $top_dl_year, 'dl-alltime' => $top_dl_alltime];
            if ($has_custom_filter) $dl_tabs['dl-custom'] = $top_dl_custom;
            foreach ($dl_tabs as $tab_id => $data) :
                $is_active = $tab_id === 'dl-24h' ? ' active' : '';
            ?>
            <div class="imz-tab-content<?php echo $is_active; ?>" data-tab="<?php echo $tab_id; ?>">
                <?php echo imz_render_rank_table($data, 'downloads'); ?>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- ============================================================= -->
        <!-- TOP MÚSICAS — REPRODUÇÕES                                      -->
        <!-- ============================================================= -->
        <div class="imz-stats-section">
            <h2><span class="emoji">🎧</span> Top Músicas — Reproduções (Player Online)</h2>
            <div class="imz-tab-group" data-group="plays">
                <button class="imz-tab-btn active" data-tab="pl-24h">24 Horas</button>
                <button class="imz-tab-btn" data-tab="pl-week">7 Dias</button>
                <button class="imz-tab-btn" data-tab="pl-month">Este Mês</button>
                <button class="imz-tab-btn" data-tab="pl-year">Este Ano</button>
                <button class="imz-tab-btn" data-tab="pl-alltime">Todos os Tempos</button>
                <?php if ($has_custom_filter) : ?><button class="imz-tab-btn" data-tab="pl-custom">📅 Personalizado</button><?php endif; ?>
            </div>
            <?php
            $pl_tabs = ['pl-24h' => $top_pl_24h, 'pl-week' => $top_pl_week, 'pl-month' => $top_pl_month, 'pl-year' => $top_pl_year, 'pl-alltime' => $top_pl_alltime];
            if ($has_custom_filter) $pl_tabs['pl-custom'] = $top_pl_custom;
            foreach ($pl_tabs as $tab_id => $data) :
                $is_active = $tab_id === 'pl-24h' ? ' active' : '';
            ?>
            <div class="imz-tab-content<?php echo $is_active; ?>" data-tab="<?php echo $tab_id; ?>">
                <?php echo imz_render_rank_table($data, 'reproduções'); ?>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- ============================================================= -->
        <!-- GEOGRAFIA + ARTISTAS                                           -->
        <!-- ============================================================= -->
        <div class="imz-stats-grid-2">
            <div class="imz-stats-section">
                <h2><span class="emoji">📍</span> Top Províncias</h2>
                <?php echo imz_render_simple_rank_table($top_regions, 'region', 'downloads'); ?>
            </div>
            <div class="imz-stats-section">
                <h2><span class="emoji">🌍</span> Top Países</h2>
                <?php echo imz_render_simple_rank_table($top_countries, 'country', 'downloads'); ?>
            </div>
        </div>

        <div class="imz-stats-grid-2">
            <div class="imz-stats-section">
                <h2><span class="emoji">🎤</span> Top Artistas (por Downloads)</h2>
                <table class="imz-rank-table">
                    <thead><tr><th>#</th><th>Artista</th><th style="text-align:right;">Downloads</th></tr></thead>
                    <tbody>
                    <?php if (!empty($top_artists)) : $rank = 1; foreach ($top_artists as $row) :
                        $artist = get_user_by('id', $row->artist_id);
                        $name = $artist ? $artist->display_name : 'Desconhecido';
                        $rank_class = $rank <= 3 ? ' rank-' . $rank : '';
                    ?>
                    <tr>
                        <td class="rank<?php echo $rank_class; ?>"><?php echo $rank; ?></td>
                        <td><?php echo esc_html($name); ?></td>
                        <td class="count"><?php echo number_format($row->total); ?></td>
                    </tr>
                    <?php $rank++; endforeach; else : ?>
                    <tr><td colspan="3" style="text-align:center;color:#9ca3af;">Sem dados</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="imz-stats-section">
                <h2><span class="emoji">📢</span> Anúncios</h2>
                <table class="imz-rank-table">
                    <thead><tr><th>Métrica</th><th style="text-align:right;">Valor</th></tr></thead>
                    <tbody>
                        <tr><td>Impressões Totais</td><td class="count"><?php echo number_format($ad_impressions); ?></td></tr>
                        <tr><td>Cliques Totais</td><td class="count"><?php echo number_format($ad_clicks); ?></td></tr>
                        <tr><td>CTR Médio</td><td class="count"><?php echo $ad_ctr; ?>%</td></tr>
                        <tr><td>Anúncios Ativos</td><td class="count"><?php
                            $active_ads = (new WP_Query(['post_type' => 'imz_anuncio', 'posts_per_page' => -1, 'meta_query' => [['key' => '_imz_ad_status', 'value' => 'ativo']]]))->found_posts;
                            echo $active_ads;
                        ?></td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ============================================================= -->
        <!-- RECOMENDAÇÕES (Likes / Dislikes)                               -->
        <!-- ============================================================= -->
        <?php
        $rec_table = $wpdb->prefix . 'imz_recommendations';
        $has_rec = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $rec_table)) === $rec_table;
        if ($has_rec) :
            $total_likes = (int) $wpdb->get_var("SELECT COUNT(*) FROM $rec_table WHERE reaction = 'like'");
            $total_dislikes = (int) $wpdb->get_var("SELECT COUNT(*) FROM $rec_table WHERE reaction = 'dislike'");
            $top_liked = $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $rec_table WHERE reaction = 'like' GROUP BY music_id ORDER BY total DESC LIMIT 10");
            $top_disliked = $wpdb->get_results("SELECT music_id, COUNT(*) as total FROM $rec_table WHERE reaction = 'dislike' GROUP BY music_id ORDER BY total DESC LIMIT 5");
        ?>
        <div class="imz-stats-section">
            <h2><span class="emoji">👍</span> Recomendações</h2>
            <div class="imz-kpi-grid" style="grid-template-columns: repeat(3, 1fr); margin-bottom: 20px;">
                <div class="imz-kpi-card green"><p class="imz-kpi-label">Total Likes</p><p class="imz-kpi-value"><?php echo number_format($total_likes); ?></p></div>
                <div class="imz-kpi-card red"><p class="imz-kpi-label">Total Dislikes</p><p class="imz-kpi-value"><?php echo number_format($total_dislikes); ?></p></div>
                <div class="imz-kpi-card blue"><p class="imz-kpi-label">Taxa de Aprovação</p><p class="imz-kpi-value"><?php echo ($total_likes + $total_dislikes) > 0 ? round($total_likes / ($total_likes + $total_dislikes) * 100) : 0; ?>%</p></div>
            </div>
        </div>
        <div class="imz-stats-grid-2">
            <div class="imz-stats-section">
                <h2><span class="emoji">❤️</span> Músicas Mais Curtidas</h2>
                <?php echo imz_render_rank_table($top_liked, 'likes'); ?>
            </div>
            <div class="imz-stats-section">
                <h2><span class="emoji">👎</span> Músicas Menos Curtidas</h2>
                <?php if (!empty($top_disliked)) : ?>
                <?php echo imz_render_rank_table($top_disliked, 'dislikes'); ?>
                <?php else : ?>
                <p style="color:#9ca3af; text-align:center;">Sem dados.</p>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

    </div>

    <!-- Chart.js (usa o da CDN do WP admin) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Gráfico
        var ctx = document.getElementById('imz-admin-chart');
        if (ctx && typeof Chart !== 'undefined') {
            new Chart(ctx.getContext('2d'), {
                type: 'line',
                data: {
                    labels: <?php echo json_encode($chart_labels); ?>,
                    datasets: [
                        {
                            label: 'Downloads',
                            data: <?php echo json_encode($chart_downloads); ?>,
                            borderColor: '#3b82f6',
                            backgroundColor: 'rgba(59,130,246,0.08)',
                            fill: true, tension: 0.4, pointRadius: 3, borderWidth: 2
                        },
                        {
                            label: 'Reproduções',
                            data: <?php echo json_encode($chart_plays); ?>,
                            borderColor: '#8b5cf6',
                            backgroundColor: 'rgba(139,92,246,0.08)',
                            fill: true, tension: 0.4, pointRadius: 3, borderWidth: 2
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { mode: 'index', intersect: false },
                    plugins: { legend: { position: 'top', labels: { usePointStyle: true, padding: 20 } } },
                    scales: {
                        x: { grid: { display: false }, ticks: { font: { size: 11 } } },
                        y: { beginAtZero: true, grid: { color: '#f3f4f6' }, ticks: { font: { size: 11 }, stepSize: 1, callback: function(v) { return Number.isInteger(v) ? v : ''; } } }
                    }
                }
            });
        }

        // Tab switching
        document.querySelectorAll('.imz-tab-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var group = this.closest('.imz-stats-section');
                group.querySelectorAll('.imz-tab-btn').forEach(function(b) { b.classList.remove('active'); });
                group.querySelectorAll('.imz-tab-content').forEach(function(c) { c.classList.remove('active'); });
                this.classList.add('active');
                var target = this.getAttribute('data-tab');
                group.querySelector('.imz-tab-content[data-tab="' + target + '"]').classList.add('active');
            });
        });
    });
    </script>
    <?php
}

// =========================================================================
// HELPER: Renderizar tabela de ranking de músicas
// =========================================================================
function imz_render_rank_table($data, $label = 'downloads') {
    if (empty($data)) return '<p style="color:#9ca3af; text-align:center; padding: 20px 0;">Sem dados para este período.</p>';

    ob_start();
    ?>
    <table class="imz-rank-table">
        <thead><tr><th style="width:40px;">#</th><th>Música</th><th>Artista</th><th style="text-align:right;"><?php echo ucfirst($label); ?></th></tr></thead>
        <tbody>
        <?php $rank = 1; foreach ($data as $row) :
            $title = get_the_title($row->music_id) ?: '(Apagada)';
            $author_id = get_post_field('post_author', $row->music_id);
            $author_name = $author_id ? get_the_author_meta('display_name', $author_id) : '—';
            $edit_link = get_edit_post_link($row->music_id);
            $rank_class = $rank <= 3 ? ' rank-' . $rank : '';
            $medals = ['🥇', '🥈', '🥉'];
        ?>
        <tr>
            <td class="rank<?php echo $rank_class; ?>"><?php echo $medals[$rank-1] ?? $rank; ?></td>
            <td><a href="<?php echo esc_url($edit_link); ?>" class="music-link"><?php echo esc_html($title); ?></a></td>
            <td style="color:#6b7280;"><?php echo esc_html($author_name); ?></td>
            <td class="count"><?php echo number_format($row->total); ?></td>
        </tr>
        <?php $rank++; endforeach; ?>
        </tbody>
    </table>
    <?php
    return ob_get_clean();
}

// =========================================================================
// HELPER: Renderizar tabela simples (províncias/países)
// =========================================================================
function imz_render_simple_rank_table($data, $field, $label = 'downloads') {
    if (empty($data)) return '<p style="color:#9ca3af; text-align:center;">Sem dados.</p>';

    ob_start();
    ?>
    <table class="imz-rank-table">
        <thead><tr><th style="width:40px;">#</th><th><?php echo ucfirst($field === 'region' ? 'Província' : 'País'); ?></th><th style="text-align:right;"><?php echo ucfirst($label); ?></th></tr></thead>
        <tbody>
        <?php $rank = 1; foreach ($data as $row) :
            $value = $row->$field;
            $rank_class = $rank <= 3 ? ' rank-' . $rank : '';
            $medals = ['🥇', '🥈', '🥉'];
        ?>
        <tr>
            <td class="rank<?php echo $rank_class; ?>"><?php echo $medals[$rank-1] ?? $rank; ?></td>
            <td><?php echo esc_html($value); ?></td>
            <td class="count"><?php echo number_format($row->total); ?></td>
        </tr>
        <?php $rank++; endforeach; ?>
        </tbody>
    </table>
    <?php
    return ob_get_clean();
}

// =========================================================================
// PÁGINA DE LOGS (mantida separada)
// =========================================================================
function imz_render_analytics_logs_page() {
    if ( function_exists( 'rmbz_render_admin_download_logs_page' ) ) {
        rmbz_render_admin_download_logs_page();
        return;
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'imz_analytics';
    
    $per_page = 50;
    $page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $offset = ($page - 1) * $per_page;

    $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $table_name");
    $total_pages = ceil($total_items / $per_page);

    $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name ORDER BY download_date DESC LIMIT %d OFFSET %d", $per_page, $offset));
    
    ?>
    <div class="wrap">
        <h1>Logs de Download</h1>
        <p>Total de Downloads Registados: <strong><?php echo number_format($total_items); ?></strong></p>
        
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr><th>ID</th><th>Data</th><th>Música</th><th>Origem</th><th>IP</th><th>País/Região</th></tr>
            </thead>
            <tbody>
                <?php if ($results): foreach ($results as $row): 
                    $music_title = get_the_title($row->music_id) ?: '(Apagada)';
                ?>
                <tr>
                    <td><?php echo $row->id; ?></td>
                    <td><?php echo $row->download_date; ?></td>
                    <td><a href="<?php echo get_edit_post_link($row->music_id); ?>"><?php echo esc_html($music_title); ?></a></td>
                    <td><?php echo $row->source === 'paid' ? '<span style="color:green;font-weight:bold;">Venda</span>' : 'Gratuito'; ?></td>
                    <td><?php echo esc_html($row->user_ip); ?></td>
                    <td><?php echo esc_html($row->country . ' ' . $row->region); ?></td>
                </tr>
                <?php endforeach; else: ?>
                    <tr><td colspan="6">Nenhum registo encontrado.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
        
        <?php if ($total_pages > 1): ?>
        <div class="tablenav bottom">
            <div class="tablenav-pages">
                <?php echo paginate_links(['base' => add_query_arg('paged', '%#%'), 'total' => $total_pages, 'current' => $page]); ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php
}
