<?php
/**
 * [FEAT 1.6.24] RESUMO FINANCEIRO MENSAL POR ARTISTA
 *
 * Página dentro do admin que mostra a um artista, num mês específico:
 *   - Receita total + breakdown por loja + país + faixa
 *   - Pagamentos feitos nesse período
 *   - Saldo (receita - pagamentos)
 *
 * Útil para enviar a artistas que perguntam "porque é que ganhei X?".
 *
 * Acedida via:
 *   ?page=rmbz-admin-distribution&tab=royalties&rsub=artist_summary
 *      &artist=+258...&period=2026-01
 *
 * Tem print-CSS que esconde o admin do WordPress para o admin poder
 * imprimir ou guardar como PDF directamente do navegador.
 */

defined('ABSPATH') or exit;


function rmbz_render_royalties_artist_summary() {
    global $wpdb;

    $artist_tel = isset($_GET['artist']) ? sanitize_text_field($_GET['artist']) : '';
    $period     = isset($_GET['period']) ? sanitize_text_field($_GET['period']) : date('Y-m', strtotime('-1 month'));

    if ( ! preg_match('/^\d{4}-\d{2}$/', $period) ) {
        $period = date('Y-m', strtotime('-1 month'));
    }
    if ( empty($artist_tel) ) {
        echo '<div class="notice notice-warning"><p>⚠ Falta o parâmetro <code>artist</code> (telemóvel). Volta a uma página com link de resumo e clica num artista.</p></div>';
        return;
    }

    // ── Lookup do artista ──────────────────────────────────────────────────
    $t_wallets = $wpdb->prefix . 'rmbz_wallets';
    $t_ledger  = $wpdb->prefix . 'rmbz_distro_ledger';
    $t_daily   = $wpdb->prefix . 'rmbz_distro_daily_stats';
    $t_payouts = $wpdb->prefix . 'rmbz_distro_payouts';
    $t_tracks  = $wpdb->prefix . 'rmbz_distro_tracks';

    $artist = $wpdb->get_row( $wpdb->prepare(
        "SELECT user_telemovel, user_nome, user_email
           FROM $t_wallets WHERE user_telemovel = %s LIMIT 1",
        $artist_tel
    ) );

    // Construir nome de exibição
    $artist_name = $artist && $artist->user_nome ? $artist->user_nome : $artist_tel;

    // ── Receita do período (ledger) ────────────────────────────────────────
    $period_revenue = (float) $wpdb->get_var( $wpdb->prepare(
        "SELECT COALESCE(SUM(amount),0)
           FROM $t_ledger
          WHERE artist_telemovel = %s
            AND reporting_period = %s",
        $artist_tel, $period
    ) );

    // ── Pagamentos do período (range de datas para apanhar saques mesmo de períodos antigos) ─
    [$yr, $mo] = explode('-', $period);
    $period_start = "$yr-$mo-01 00:00:00";
    $period_end   = date('Y-m-t 23:59:59', strtotime($period_start));

    $period_payouts = $wpdb->get_results( $wpdb->prepare(
        "SELECT *
           FROM $t_payouts
          WHERE artist_telemovel = %s
            AND status = 'completed'
            AND reverted_at IS NULL
            AND paid_at BETWEEN %s AND %s
          ORDER BY paid_at ASC",
        $artist_tel, $period_start, $period_end
    ) );
    $total_paid_period = 0.0;
    foreach ( $period_payouts as $pp ) $total_paid_period += (float) $pp->amount_usd;

    // ── Breakdown por loja (daily_stats) ───────────────────────────────────
    // Atenção: daily_stats tem report_date dentro do mês reportado, mas a
    // RECEITA não está aí — está em rmbz_distro_ledger. Para breakdown por
    // loja, usamos daily_stats (que tem 'sales' que é a quota proporcional)
    // mas precisamos de juntar com o ledger para alinhar com período.
    //
    // Heurística: filtrar daily_stats por report_date dentro do mês +
    // pending_approval = 0 (já confirmado). Soma de 'sales' deve aproximar
    // a receita do ledger (não bate sempre por causa de splits/taxas).
    $report_date_start = "$yr-$mo-01";
    $report_date_end   = date('Y-m-t', strtotime($report_date_start));

    $by_store = $wpdb->get_results( $wpdb->prepare(
        "SELECT store,
                SUM(streams) AS streams,
                SUM(sales) AS revenue,
                COUNT(DISTINCT track_id) AS tracks
           FROM $t_daily
          WHERE artist_telemovel = %s
            AND report_date BETWEEN %s AND %s
            AND pending_approval = 0
          GROUP BY store
          ORDER BY revenue DESC",
        $artist_tel, $report_date_start, $report_date_end
    ) );

    // ── Breakdown por país ────────────────────────────────────────────────
    $by_country = $wpdb->get_results( $wpdb->prepare(
        "SELECT country_code,
                SUM(streams) AS streams,
                SUM(sales) AS revenue
           FROM $t_daily
          WHERE artist_telemovel = %s
            AND report_date BETWEEN %s AND %s
            AND pending_approval = 0
          GROUP BY country_code
          ORDER BY revenue DESC
          LIMIT 20",
        $artist_tel, $report_date_start, $report_date_end
    ) );

    // ── Breakdown por faixa ───────────────────────────────────────────────
    $by_track = $wpdb->get_results( $wpdb->prepare(
        "SELECT d.track_id,
                t.track_title,
                SUM(d.streams) AS streams,
                SUM(d.sales) AS revenue,
                COUNT(DISTINCT d.store) AS n_stores
           FROM $t_daily d
      LEFT JOIN $t_tracks t ON t.id = d.track_id
          WHERE d.artist_telemovel = %s
            AND d.report_date BETWEEN %s AND %s
            AND d.pending_approval = 0
            AND d.track_id IS NOT NULL
          GROUP BY d.track_id
          ORDER BY revenue DESC
          LIMIT 30",
        $artist_tel, $report_date_start, $report_date_end
    ) );

    // ── Total streams + países distintos ──────────────────────────────────
    $totals = $wpdb->get_row( $wpdb->prepare(
        "SELECT COALESCE(SUM(streams),0) AS streams,
                COUNT(DISTINCT country_code) AS countries,
                COUNT(DISTINCT store) AS stores,
                COUNT(DISTINCT track_id) AS tracks
           FROM $t_daily
          WHERE artist_telemovel = %s
            AND report_date BETWEEN %s AND %s
            AND pending_approval = 0",
        $artist_tel, $report_date_start, $report_date_end
    ) );

    // ── Label PT do mês ────────────────────────────────────────────────────
    $months_pt = ['', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
                  'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
    $period_label = ($months_pt[(int)$mo] ?? '') . ' ' . $yr;

    // ── Permitir mudar período via dropdown ───────────────────────────────
    // Anteriores 12 meses
    $period_options = [];
    for ( $i = 0; $i < 12; $i++ ) {
        $ym = date('Y-m', strtotime("-{$i} months"));
        [$y2, $m2] = explode('-', $ym);
        $period_options[$ym] = ($months_pt[(int)$m2] ?? '') . ' ' . $y2;
    }
    ?>

    <div class="ras-page">

        <?php // ── Topo (escondido na impressão) ────────────────────────── ?>
        <div class="ras-toolbar no-print">
            <form method="get" class="ras-period-form">
                <input type="hidden" name="page" value="rmbz-admin-distribution">
                <input type="hidden" name="tab" value="royalties">
                <input type="hidden" name="rsub" value="artist_summary">
                <input type="hidden" name="artist" value="<?php echo esc_attr($artist_tel); ?>">
                <label>Período:</label>
                <select name="period" onchange="this.form.submit()">
                    <?php foreach ( $period_options as $ym => $lbl ): ?>
                        <option value="<?php echo esc_attr($ym); ?>" <?php selected($period, $ym); ?>><?php echo esc_html($lbl); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>

            <div class="ras-actions">
                <button type="button" onclick="window.print()" class="button button-primary">🖨️ Imprimir / Guardar PDF</button>
                <a href="<?php echo esc_url( admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=payouts') ); ?>" class="button">← Voltar a Pagamentos</a>
            </div>
        </div>

        <?php // ── DOCUMENTO IMPRIMÍVEL ────────────────────────────────── ?>
        <div class="ras-document">

            <header class="ras-header">
                <div class="ras-brand">
                    <strong>1MZ For Artists</strong>
                    <small>Resumo financeiro mensal</small>
                </div>
                <div class="ras-date">
                    Emitido em <?php echo esc_html( date_i18n('d \d\e F \d\e Y') ); ?>
                </div>
            </header>

            <section class="ras-artist-card">
                <div class="ras-artist-info">
                    <h1><?php echo esc_html($artist_name); ?></h1>
                    <div class="ras-artist-meta">
                        <span>📱 <?php echo esc_html($artist_tel); ?></span>
                        <?php if ( $artist && $artist->user_email ): ?>
                            <span>✉ <?php echo esc_html($artist->user_email); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="ras-period-badge">
                    📅 <?php echo esc_html($period_label); ?>
                </div>
            </section>

            <section class="ras-summary">
                <div class="ras-summary-grid">
                    <div class="ras-stat green">
                        <div class="lbl">💵 Receita do período</div>
                        <div class="val">$<?php echo number_format($period_revenue, 2); ?></div>
                        <div class="sub">USD acumulado neste mês</div>
                    </div>
                    <div class="ras-stat blue">
                        <div class="lbl">💸 Pagamentos recebidos</div>
                        <div class="val">$<?php echo number_format($total_paid_period, 2); ?></div>
                        <div class="sub"><?php echo count($period_payouts); ?> pagamento(s) neste mês</div>
                    </div>
                    <div class="ras-stat amber">
                        <div class="lbl">🎵 Faixas com receita</div>
                        <div class="val"><?php echo (int) ($totals->tracks ?? 0); ?></div>
                        <div class="sub"><?php echo number_format((int) ($totals->streams ?? 0)); ?> streams</div>
                    </div>
                    <div class="ras-stat purple">
                        <div class="lbl">🌍 Países alcançados</div>
                        <div class="val"><?php echo (int) ($totals->countries ?? 0); ?></div>
                        <div class="sub"><?php echo (int) ($totals->stores ?? 0); ?> lojas activas</div>
                    </div>
                </div>
            </section>

            <?php if ( ! empty( $by_store ) ): ?>
            <section class="ras-section">
                <h2>📦 Receita por loja</h2>
                <table class="ras-table">
                    <thead>
                        <tr>
                            <th>Loja</th>
                            <th class="num">Streams</th>
                            <th class="num">Faixas activas</th>
                            <th class="num">Receita</th>
                            <th class="num">% do total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $store_total = 0;
                        foreach ( $by_store as $s ) $store_total += (float) $s->revenue;
                        foreach ( $by_store as $s ):
                            $pct = $store_total > 0 ? ( (float) $s->revenue / $store_total ) * 100 : 0;
                        ?>
                            <tr>
                                <td><strong><?php echo esc_html($s->store ?: '—'); ?></strong></td>
                                <td class="num"><?php echo number_format((int) $s->streams); ?></td>
                                <td class="num"><?php echo (int) $s->tracks; ?></td>
                                <td class="num"><strong>$<?php echo number_format((float) $s->revenue, 4); ?></strong></td>
                                <td class="num">
                                    <div class="ras-bar-wrap">
                                        <span class="ras-bar" style="width:<?php echo number_format($pct, 1); ?>%;"></span>
                                        <span class="ras-bar-pct"><?php echo number_format($pct, 1); ?>%</span>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </section>
            <?php endif; ?>

            <?php if ( ! empty( $by_country ) ): ?>
            <section class="ras-section">
                <h2>🌍 Receita por país <small>(top 20)</small></h2>
                <table class="ras-table">
                    <thead>
                        <tr>
                            <th>País</th>
                            <th class="num">Streams</th>
                            <th class="num">Receita</th>
                            <th class="num">% do total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $country_total = 0;
                        foreach ( $by_country as $c ) $country_total += (float) $c->revenue;
                        foreach ( $by_country as $c ):
                            $pct = $country_total > 0 ? ( (float) $c->revenue / $country_total ) * 100 : 0;
                            $flag = function_exists('rmbz_country_flag_emoji') ? rmbz_country_flag_emoji($c->country_code) : '';
                            $cname = function_exists('rmbz_country_name_pt') ? rmbz_country_name_pt($c->country_code) : $c->country_code;
                        ?>
                            <tr>
                                <td>
                                    <?php if ($flag): ?><span style="margin-right:6px;"><?php echo $flag; ?></span><?php endif; ?>
                                    <strong><?php echo esc_html($cname); ?></strong>
                                    <span style="color:#888; font-size:11px;">· <?php echo esc_html($c->country_code); ?></span>
                                </td>
                                <td class="num"><?php echo number_format((int) $c->streams); ?></td>
                                <td class="num"><strong>$<?php echo number_format((float) $c->revenue, 4); ?></strong></td>
                                <td class="num">
                                    <div class="ras-bar-wrap">
                                        <span class="ras-bar blue" style="width:<?php echo number_format($pct, 1); ?>%;"></span>
                                        <span class="ras-bar-pct"><?php echo number_format($pct, 1); ?>%</span>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </section>
            <?php endif; ?>

            <?php if ( ! empty( $by_track ) ): ?>
            <section class="ras-section">
                <h2>🎵 Receita por faixa <small>(top 30)</small></h2>
                <table class="ras-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Faixa</th>
                            <th class="num">Streams</th>
                            <th class="num">Lojas</th>
                            <th class="num">Receita</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $rank = 1; foreach ( $by_track as $t ):
                            $medal = $rank === 1 ? '🥇' : ($rank === 2 ? '🥈' : ($rank === 3 ? '🥉' : $rank));
                        ?>
                            <tr>
                                <td class="num"><?php echo $medal; ?></td>
                                <td><strong><?php echo esc_html($t->track_title ?: '(faixa #' . (int) $t->track_id . ')'); ?></strong></td>
                                <td class="num"><?php echo number_format((int) $t->streams); ?></td>
                                <td class="num"><?php echo (int) $t->n_stores; ?></td>
                                <td class="num"><strong>$<?php echo number_format((float) $t->revenue, 4); ?></strong></td>
                            </tr>
                        <?php $rank++; endforeach; ?>
                    </tbody>
                </table>
            </section>
            <?php endif; ?>

            <?php if ( ! empty( $period_payouts ) ): ?>
            <section class="ras-section">
                <h2>💸 Pagamentos efectuados neste período</h2>
                <table class="ras-table">
                    <thead>
                        <tr>
                            <th>Data</th>
                            <th>Método</th>
                            <th>Referência</th>
                            <th class="num">Valor</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $period_payouts as $pp ): ?>
                            <tr>
                                <td><?php echo esc_html( date('d/m/Y', strtotime($pp->paid_at)) ); ?></td>
                                <td><?php echo esc_html( ucfirst( str_replace('_', ' ', $pp->method) ) ); ?></td>
                                <td><?php if ($pp->reference_number): ?><code><?php echo esc_html($pp->reference_number); ?></code><?php else: ?>—<?php endif; ?></td>
                                <td class="num"><strong>$<?php echo number_format((float) $pp->amount_usd, 2); ?></strong></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </section>
            <?php endif; ?>

            <?php if ( empty($by_store) && empty($by_track) && empty($period_payouts) && $period_revenue <= 0 ): ?>
            <div class="ras-empty">
                <h3>📭 Sem dados neste período</h3>
                <p>Este artista não tem receita registada nem pagamentos efectuados em <strong><?php echo esc_html($period_label); ?></strong>.</p>
                <p>Tenta um período diferente no dropdown em cima.</p>
            </div>
            <?php endif; ?>

            <footer class="ras-footer">
                <div>
                    <strong>1MZ For Artists</strong> · Distribuição musical
                </div>
                <div>
                    Resumo gerado automaticamente em <?php echo esc_html( date_i18n('d/m/Y H:i') ); ?>
                </div>
            </footer>
        </div>

    </div>

    <style>
    /* ───────────────────────────────────────────────────────────────────── */
    /* Toolbar (escondida na impressão)                                     */
    /* ───────────────────────────────────────────────────────────────────── */
    .ras-toolbar {
        background: #fff; border: 1px solid #e5e5e5;
        border-radius: 8px; padding: 10px 14px;
        margin-bottom: 14px;
        display: flex; justify-content: space-between;
        align-items: center; gap: 12px; flex-wrap: wrap;
    }
    .ras-period-form { display: flex; align-items: center; gap: 8px; font-size: 13px; }
    .ras-period-form select { padding: 5px 10px; border-radius: 4px; border: 1px solid #ddd; font-size: 13px; }
    .ras-actions { display: flex; gap: 8px; }

    /* ───────────────────────────────────────────────────────────────────── */
    /* Documento (formato A4-friendly)                                      */
    /* ───────────────────────────────────────────────────────────────────── */
    .ras-document {
        background: #fff;
        border: 1px solid #e5e5e5;
        border-radius: 8px;
        padding: 32px 40px;
        max-width: 900px;
        margin: 0 auto;
        font-family: 'Helvetica Neue', Arial, sans-serif;
        color: #1a1a1a;
    }

    .ras-header {
        display: flex; justify-content: space-between;
        align-items: flex-start;
        padding-bottom: 14px;
        border-bottom: 2px solid #f0b90b;
        margin-bottom: 22px;
    }
    .ras-brand strong { display: block; font-size: 18px; color: #1a1a1a; }
    .ras-brand small { color: #6b7280; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; }
    .ras-date { font-size: 11px; color: #6b7280; }

    .ras-artist-card {
        display: flex; justify-content: space-between;
        align-items: flex-start; gap: 16px;
        margin-bottom: 24px; flex-wrap: wrap;
    }
    .ras-artist-info h1 { margin: 0 0 6px 0; font-size: 26px; color: #1a1a1a; }
    .ras-artist-meta { display: flex; gap: 14px; font-size: 12px; color: #6b7280; flex-wrap: wrap; }
    .ras-period-badge {
        background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
        border: 1px solid #fcd34d;
        padding: 8px 16px; border-radius: 8px;
        font-size: 14px; font-weight: 600; color: #92400e;
    }

    .ras-summary {
        margin-bottom: 24px;
    }
    .ras-summary-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 10px;
    }
    .ras-stat {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-left: 3px solid #ccc;
        border-radius: 6px;
        padding: 10px 14px;
    }
    .ras-stat.green { border-left-color: #10b981; }
    .ras-stat.blue  { border-left-color: #3b82f6; }
    .ras-stat.amber { border-left-color: #f0b90b; }
    .ras-stat.purple { border-left-color: #8b5cf6; }
    .ras-stat .lbl { font-size: 10px; color: #6b7280; text-transform: uppercase; font-weight: 600; }
    .ras-stat .val { font-size: 22px; font-weight: 600; margin: 3px 0 1px; color: #1a1a1a; font-variant-numeric: tabular-nums; }
    .ras-stat .sub { font-size: 10px; color: #888; }

    .ras-section {
        margin-bottom: 22px;
        page-break-inside: avoid;
    }
    .ras-section h2 {
        font-size: 14px; color: #1a1a1a;
        margin: 0 0 10px 0; padding-bottom: 6px;
        border-bottom: 1px solid #e5e7eb;
        font-weight: 600;
    }
    .ras-section h2 small { color: #888; font-weight: 400; font-size: 11px; }

    .ras-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 12px;
    }
    .ras-table th {
        text-align: left;
        padding: 7px 10px;
        background: #f9fafb;
        font-size: 10px;
        text-transform: uppercase;
        color: #6b7280;
        font-weight: 600;
        border-bottom: 1px solid #e5e7eb;
    }
    .ras-table th.num, .ras-table td.num { text-align: right; font-variant-numeric: tabular-nums; }
    .ras-table td {
        padding: 7px 10px;
        border-bottom: 1px solid #f3f4f6;
    }
    .ras-table tr:last-child td { border-bottom: none; }
    .ras-table code { background: #f5f5f5; padding: 1px 5px; border-radius: 3px; font-size: 10px; }

    .ras-bar-wrap {
        position: relative;
        display: inline-block;
        width: 100%;
        background: #f3f4f6;
        height: 16px;
        border-radius: 8px;
        overflow: hidden;
    }
    .ras-bar {
        position: absolute; left: 0; top: 0; bottom: 0;
        background: linear-gradient(90deg, #10b981, #059669);
        min-width: 1px;
    }
    .ras-bar.blue {
        background: linear-gradient(90deg, #3b82f6, #2563eb);
    }
    .ras-bar-pct {
        position: relative; z-index: 2;
        font-size: 10px; color: #1a1a1a;
        text-shadow: 0 0 2px #fff;
        line-height: 16px;
        padding-left: 4px;
    }

    .ras-empty {
        background: #f9fafb;
        border: 1px dashed #ddd;
        border-radius: 8px;
        padding: 30px;
        text-align: center;
        color: #6b7280;
    }
    .ras-empty h3 { margin: 0 0 8px 0; }

    .ras-footer {
        margin-top: 30px;
        padding-top: 14px;
        border-top: 1px solid #e5e7eb;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 10px;
        color: #9ca3af;
    }

    /* ───────────────────────────────────────────────────────────────────── */
    /* Print: limpar tudo o que é admin do WP                              */
    /* ───────────────────────────────────────────────────────────────────── */
    @media print {
        .no-print, #wpadminbar, #adminmenuback, #adminmenuwrap, #adminmenu, #wpfooter,
        .rmbz-ro-sidebar, .rmbz-ro-head, .ras-toolbar { display: none !important; }
        #wpcontent, #wpbody-content, .rmbz-royalties-wrap, .rmbz-ro-layout, .rmbz-ro-main {
            margin: 0 !important; padding: 0 !important; max-width: none !important;
        }
        body { background: #fff !important; }
        .ras-document {
            border: none !important;
            box-shadow: none !important;
            padding: 0 !important;
            max-width: 100% !important;
        }
        .ras-section { page-break-inside: avoid; }
        .ras-summary-grid { page-break-inside: avoid; }
    }
    </style>
    <?php
}
