<?php
/**
 * Estatísticas avançadas do site — secções que igualam a app.
 *
 * [1.5.227] FASE 1a — Lista de relatórios mensais.
 *
 * A app tem um ecrã "Todos os relatórios" que lista cada import
 * (relatório mensal) com ganhos e streams. Esta função renderiza
 * a MESMA lista no site, para ser adicionada ao fundo da vista
 * de analytics (rmbz_render_analytics_view).
 *
 * Reusa exactamente a query do endpoint /stats/imports da API.
 *
 * Não substitui nada da vista antiga — é uma secção ADICIONAL.
 */

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

/**
 * Vai buscar a lista de relatórios mensais (imports) do artista.
 * Mesma lógica do endpoint REST rmbz_api_handle_stats_imports_list.
 *
 * @param string $telemovel  Telemóvel do artista.
 * @param int    $limit      Máx. de relatórios.
 * @return array  Lista de objectos com id, source_name, reporting_period,
 *                imported_at, earnings_usd, streams, stores_count,
 *                countries_count.
 */
function rmbz_analytics_get_imports_list( $telemovel, $limit = 24 ) {
    global $wpdb;

    $limit   = max( 1, min( 100, (int) $limit ) );
    $t_logs  = $wpdb->prefix . 'rmbz_distro_import_logs';
    $t_daily = $wpdb->prefix . 'rmbz_distro_daily_stats';

    if ( ! rmbz_analytics_table_exists( $t_logs ) ||
         ! rmbz_analytics_table_exists( $t_daily ) ) {
        return [];
    }

    $cols_daily  = (array) $wpdb->get_col( "SHOW COLUMNS FROM $t_daily" );
    $has_log_id  = in_array( 'import_log_id', $cols_daily, true );
    $has_hash    = in_array( 'import_hash',   $cols_daily, true );
    $has_pending = in_array( 'pending_approval', $cols_daily, true );
    $approval_where = $has_pending ? 'AND ds.pending_approval = 0' : '';

    // Mesmo fallback de JOIN do endpoint REST — linhas antigas têm
    // import_log_id NULL e ligam-se por import_hash.
    if ( $has_log_id && $has_hash ) {
        $join_clause = "ds.import_log_id = il.id
                        OR ( ds.import_log_id IS NULL AND ds.import_hash = il.file_hash )";
    } elseif ( $has_hash ) {
        $join_clause = "ds.import_hash = il.file_hash";
    } else {
        $join_clause = "ds.import_log_id = il.id";
    }

    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT
             il.id,
             il.source_name,
             il.reporting_period,
             il.imported_at,
             il.approval_status,
             COALESCE(SUM(ds.sales), 0)   AS earnings_usd,
             COALESCE(SUM(ds.streams), 0) AS streams,
             COUNT(DISTINCT ds.store)        AS stores_count,
             COUNT(DISTINCT ds.country_code) AS countries_count
         FROM $t_logs il
         INNER JOIN $t_daily ds ON ( $join_clause )
         WHERE il.status = 'active'
           AND ds.artist_telemovel = %s
           $approval_where
         GROUP BY il.id
         HAVING earnings_usd > 0 OR streams > 0
         ORDER BY il.imported_at DESC
         LIMIT %d",
        $telemovel, $limit
    ) );

    return is_array( $rows ) ? $rows : [];
}

/**
 * Converte "2026-04" ou "2026-04-01" no nome do mês em PT.
 * Ex: "2026-04" → "Abril 2026". Devolve o original se não reconhecer.
 */
function rmbz_analytics_format_period( $period ) {
    $period = trim( (string) $period );
    if ( $period === '' || strpos( $period, '-' ) === false ) {
        return $period ?: '—';
    }
    $parts = explode( '-', $period );
    $meses = [
        1 => 'Janeiro', 2 => 'Fevereiro', 3 => 'Março', 4 => 'Abril',
        5 => 'Maio', 6 => 'Junho', 7 => 'Julho', 8 => 'Agosto',
        9 => 'Setembro', 10 => 'Outubro', 11 => 'Novembro', 12 => 'Dezembro',
    ];
    $ano = (int) $parts[0];
    $mes = (int) ( $parts[1] ?? 0 );
    if ( isset( $meses[ $mes ] ) && $ano > 0 ) {
        return $meses[ $mes ] . ' ' . $ano;
    }
    return $period;
}

/**
 * Renderiza a secção "Relatórios mensais" — lista de imports.
 *
 * Pensada para ser chamada no fim da rmbz_render_analytics_view,
 * dentro do container .distro-analytics-container.
 *
 * @param string $telemovel  Telemóvel do artista.
 */
function rmbz_analytics_render_imports_section( $telemovel ) {
    $imports = rmbz_analytics_get_imports_list( $telemovel, 24 );

    // Sem relatórios — não mostra a secção (a vista antiga já tem
    // o empty state educativo).
    if ( empty( $imports ) ) {
        return;
    }
    ?>
    <div style="margin-top:32px;">
        <div style="display:flex; align-items:center; gap:10px; margin-bottom:16px;">
            <span style="font-size:20px;">📄</span>
            <h2 style="color:var(--rmbz-text-primary, #fff); margin:0; font-size:18px;">
                Relatórios mensais
            </h2>
        </div>
        <p style="color:var(--rmbz-text-faint, #888); font-size:12px; margin:0 0 16px 0;">
            Cada relatório corresponde a um mês reportado pela distribuidora.
            Toca para ver o detalhe.
        </p>

        <div style="display:flex; flex-direction:column; gap:10px;">
            <?php foreach ( $imports as $imp ):
                $period_label = rmbz_analytics_format_period( $imp->reporting_period );
                $earnings     = (float) $imp->earnings_usd;
                $streams      = (int) $imp->streams;
                $detail_url   = add_query_arg( [
                    'distro_action' => 'analytics',
                    'import_id'     => (int) $imp->id,
                ] );
            ?>
                <a href="<?php echo esc_url( $detail_url ); ?>"
                   style="display:flex; align-items:center; gap:14px;
                          background:var(--rmbz-bg-surface, #1a1a1a);
                          border:1px solid #2a2a2a; border-radius:12px;
                          padding:14px 16px; text-decoration:none;
                          transition:border-color .15s;"
                   onmouseover="this.style.borderColor='#f0b90b';"
                   onmouseout="this.style.borderColor='#2a2a2a';">
                    <div style="width:42px; height:42px; border-radius:10px;
                                background:rgba(240,185,11,0.12);
                                display:flex; align-items:center; justify-content:center;
                                font-size:20px; flex-shrink:0;">📅</div>
                    <div style="flex:1; min-width:0;">
                        <strong style="color:var(--rmbz-text-primary, #fff);
                                       font-size:14px; display:block;">
                            <?php echo esc_html( $period_label ); ?>
                        </strong>
                        <small style="color:var(--rmbz-text-faint, #888); font-size:11px;">
                            1MZ For Artists
                            · <?php echo number_format( $streams ); ?> streams
                        </small>
                    </div>
                    <div style="text-align:right;">
                        <strong style="color:var(--rmbz-success, #10b981);
                                       font-size:15px; display:block;">
                            $<?php echo number_format( $earnings, 2 ); ?>
                        </strong>
                        <small style="color:var(--rmbz-text-faint, #666); font-size:10px;">
                            <?php echo (int) $imp->stores_count; ?> lojas
                        </small>
                    </div>
                    <span style="color:#f0b90b; font-size:18px;">›</span>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}

/* ============================================================================
 * [1.5.228] FASE 1b — Evolução mês-a-mês
 *
 * Mostra a tendência: ganhos/streams de cada relatório, com a
 * variação % face ao mês anterior (subida/descida). Igual ao
 * ecrã "Evolução" da app.
 * ============================================================================ */

/**
 * Renderiza a secção "Evolução" — tendência mês-a-mês com gráfico
 * de barras e variações.
 *
 * @param string $telemovel  Telemóvel do artista.
 */
function rmbz_analytics_render_evolution_section( $telemovel ) {
    $imports = rmbz_analytics_get_imports_list( $telemovel, 24 );

    // Precisa de pelo menos 1 relatório.
    if ( empty( $imports ) ) {
        return;
    }

    // A query devolve do mais recente para o mais antigo —
    // invertemos para ficar cronológico (antigo → recente).
    $chrono = array_reverse( $imports );

    // Construir pontos com variação % (sobre ganhos).
    $points = [];
    $prev_earnings = null;
    foreach ( $chrono as $imp ) {
        $earnings = (float) $imp->earnings_usd;
        $change   = null;
        if ( $prev_earnings !== null && $prev_earnings > 0 ) {
            $change = ( ( $earnings - $prev_earnings ) / $prev_earnings ) * 100;
        }
        $points[] = [
            'label'    => rmbz_analytics_format_period( $imp->reporting_period ),
            'earnings' => $earnings,
            'streams'  => (int) $imp->streams,
            'change'   => $change,
        ];
        $prev_earnings = $earnings;
    }

    $max_earnings = 0.0;
    foreach ( $points as $p ) {
        if ( $p['earnings'] > $max_earnings ) $max_earnings = $p['earnings'];
    }
    if ( $max_earnings <= 0 ) $max_earnings = 1.0;

    $total = array_sum( array_column( $points, 'earnings' ) );
    ?>
    <div style="margin-top:32px;">
        <div style="display:flex; align-items:center; gap:10px; margin-bottom:16px;">
            <span style="font-size:20px;">📈</span>
            <h2 style="color:var(--rmbz-text-primary, #fff); margin:0; font-size:18px;">
                Evolução mês a mês
            </h2>
        </div>

        <!-- Resumo -->
        <div style="display:flex; gap:12px; margin-bottom:18px; flex-wrap:wrap;">
            <div style="flex:1; min-width:140px; background:var(--rmbz-bg-surface, #1a1a1a);
                        border-radius:12px; padding:14px;">
                <small style="color:var(--rmbz-text-faint, #888); font-size:11px;">
                    Total acumulado
                </small>
                <strong style="color:var(--rmbz-success, #10b981); font-size:18px;
                               display:block; margin-top:4px;">
                    $<?php echo number_format( $total, 2 ); ?>
                </strong>
            </div>
            <div style="flex:1; min-width:140px; background:var(--rmbz-bg-surface, #1a1a1a);
                        border-radius:12px; padding:14px;">
                <small style="color:var(--rmbz-text-faint, #888); font-size:11px;">
                    Relatórios
                </small>
                <strong style="color:var(--rmbz-text-primary, #fff); font-size:18px;
                               display:block; margin-top:4px;">
                    <?php echo count( $points ); ?>
                </strong>
            </div>
        </div>

        <?php if ( count( $points ) >= 2 ): ?>
            <!-- Gráfico de barras -->
            <div style="background:var(--rmbz-bg-surface, #1a1a1a); border-radius:12px;
                        padding:18px; margin-bottom:18px;">
                <div style="display:flex; align-items:flex-end; gap:8px; height:160px;">
                    <?php foreach ( $points as $p ):
                        $h = max( 4, ( $p['earnings'] / $max_earnings ) * 130 );
                    ?>
                        <div style="flex:1; display:flex; flex-direction:column;
                                    align-items:center; justify-content:flex-end;">
                            <div style="width:100%; max-width:42px;
                                        height:<?php echo (int) $h; ?>px;
                                        background:linear-gradient(180deg,#DAA520,#B8860B);
                                        border-radius:6px 6px 0 0;"
                                 title="$<?php echo number_format( $p['earnings'], 2 ); ?>"></div>
                            <small style="color:var(--rmbz-text-faint, #888);
                                           font-size:9px; margin-top:6px; text-align:center;">
                                <?php echo esc_html( substr( $p['label'], 0, 3 ) ); ?>
                            </small>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php else: ?>
            <p style="color:var(--rmbz-text-faint, #888); font-size:12px;
                      background:var(--rmbz-bg-surface,#1a1a1a); border-radius:12px;
                      padding:16px; margin-bottom:18px;">
                Só há um relatório por agora. Quando chegar o próximo mês,
                vais ver aqui a comparação.
            </p>
        <?php endif; ?>

        <!-- Detalhe por mês (do mais recente para o mais antigo) -->
        <div style="display:flex; flex-direction:column; gap:8px;">
            <?php foreach ( array_reverse( $points ) as $p ):
                $change = $p['change'];
                if ( $change === null ) {
                    $pill_bg = 'rgba(150,150,150,0.15)';
                    $pill_fg = '#999';
                    $pill_tx = '1º mês';
                } elseif ( $change > 0.5 ) {
                    $pill_bg = 'rgba(46,204,113,0.15)';
                    $pill_fg = '#2ecc71';
                    $pill_tx = '▲ +' . number_format( $change, 0 ) . '%';
                } elseif ( $change < -0.5 ) {
                    $pill_bg = 'rgba(231,76,60,0.15)';
                    $pill_fg = '#e74c3c';
                    $pill_tx = '▼ ' . number_format( $change, 0 ) . '%';
                } else {
                    $pill_bg = 'rgba(150,150,150,0.15)';
                    $pill_fg = '#999';
                    $pill_tx = 'estável';
                }
            ?>
                <div style="display:flex; align-items:center; gap:12px;
                            background:var(--rmbz-bg-surface, #1a1a1a);
                            border-radius:10px; padding:12px 14px;">
                    <div style="flex:1; min-width:0;">
                        <strong style="color:var(--rmbz-text-primary, #fff);
                                       font-size:13px; display:block;">
                            <?php echo esc_html( $p['label'] ); ?>
                        </strong>
                        <small style="color:var(--rmbz-text-faint, #888); font-size:11px;">
                            $<?php echo number_format( $p['earnings'], 2 ); ?>
                            · <?php echo number_format( $p['streams'] ); ?> streams
                        </small>
                    </div>
                    <span style="background:<?php echo $pill_bg; ?>;
                                 color:<?php echo $pill_fg; ?>;
                                 font-size:11px; font-weight:700;
                                 padding:5px 10px; border-radius:50px;">
                        <?php echo esc_html( $pill_tx ); ?>
                    </span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}

/* ============================================================================
 * [1.5.229] FASE 1c — Detalhe de um relatório (import)
 *
 * Quando o artista clica num relatório da lista, mostramos o
 * detalhe: totais, Top 5 músicas, Top 5 lojas, Top 5 países e
 * gráfico diário. Igual ao ecrã da app.
 *
 * Reusa a lógica do endpoint /stats/imports/{id} da API.
 * ============================================================================ */

/**
 * Vai buscar o detalhe completo de um import.
 *
 * @param string $telemovel  Telemóvel do artista.
 * @param int    $import_id  ID do import.
 * @return array|null  ['header'=>.., 'totals'=>.., 'top_tracks'=>[],
 *                      'top_stores'=>[], 'top_countries'=>[], 'daily'=>[]]
 *                      ou null se não existir.
 */
function rmbz_analytics_get_import_detail( $telemovel, $import_id ) {
    global $wpdb;

    $import_id = (int) $import_id;
    if ( $import_id <= 0 ) return null;

    $t_logs     = $wpdb->prefix . 'rmbz_distro_import_logs';
    $t_daily    = $wpdb->prefix . 'rmbz_distro_daily_stats';
    $t_tracks   = $wpdb->prefix . 'rmbz_distro_tracks';
    $t_releases = $wpdb->prefix . 'rmbz_distro_releases';

    if ( ! rmbz_analytics_table_exists( $t_logs ) ||
         ! rmbz_analytics_table_exists( $t_daily ) ) {
        return null;
    }

    $log = $wpdb->get_row( $wpdb->prepare(
        "SELECT id, source_name, reporting_period, imported_at,
                approval_status, status, file_hash
         FROM $t_logs WHERE id = %d",
        $import_id
    ) );
    if ( ! $log || $log->status !== 'active' ) return null;

    $cols_daily  = (array) $wpdb->get_col( "SHOW COLUMNS FROM $t_daily" );
    $has_log_id  = in_array( 'import_log_id', $cols_daily, true );
    $has_hash    = in_array( 'import_hash',   $cols_daily, true );
    $has_pending = in_array( 'pending_approval', $cols_daily, true );
    $approval_where = $has_pending ? 'AND pending_approval = 0' : '';

    // Fallback por hash para linhas antigas (igual ao endpoint REST).
    if ( $has_log_id && $has_hash ) {
        $row_match  = "( import_log_id = %d OR ( import_log_id IS NULL AND import_hash = %s ) )";
        $row_params = [ $import_id, (string) ( $log->file_hash ?? '' ) ];
    } elseif ( $has_hash ) {
        $row_match  = "import_hash = %s";
        $row_params = [ (string) ( $log->file_hash ?? '' ) ];
    } else {
        $row_match  = "import_log_id = %d";
        $row_params = [ $import_id ];
    }
    $totals_params = array_merge( $row_params, [ $telemovel ] );

    $artist_rows = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM $t_daily WHERE $row_match AND artist_telemovel = %s $approval_where",
        $totals_params
    ) );
    if ( $artist_rows < 1 ) return null;

    // Totais
    $totals = $wpdb->get_row( $wpdb->prepare(
        "SELECT COALESCE(SUM(sales),0) AS earnings_usd,
                COALESCE(SUM(streams),0) AS streams
         FROM $t_daily
         WHERE $row_match AND artist_telemovel = %s $approval_where",
        $totals_params
    ) );
    $earnings = $totals ? (float) $totals->earnings_usd : 0.0;
    $streams  = $totals ? (int)   $totals->streams      : 0;

    // Top 5 lojas
    $top_stores = $wpdb->get_results( $wpdb->prepare(
        "SELECT store, SUM(sales) AS earnings_usd, SUM(streams) AS streams
         FROM $t_daily
         WHERE $row_match AND artist_telemovel = %s $approval_where
         GROUP BY store ORDER BY earnings_usd DESC LIMIT 5",
        $totals_params
    ) );

    // Top 5 países
    $top_countries = $wpdb->get_results( $wpdb->prepare(
        "SELECT country_code, SUM(sales) AS earnings_usd, SUM(streams) AS streams
         FROM $t_daily
         WHERE $row_match AND artist_telemovel = %s $approval_where
         GROUP BY country_code ORDER BY earnings_usd DESC LIMIT 5",
        $totals_params
    ) );

    // Top 5 faixas (JOIN com tracks)
    $top_tracks = [];
    if ( rmbz_analytics_table_exists( $t_tracks ) ) {
        $top_tracks = $wpdb->get_results( $wpdb->prepare(
            "SELECT t.track_title, SUM(d.sales) AS earnings_usd, SUM(d.streams) AS streams
             FROM $t_daily d
             JOIN $t_tracks t ON d.track_id = t.id
             WHERE $row_match AND d.artist_telemovel = %s
               AND d.track_id IS NOT NULL $approval_where
             GROUP BY t.id ORDER BY earnings_usd DESC LIMIT 5",
            $totals_params
        ) );
    }

    // Timeline diária
    $daily = $wpdb->get_results( $wpdb->prepare(
        "SELECT report_date AS day, SUM(sales) AS earnings_usd, SUM(streams) AS streams
         FROM $t_daily
         WHERE $row_match AND artist_telemovel = %s $approval_where
         GROUP BY report_date ORDER BY report_date ASC",
        $totals_params
    ) );

    return [
        'header'        => $log,
        'earnings'      => $earnings,
        'streams'       => $streams,
        'top_tracks'    => is_array( $top_tracks )    ? $top_tracks    : [],
        'top_stores'    => is_array( $top_stores )    ? $top_stores    : [],
        'top_countries' => is_array( $top_countries ) ? $top_countries : [],
        'daily'         => is_array( $daily )         ? $daily         : [],
    ];
}

/**
 * Renderiza a PÁGINA de detalhe de um relatório.
 * Chamada quando ?import_id=X está presente na vista de analytics.
 *
 * @param string $telemovel  Telemóvel do artista.
 * @param int    $import_id  ID do import.
 */
function rmbz_analytics_render_import_detail_page( $telemovel, $import_id ) {
    $detail = rmbz_analytics_get_import_detail( $telemovel, $import_id );

    $back_url = remove_query_arg( 'import_id' );

    if ( ! $detail ) {
        ?>
        <div class="distro-analytics-container rmbz-fullbleed">
            <a href="<?php echo esc_url( $back_url ); ?>"
               style="color:#f0b90b; text-decoration:none; font-size:13px;">
                &larr; Voltar às estatísticas
            </a>
            <div style="background:var(--rmbz-bg-surface,#1a1a1a);
                        border-radius:12px; padding:30px; margin-top:16px;
                        text-align:center; color:var(--rmbz-text-faint,#888);">
                Relatório não encontrado.
            </div>
        </div>
        <?php
        return;
    }

    $header       = $detail['header'];
    $period_label = rmbz_analytics_format_period( $header->reporting_period );
    $earnings     = (float) $detail['earnings'];
    $streams      = (int) $detail['streams'];
    $daily        = $detail['daily'];

    // Máximo para o gráfico diário
    $max_daily = 0;
    foreach ( $daily as $d ) {
        if ( (int) $d->streams > $max_daily ) $max_daily = (int) $d->streams;
    }
    if ( $max_daily <= 0 ) $max_daily = 1;
    ?>
    <div class="distro-analytics-container rmbz-fullbleed">

        <a href="<?php echo esc_url( $back_url ); ?>"
           style="color:#f0b90b; text-decoration:none; font-size:13px;
                  display:inline-block; margin-bottom:16px;">
            &larr; Voltar às estatísticas
        </a>

        <!-- Cabeçalho -->
        <div style="display:flex; align-items:center; gap:14px; margin-bottom:20px;">
            <div style="width:54px; height:54px; border-radius:12px;
                        background:rgba(240,185,11,0.12); display:flex;
                        align-items:center; justify-content:center; font-size:26px;">📅</div>
            <div>
                <h1 style="color:var(--rmbz-text-primary,#fff); margin:0; font-size:24px;">
                    <?php echo esc_html( $period_label ); ?>
                </h1>
                <small style="color:var(--rmbz-text-faint,#888); font-size:12px;">
                    Relatório · 1MZ For Artists
                </small>
            </div>
        </div>

        <!-- Hero de ganhos -->
        <div style="background:var(--rmbz-bg-surface,#1a1a1a);
                    border:1px solid rgba(240,185,11,0.35); border-radius:16px;
                    padding:22px; margin-bottom:14px;">
            <small style="color:var(--rmbz-text-faint,#888); font-size:12px;">
                Ganho neste relatório
            </small>
            <div style="color:var(--rmbz-text-primary,#fff); font-size:36px;
                        font-weight:700; margin-top:4px;">
                <span style="color:#DAA520; font-size:22px;">$</span><?php
                echo number_format( $earnings, 2 ); ?>
                <span style="color:var(--rmbz-text-faint,#888); font-size:14px;">USD</span>
            </div>
        </div>

        <!-- Mini-stats -->
        <div style="display:flex; gap:12px; margin-bottom:20px; flex-wrap:wrap;">
            <div style="flex:1; min-width:140px; background:var(--rmbz-bg-surface,#1a1a1a);
                        border-radius:12px; padding:14px;">
                <small style="color:var(--rmbz-text-faint,#888); font-size:11px;">
                    Streams
                </small>
                <strong style="color:var(--rmbz-text-primary,#fff); font-size:20px;
                               display:block; margin-top:4px;">
                    <?php echo number_format( $streams ); ?>
                </strong>
            </div>
            <div style="flex:1; min-width:140px; background:var(--rmbz-bg-surface,#1a1a1a);
                        border-radius:12px; padding:14px;">
                <small style="color:var(--rmbz-text-faint,#888); font-size:11px;">
                    Dias com dados
                </small>
                <strong style="color:var(--rmbz-text-primary,#fff); font-size:20px;
                               display:block; margin-top:4px;">
                    <?php echo count( $daily ); ?>
                </strong>
            </div>
        </div>

        <?php if ( count( $daily ) >= 2 ): ?>
            <!-- Gráfico diário -->
            <h3 style="color:var(--rmbz-text-primary,#fff); font-size:15px;
                       margin:0 0 12px 0;">Streams por dia</h3>
            <div style="background:var(--rmbz-bg-surface,#1a1a1a); border-radius:12px;
                        padding:18px; margin-bottom:24px;">
                <div style="display:flex; align-items:flex-end; gap:4px; height:140px;">
                    <?php foreach ( $daily as $d ):
                        $h = max( 3, ( (int) $d->streams / $max_daily ) * 115 );
                    ?>
                        <div style="flex:1; height:<?php echo (int) $h; ?>px;
                                    background:linear-gradient(180deg,#DAA520,#B8860B);
                                    border-radius:3px 3px 0 0;"
                             title="<?php echo esc_attr( $d->day . ': ' . number_format( (int) $d->streams ) . ' streams' ); ?>"></div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php
        // Top músicas
        rmbz_analytics_render_breakdown(
            '🎵 Top 5 músicas', $detail['top_tracks'], 'track_title', $earnings
        );
        // Top lojas
        rmbz_analytics_render_breakdown(
            '📻 Top 5 lojas', $detail['top_stores'], 'store', $earnings
        );
        // Top países
        rmbz_analytics_render_breakdown(
            '🌍 Top 5 países', $detail['top_countries'], 'country_code', $earnings
        );
        ?>

    </div>
    <?php
}

/**
 * Helper — renderiza uma lista de breakdown (músicas/lojas/países).
 *
 * @param string $title       Título da secção.
 * @param array  $rows        Linhas (cada uma com $name_field, earnings_usd, streams).
 * @param string $name_field  Campo do nome em cada linha.
 * @param float  $total_earn  Total de ganhos do import (para a %).
 */
function rmbz_analytics_render_breakdown( $title, $rows, $name_field, $total_earn ) {
    if ( empty( $rows ) ) return;
    ?>
    <div style="margin-bottom:22px;">
        <h3 style="color:var(--rmbz-text-primary,#fff); font-size:15px;
                   margin:0 0 12px 0;"><?php echo esc_html( $title ); ?></h3>
        <div style="display:flex; flex-direction:column; gap:8px;">
            <?php foreach ( $rows as $row ):
                $name     = (string) ( $row->$name_field ?? '—' );
                $earn     = (float) $row->earnings_usd;
                $streams  = (int) $row->streams;
                $pct      = $total_earn > 0 ? ( $earn / $total_earn ) * 100 : 0;

                // País: mostrar bandeira
                if ( $name_field === 'country_code' && function_exists( 'rmbz_country_flag' ) ) {
                    $name = rmbz_country_flag( $name ) . ' ' . ( $name ?: 'UNK' );
                }
            ?>
                <div style="background:var(--rmbz-bg-surface,#1a1a1a);
                            border-radius:10px; padding:12px 14px;">
                    <div style="display:flex; align-items:center; gap:10px;">
                        <strong style="flex:1; color:var(--rmbz-text-primary,#fff);
                                       font-size:13px; min-width:0;">
                            <?php echo esc_html( $name ); ?>
                        </strong>
                        <span style="color:#f0b90b; font-size:12px; font-weight:700;">
                            <?php echo number_format( $pct, 1 ); ?>%
                        </span>
                        <strong style="color:var(--rmbz-success,#10b981); font-size:13px;">
                            $<?php echo number_format( $earn, 2 ); ?>
                        </strong>
                    </div>
                    <div style="margin-top:8px; height:3px; border-radius:2px;
                                background:rgba(255,255,255,0.06);">
                        <div style="height:3px; border-radius:2px;
                                    width:<?php echo min( 100, max( 2, $pct ) ); ?>%;
                                    background:#DAA520;"></div>
                    </div>
                    <small style="color:var(--rmbz-text-faint,#666); font-size:10px;">
                        <?php echo number_format( $streams ); ?> streams
                    </small>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
}

/* ============================================================================
 * [1.5.230] FASE 1d — Relatório de ganhos por release
 *
 * Agrega todas as faixas de um release. Igual ao "Relatório de
 * ganhos" da app. Mostra: ganhos totais, streams, top lojas,
 * top países e breakdown por faixa.
 * ============================================================================ */

/**
 * Vai buscar o relatório de ganhos de um release inteiro.
 *
 * @param string $telemovel  Telemóvel do artista.
 * @param int    $release_id ID do release.
 * @return array  ['has_data'=>bool, 'release'=>obj, ...]
 */
function rmbz_analytics_get_release_detail( $telemovel, $release_id ) {
    global $wpdb;

    $release_id = (int) $release_id;
    $t_daily    = $wpdb->prefix . 'rmbz_distro_daily_stats';
    $t_tracks   = $wpdb->prefix . 'rmbz_distro_tracks';
    $t_releases = $wpdb->prefix . 'rmbz_distro_releases';

    $release = $wpdb->get_row( $wpdb->prepare(
        "SELECT id, title, cover_image FROM $t_releases WHERE id = %d AND artist_telemovel = %s LIMIT 1",
        $release_id, $telemovel
    ) );
    if ( ! $release ) return [ 'has_data' => false, 'release' => null ];

    if ( ! rmbz_analytics_table_exists( $t_daily ) ) {
        return [ 'has_data' => false, 'release' => $release ];
    }

    $pa = function_exists( 'rmbz_approval_clause' )
        ? rmbz_approval_clause( $t_daily ) : '';

    // Faixas do release
    $track_ids = (array) $wpdb->get_col( $wpdb->prepare(
        "SELECT id FROM $t_tracks WHERE release_id = %d", $release_id
    ) );
    $track_ids = array_map( 'intval', $track_ids );

    if ( empty( $track_ids ) ) {
        return [ 'has_data' => false, 'release' => $release ];
    }

    $ph = implode( ',', array_fill( 0, count( $track_ids ), '%d' ) );
    $in = "track_id IN ($ph)";

    // Há linhas de stats?
    $has_rows = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM $t_daily
         WHERE artist_telemovel = %s AND $in $pa",
        array_merge( [ $telemovel ], $track_ids )
    ) );
    if ( $has_rows === 0 ) {
        return [ 'has_data' => false, 'release' => $release ];
    }

    // Totais
    $totals = $wpdb->get_row( $wpdb->prepare(
        "SELECT COALESCE(SUM(streams),0) s, COALESCE(SUM(sales),0) e
         FROM $t_daily WHERE artist_telemovel = %s AND $in $pa",
        array_merge( [ $telemovel ], $track_ids )
    ) );
    $streams  = $totals ? (int)   $totals->s : 0;
    $earnings = $totals ? (float) $totals->e : 0.0;

    // Top lojas
    $top_stores = $wpdb->get_results( $wpdb->prepare(
        "SELECT store, SUM(streams) AS streams, SUM(sales) AS earnings_usd
         FROM $t_daily WHERE artist_telemovel = %s AND $in $pa
         GROUP BY store ORDER BY streams DESC LIMIT 10",
        array_merge( [ $telemovel ], $track_ids )
    ) );

    // Top países
    $top_countries = $wpdb->get_results( $wpdb->prepare(
        "SELECT country_code, SUM(streams) AS streams, SUM(sales) AS earnings_usd
         FROM $t_daily WHERE artist_telemovel = %s AND $in $pa
         GROUP BY country_code ORDER BY streams DESC LIMIT 10",
        array_merge( [ $telemovel ], $track_ids )
    ) );

    // Breakdown por faixa
    $tracks = $wpdb->get_results( $wpdb->prepare(
        "SELECT t.track_title,
                COALESCE(SUM(d.streams),0) AS streams,
                COALESCE(SUM(d.sales),0)   AS earnings_usd
         FROM $t_tracks t
         LEFT JOIN $t_daily d ON d.track_id = t.id
                AND d.artist_telemovel = %s $pa
         WHERE t.release_id = %d
         GROUP BY t.id ORDER BY earnings_usd DESC",
        $telemovel, $release_id
    ) );

    return [
        'has_data'      => true,
        'release'       => $release,
        'streams'       => $streams,
        'earnings'      => $earnings,
        'top_stores'    => is_array( $top_stores )    ? $top_stores    : [],
        'top_countries' => is_array( $top_countries ) ? $top_countries : [],
        'tracks'        => is_array( $tracks )        ? $tracks        : [],
    ];
}

/**
 * Renderiza a PÁGINA do relatório de ganhos de um release.
 * Chamada quando ?release_stats=X está presente.
 *
 * @param string $telemovel  Telemóvel do artista.
 * @param int    $release_id ID do release.
 */
function rmbz_analytics_render_release_detail_page( $telemovel, $release_id ) {
    $detail   = rmbz_analytics_get_release_detail( $telemovel, $release_id );
    $back_url = remove_query_arg( 'release_stats' );
    $release  = $detail['release'];

    ?>
    <div class="distro-analytics-container rmbz-fullbleed">
        <a href="<?php echo esc_url( $back_url ); ?>"
           style="color:#f0b90b; text-decoration:none; font-size:13px;
                  display:inline-block; margin-bottom:16px;">
            &larr; Voltar
        </a>

        <?php if ( ! $release ): ?>
            <div style="background:var(--rmbz-bg-surface,#1a1a1a); border-radius:12px;
                        padding:30px; text-align:center; color:var(--rmbz-text-faint,#888);">
                Lançamento não encontrado.
            </div>
            </div>
            <?php return; ?>
        <?php endif; ?>

        <!-- Cabeçalho -->
        <div style="display:flex; align-items:center; gap:14px; margin-bottom:20px;">
            <?php if ( ! empty( $release->cover_image ) ): ?>
                <img src="<?php echo esc_url( $release->cover_image ); ?>"
                     style="width:56px; height:56px; border-radius:10px; object-fit:cover;"
                     alt="">
            <?php else: ?>
                <div style="width:56px; height:56px; border-radius:10px;
                            background:rgba(240,185,11,0.12); display:flex;
                            align-items:center; justify-content:center; font-size:26px;">🎵</div>
            <?php endif; ?>
            <div>
                <h1 style="color:var(--rmbz-text-primary,#fff); margin:0; font-size:22px;">
                    <?php echo esc_html( $release->title ); ?>
                </h1>
                <small style="color:var(--rmbz-text-faint,#888); font-size:12px;">
                    Relatório de ganhos do lançamento
                </small>
            </div>
        </div>

        <?php if ( empty( $detail['has_data'] ) ): ?>
            <!-- Estado "a acumular ganhos" -->
            <div style="background:var(--rmbz-bg-surface,#1a1a1a); border-radius:16px;
                        padding:40px 24px; text-align:center;">
                <div style="font-size:42px; margin-bottom:12px;">📈</div>
                <h2 style="color:var(--rmbz-text-primary,#fff); font-size:17px; margin:0 0 8px;">
                    Esta música está a acumular ganhos
                </h2>
                <p style="color:var(--rmbz-text-faint,#888); font-size:13px;
                          max-width:420px; margin:0 auto; line-height:1.6;">
                    Ainda não há relatórios da distribuidora para este
                    lançamento. Assim que chegarem os primeiros dados de
                    reproduções e ganhos, o relatório aparece aqui.
                </p>
            </div>
            </div>
            <?php return; ?>
        <?php endif; ?>

        <?php
        $earnings = (float) $detail['earnings'];
        $streams  = (int) $detail['streams'];
        $tracks   = $detail['tracks'];
        ?>

        <!-- Hero de ganhos -->
        <div style="background:var(--rmbz-bg-surface,#1a1a1a);
                    border:1px solid rgba(240,185,11,0.35); border-radius:16px;
                    padding:22px; margin-bottom:14px;">
            <small style="color:var(--rmbz-text-faint,#888); font-size:12px;">
                Total ganho com este lançamento
            </small>
            <div style="color:var(--rmbz-text-primary,#fff); font-size:36px;
                        font-weight:700; margin-top:4px;">
                <span style="color:#DAA520; font-size:22px;">$</span><?php
                echo number_format( $earnings, 2 ); ?>
                <span style="color:var(--rmbz-text-faint,#888); font-size:14px;">USD</span>
            </div>
        </div>

        <!-- Mini-stats -->
        <div style="display:flex; gap:12px; margin-bottom:20px; flex-wrap:wrap;">
            <div style="flex:1; min-width:140px; background:var(--rmbz-bg-surface,#1a1a1a);
                        border-radius:12px; padding:14px;">
                <small style="color:var(--rmbz-text-faint,#888); font-size:11px;">Reproduções</small>
                <strong style="color:var(--rmbz-text-primary,#fff); font-size:20px;
                               display:block; margin-top:4px;">
                    <?php echo number_format( $streams ); ?>
                </strong>
            </div>
            <div style="flex:1; min-width:140px; background:var(--rmbz-bg-surface,#1a1a1a);
                        border-radius:12px; padding:14px;">
                <small style="color:var(--rmbz-text-faint,#888); font-size:11px;">Faixas</small>
                <strong style="color:var(--rmbz-text-primary,#fff); font-size:20px;
                               display:block; margin-top:4px;">
                    <?php echo count( $tracks ); ?>
                </strong>
            </div>
        </div>

        <?php if ( ! empty( $tracks ) ): ?>
            <h3 style="color:var(--rmbz-text-primary,#fff); font-size:15px;
                       margin:0 0 12px 0;">🎵 Faixas</h3>
            <div style="display:flex; flex-direction:column; gap:8px; margin-bottom:22px;">
                <?php $pos = 0; foreach ( $tracks as $t ): $pos++; ?>
                    <div style="display:flex; align-items:center; gap:12px;
                                background:var(--rmbz-bg-surface,#1a1a1a);
                                border-radius:10px; padding:12px 14px;">
                        <div style="width:26px; height:26px; border-radius:50%;
                                    background:<?php echo $pos <= 3 ? 'rgba(240,185,11,0.18)' : 'rgba(255,255,255,0.06)'; ?>;
                                    display:flex; align-items:center; justify-content:center;
                                    color:<?php echo $pos <= 3 ? '#DAA520' : '#888'; ?>;
                                    font-size:12px; font-weight:700; flex-shrink:0;">
                            <?php echo $pos; ?>
                        </div>
                        <div style="flex:1; min-width:0;">
                            <strong style="color:var(--rmbz-text-primary,#fff);
                                           font-size:13px; display:block;">
                                <?php echo esc_html( $t->track_title ?: 'Faixa' ); ?>
                            </strong>
                            <small style="color:var(--rmbz-text-faint,#888); font-size:11px;">
                                <?php echo number_format( (int) $t->streams ); ?> reproduções
                            </small>
                        </div>
                        <strong style="color:var(--rmbz-success,#10b981); font-size:14px;">
                            $<?php echo number_format( (float) $t->earnings_usd, 2 ); ?>
                        </strong>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php
        rmbz_analytics_render_breakdown(
            '📻 Top plataformas', $detail['top_stores'], 'store', $earnings
        );
        rmbz_analytics_render_breakdown(
            '🌍 Top países', $detail['top_countries'], 'country_code', $earnings
        );
        ?>

    </div>
    <?php
}
