<?php
// includes/admin/royalties/royalties-commissions-reports.php
// Comissões 1MZ (margem) + Relatórios exportáveis

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


/* ============================================================================
 * COMISSÕES 1MZ — quanto a plataforma ganhou
 * ============================================================================ */
function rmbz_render_royalties_commissions() {
    global $wpdb;
    $t_comm = $wpdb->prefix . 'rmbz_distro_platform_commissions';

    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_comm'") !== $t_comm ) {
        echo '<div class="notice notice-warning"><p>Sem dados de comissão. Faça uma importação primeiro.</p></div>';
        return;
    }

    $totals = $wpdb->get_row(
        "SELECT COUNT(*) AS imports,
                COALESCE(SUM(gross_amount_usd),0)  AS gross,
                COALESCE(SUM(artist_total_usd),0)  AS artists,
                COALESCE(SUM(onemz_margin_usd),0)  AS margin,
                AVG(artist_share_pct)              AS avg_pct
         FROM $t_comm WHERE reverted_at IS NULL"
    );

    $by_month = $wpdb->get_results(
        "SELECT reporting_period,
                COUNT(*) AS n,
                SUM(gross_amount_usd) AS gross,
                SUM(artist_total_usd) AS artists,
                SUM(onemz_margin_usd) AS margin
         FROM $t_comm WHERE reverted_at IS NULL
         GROUP BY reporting_period ORDER BY reporting_period DESC LIMIT 24"
    );

    $by_distrib = $wpdb->get_results(
        "SELECT distributor_name,
                COUNT(*) AS n,
                SUM(gross_amount_usd) AS gross,
                SUM(artist_total_usd) AS artists,
                SUM(onemz_margin_usd) AS margin
         FROM $t_comm WHERE reverted_at IS NULL
         GROUP BY distributor_name ORDER BY margin DESC"
    );

    $max_margin_month = 0;
    foreach ( $by_month as $m ) $max_margin_month = max($max_margin_month, (float)$m->margin);
    ?>

    <div class="roc-kpis">
        <div class="roc-kpi gray">
            <div class="lbl">Bruto acumulado</div>
            <div class="val">$<?php echo number_format($totals->gross ?? 0, 2); ?></div>
            <div class="sub">todas as importações</div>
        </div>
        <div class="roc-kpi green">
            <div class="lbl">Pago a artistas</div>
            <div class="val">$<?php echo number_format($totals->artists ?? 0, 2); ?></div>
            <div class="sub">~<?php echo number_format($totals->avg_pct ?? 0, 0); ?>% médio</div>
        </div>
        <div class="roc-kpi blue">
            <div class="lbl">💰 Margem 1MZ</div>
            <div class="val">$<?php echo number_format($totals->margin ?? 0, 2); ?></div>
            <div class="sub">receita da plataforma</div>
        </div>
        <div class="roc-kpi purple">
            <div class="lbl">Importações</div>
            <div class="val"><?php echo (int) ($totals->imports ?? 0); ?></div>
            <div class="sub">processadas</div>
        </div>
    </div>

    <div class="roc-card">
        <div class="roc-card-head">
            <strong>📅 Margem por mês (últimos 24)</strong>
            <span>período · margem 1MZ · pago artistas · bruto</span>
        </div>
        <?php if ( empty($by_month) ): ?>
            <p style="color:#888;">Sem dados.</p>
        <?php else: ?>
            <div class="roc-month-list">
                <?php foreach ( array_reverse($by_month) as $m ):
                    $pct = $max_margin_month > 0 ? ((float)$m->margin / $max_margin_month * 100) : 0;
                ?>
                    <div class="roc-month">
                        <div class="period"><?php echo esc_html($m->reporting_period); ?></div>
                        <div class="bar">
                            <div class="fill" style="width: <?php echo number_format($pct, 1); ?>%;"></div>
                        </div>
                        <div class="vals">
                            <strong>$<?php echo number_format($m->margin, 2); ?></strong>
                            <small>· $<?php echo number_format($m->artists, 2); ?> art · $<?php echo number_format($m->gross, 2); ?> bruto</small>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="roc-card">
        <div class="roc-card-head">
            <strong>🏢 Margem por distribuidora</strong>
            <span>ranking de rentabilidade</span>
        </div>
        <?php if ( empty($by_distrib) ): ?>
            <p style="color:#888;">Sem dados.</p>
        <?php else: ?>
            <table class="roc-table">
                <thead>
                    <tr>
                        <th>Distribuidora</th>
                        <th style="text-align:right;">Importações</th>
                        <th style="text-align:right;">Bruto</th>
                        <th style="text-align:right;">Artistas</th>
                        <th style="text-align:right;">💰 Margem 1MZ</th>
                        <th style="text-align:right;">% efectiva</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $by_distrib as $d ):
                        $eff_pct = (float)$d->gross > 0 ? ((float)$d->margin / (float)$d->gross * 100) : 0;
                    ?>
                        <tr>
                            <td><strong><?php echo esc_html($d->distributor_name); ?></strong></td>
                            <td style="text-align:right;"><?php echo (int) $d->n; ?></td>
                            <td style="text-align:right;">$<?php echo number_format($d->gross, 2); ?></td>
                            <td style="text-align:right; color:#27ae60;">$<?php echo number_format($d->artists, 2); ?></td>
                            <td style="text-align:right;"><strong style="color:var(--wp-admin-theme-color, #2271b1);">$<?php echo number_format($d->margin, 2); ?></strong></td>
                            <td style="text-align:right;"><?php echo number_format($eff_pct, 1); ?>%</td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <style>
    .roc-kpis { display:grid; grid-template-columns:repeat(auto-fit, minmax(180px, 1fr)); gap:10px; margin-bottom:16px; }
    .roc-kpi { background:#fff; border:1px solid #e5e5e5; border-left:3px solid #ccc; border-radius:8px; padding:12px 16px; }
    .roc-kpi.gray   { border-left-color:#888; }
    .roc-kpi.green  { border-left-color:#2ecc71; }
    .roc-kpi.blue   { border-left-color:#3498db; }
    .roc-kpi.purple { border-left-color:#9b59b6; }
    .roc-kpi .lbl { font-size:10px; color:#888; text-transform:uppercase; letter-spacing:0.3px; font-weight:600; }
    .roc-kpi .val { font-size:22px; font-weight:500; color:#222; margin:4px 0 2px 0; }
    .roc-kpi.blue .val { color:var(--wp-admin-theme-color, #2271b1); }
    .roc-kpi .sub { font-size:11px; color:#666; }
    .roc-card { background:#fff; border:1px solid #e5e5e5; border-radius:8px; padding:14px 16px; margin-bottom:12px; }
    .roc-card-head { display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; padding-bottom:8px; border-bottom:1px solid #f0f0f0; }
    .roc-card-head strong { font-size:13px; color:#222; }
    .roc-card-head span { font-size:11px; color:#888; }
    .roc-month-list { display:flex; flex-direction:column; gap:6px; }
    .roc-month { display:grid; grid-template-columns: 90px 1fr 280px; gap:10px; align-items:center; font-size:12px; }
    .roc-month .period { font-family:monospace; font-size:11px; color:#666; }
    .roc-month .bar { height:18px; background:#f0f0f0; border-radius:9px; overflow:hidden; }
    .roc-month .bar .fill { height:100%; background:#3498db; transition:width 0.4s; }
    .roc-month .vals { font-size:11px; text-align:right; color:#444; }
    .roc-month .vals strong { color:var(--wp-admin-theme-color, #2271b1); }
    .roc-month .vals small { color:#888; }
    .roc-table { width:100%; border-collapse:collapse; font-size:12px; }
    .roc-table th { background:#fafafa; padding:8px; text-align:left; font-size:10px; text-transform:uppercase; color:#666; font-weight:600; border-bottom:1px solid #e5e5e5; }
    .roc-table td { padding:10px 8px; border-bottom:1px solid #f0f0f0; }
    .roc-table tr:last-child td { border-bottom:none; }
    </style>
    <?php
}


/* ============================================================================
 * RELATÓRIOS — exportações CSV
 * ============================================================================ */
function rmbz_render_royalties_reports() {
    ?>
    <div class="ror-grid">
        <div class="ror-card">
            <div class="icon">📒</div>
            <h3>Extracto financeiro completo</h3>
            <p>Todas as transacções (royalties, ajustes, pagamentos) com detalhe por linha. Para auditoria fiscal.</p>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="rmbz_export_report">
                <input type="hidden" name="report_type" value="ledger_full">
                <?php wp_nonce_field('rmbz_export_report_nonce'); ?>
                <select name="period" style="width:100%; margin-bottom:8px; padding:6px;">
                    <option value="all">Tudo</option>
                    <option value="ytd">Ano actual</option>
                    <option value="last_year"><?php echo (int) date('Y') - 1; ?></option>
                    <option value="last_month">Mês anterior</option>
                </select>
                <button type="submit" class="button button-primary" style="width:100%;">📥 Exportar CSV</button>
            </form>
        </div>

        <div class="ror-card">
            <div class="icon">👤</div>
            <h3>Extracto por artista</h3>
            <p>Movimentos de um artista específico (créditos, débitos, saldo). Útil para enviar a cada artista.</p>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="rmbz_export_report">
                <input type="hidden" name="report_type" value="artist_statement">
                <?php wp_nonce_field('rmbz_export_report_nonce'); ?>
                <input type="text" name="artist_phone" required placeholder="Telemóvel +258..." style="width:100%; margin-bottom:8px; padding:6px;">
                <button type="submit" class="button button-primary" style="width:100%;">📥 Exportar CSV</button>
            </form>
        </div>

        <div class="ror-card">
            <div class="icon">🏦</div>
            <h3>Receita 1MZ (comissões)</h3>
            <p>Resumo executivo da margem da plataforma. Quanto a 1MZ ganhou por mês e por distribuidora.</p>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="rmbz_export_report">
                <input type="hidden" name="report_type" value="commissions">
                <?php wp_nonce_field('rmbz_export_report_nonce'); ?>
                <select name="group_by" style="width:100%; margin-bottom:8px; padding:6px;">
                    <option value="month">Por mês</option>
                    <option value="distributor">Por distribuidora</option>
                    <option value="both">Mês + distribuidora</option>
                </select>
                <button type="submit" class="button button-primary" style="width:100%;">📥 Exportar CSV</button>
            </form>
        </div>

        <div class="ror-card">
            <div class="icon">💸</div>
            <h3>Pagamentos efectuados</h3>
            <p>Lista de todos os saques pagos aos artistas (M-Pesa, banco, etc.) com referências.</p>
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="rmbz_export_report">
                <input type="hidden" name="report_type" value="payouts">
                <?php wp_nonce_field('rmbz_export_report_nonce'); ?>
                <select name="period" style="width:100%; margin-bottom:8px; padding:6px;">
                    <option value="all">Tudo</option>
                    <option value="ytd">Ano actual</option>
                    <option value="last_month">Mês anterior</option>
                </select>
                <button type="submit" class="button button-primary" style="width:100%;">📥 Exportar CSV</button>
            </form>
        </div>
    </div>

    <style>
    .ror-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(280px, 1fr)); gap:14px; }
    .ror-card { background:#fff; border:1px solid #e5e5e5; border-radius:8px; padding:18px; }
    .ror-card .icon { font-size:32px; margin-bottom:8px; }
    .ror-card h3 { margin:0 0 6px 0; font-size:14px; font-weight:500; color:#222; }
    .ror-card p { margin:0 0 12px 0; font-size:12px; color:#666; line-height:1.5; }
    </style>
    <?php
}


/* ============================================================================
 * HANDLER — exportar CSV
 * ============================================================================ */
function rmbz_handle_export_report() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');
    check_admin_referer('rmbz_export_report_nonce');

    global $wpdb;
    $type = sanitize_key($_POST['report_type'] ?? '');

    nocache_headers();
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="1mz_' . $type . '_' . date('Ymd_His') . '.csv"');
    echo "\xEF\xBB\xBF"; // BOM UTF-8 (para Excel ler acentos)
    $out = fopen('php://output', 'w');

    if ( $type === 'ledger_full' ) {
        $period = sanitize_key($_POST['period'] ?? 'all');
        $where = ['1=1'];
        if ( $period === 'ytd' )       $where[] = "YEAR(created_at) = " . (int) date('Y');
        if ( $period === 'last_year' ) $where[] = "YEAR(created_at) = " . ((int) date('Y') - 1);
        if ( $period === 'last_month') $where[] = "DATE_FORMAT(created_at, '%Y-%m') = '" . date('Y-m', strtotime('-1 month')) . "'";
        $where_sql = implode(' AND ', $where);
        fputcsv($out, ['Data','Artista','Tipo','Valor USD','Moeda Original','Valor Original','Período','Fonte','Descrição','Status']);
        $rows = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}rmbz_distro_ledger WHERE $where_sql ORDER BY created_at DESC");
        foreach ( $rows as $r ) {
            fputcsv($out, [
                $r->created_at, $r->artist_telemovel, $r->type, $r->amount,
                $r->original_currency, $r->original_amount, $r->reporting_period,
                $r->source_name, $r->description, ! empty($r->reverted_at) ? 'reverted' : 'active',
            ]);
        }
    } elseif ( $type === 'artist_statement' ) {
        $phone = preg_replace('/[^0-9+]/', '', (string) ($_POST['artist_phone'] ?? ''));
        fputcsv($out, ['Data','Tipo','Valor USD','Período','Descrição','Status']);
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}rmbz_distro_ledger WHERE artist_telemovel = %s ORDER BY created_at DESC",
            $phone
        ) );
        foreach ( $rows as $r ) {
            fputcsv($out, [
                $r->created_at, $r->type, $r->amount, $r->reporting_period,
                $r->description, ! empty($r->reverted_at) ? 'reverted' : 'active',
            ]);
        }
    } elseif ( $type === 'commissions' ) {
        $group = sanitize_key($_POST['group_by'] ?? 'month');
        if ( $group === 'distributor' ) {
            fputcsv($out, ['Distribuidora','Importações','Bruto USD','Pago Artistas','Margem 1MZ','% Efectiva']);
            $rows = $wpdb->get_results(
                "SELECT distributor_name, COUNT(*) AS n,
                        SUM(gross_amount_usd) AS gross, SUM(artist_total_usd) AS artists, SUM(onemz_margin_usd) AS margin
                 FROM {$wpdb->prefix}rmbz_distro_platform_commissions
                 WHERE reverted_at IS NULL GROUP BY distributor_name ORDER BY margin DESC"
            );
            foreach ( $rows as $r ) {
                $pct = (float)$r->gross > 0 ? ((float)$r->margin / (float)$r->gross * 100) : 0;
                fputcsv($out, [$r->distributor_name, $r->n, $r->gross, $r->artists, $r->margin, number_format($pct, 2)]);
            }
        } elseif ( $group === 'both' ) {
            fputcsv($out, ['Período','Distribuidora','Importações','Bruto USD','Pago Artistas','Margem 1MZ']);
            $rows = $wpdb->get_results(
                "SELECT reporting_period, distributor_name, COUNT(*) AS n,
                        SUM(gross_amount_usd) AS gross, SUM(artist_total_usd) AS artists, SUM(onemz_margin_usd) AS margin
                 FROM {$wpdb->prefix}rmbz_distro_platform_commissions
                 WHERE reverted_at IS NULL GROUP BY reporting_period, distributor_name ORDER BY reporting_period DESC"
            );
            foreach ( $rows as $r ) {
                fputcsv($out, [$r->reporting_period, $r->distributor_name, $r->n, $r->gross, $r->artists, $r->margin]);
            }
        } else {
            fputcsv($out, ['Período','Importações','Bruto USD','Pago Artistas','Margem 1MZ']);
            $rows = $wpdb->get_results(
                "SELECT reporting_period, COUNT(*) AS n,
                        SUM(gross_amount_usd) AS gross, SUM(artist_total_usd) AS artists, SUM(onemz_margin_usd) AS margin
                 FROM {$wpdb->prefix}rmbz_distro_platform_commissions
                 WHERE reverted_at IS NULL GROUP BY reporting_period ORDER BY reporting_period DESC"
            );
            foreach ( $rows as $r ) {
                fputcsv($out, [$r->reporting_period, $r->n, $r->gross, $r->artists, $r->margin]);
            }
        }
    } elseif ( $type === 'payouts' ) {
        $period = sanitize_key($_POST['period'] ?? 'all');
        $where = ['1=1'];
        if ( $period === 'ytd' )        $where[] = "YEAR(paid_at) = " . (int) date('Y');
        if ( $period === 'last_month' ) $where[] = "DATE_FORMAT(paid_at, '%Y-%m') = '" . date('Y-m', strtotime('-1 month')) . "'";
        $where_sql = implode(' AND ', $where);
        fputcsv($out, ['Data','Artista','Valor USD','Método','Referência','Status','Pago Por','Notas']);
        $rows = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}rmbz_distro_payouts WHERE $where_sql ORDER BY paid_at DESC");
        foreach ( $rows as $r ) {
            fputcsv($out, [$r->paid_at, $r->artist_telemovel, $r->amount_usd, $r->method, $r->reference_number, $r->status, $r->paid_by, $r->notes]);
        }
    }

    fclose($out);
    exit;
}
add_action('admin_post_rmbz_export_report', 'rmbz_handle_export_report');
