<?php
// includes/admin/royalties/royalties-payouts.php
// Pagamentos aos artistas (M-Pesa, banco, manual, etc.)

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



/**
 * [FEAT 1.6.23] Página de Levantamentos modernizada.
 *
 * Mantém compatibilidade total com `rmbz_handle_payout_create` (não tocada).
 * Acrescenta: KPIs adicionais, sparkline mensal, top 5 artistas, pesquisa
 * instantânea JS, atalhos de teclado, ícones por método.
 */
function rmbz_render_royalties_payouts() {
    global $wpdb;
    $t_payouts = $wpdb->prefix . 'rmbz_distro_payouts';
    $t_stats   = $wpdb->prefix . 'rmbz_distro_stats';
    $t_wallets = $wpdb->prefix . 'rmbz_wallets';

    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_payouts'") !== $t_payouts ) {
        echo '<div class="notice notice-warning"><p>Tabela de pagamentos ainda não existe. Recarregue a página.</p></div>';
        return;
    }

    if ( isset($_GET['pay_done']) ) {
        echo '<div class="notice notice-success is-dismissible"><p>✓ Pagamento registado com sucesso.</p></div>';
    }
    if ( isset($_GET['pay_error']) ) {
        echo '<div class="notice notice-error"><p>Erro: ' . esc_html(urldecode($_GET['pay_error'])) . '</p></div>';
    }

    // ── KPIs principais ─────────────────────────────────────────────────────
    $total_paid    = (float) $wpdb->get_var("SELECT COALESCE(SUM(amount_usd),0) FROM $t_payouts WHERE status = 'completed' AND reverted_at IS NULL");
    $total_pending = (float) $wpdb->get_var("SELECT COALESCE(SUM(amount_usd),0) FROM $t_payouts WHERE status = 'pending'");
    $count_paid    = (int)   $wpdb->get_var("SELECT COUNT(*) FROM $t_payouts WHERE status = 'completed' AND reverted_at IS NULL");

    // [FEAT 1.6.23] KPIs adicionais
    $month_start = date('Y-m-01');
    $month_paid = (float) $wpdb->get_var( $wpdb->prepare(
        "SELECT COALESCE(SUM(amount_usd),0) FROM $t_payouts WHERE status = 'completed' AND reverted_at IS NULL AND paid_at >= %s",
        $month_start
    ));
    $month_count = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM $t_payouts WHERE status = 'completed' AND reverted_at IS NULL AND paid_at >= %s",
        $month_start
    ));
    $unique_artists = (int) $wpdb->get_var("SELECT COUNT(DISTINCT artist_telemovel) FROM $t_payouts WHERE status = 'completed' AND reverted_at IS NULL");

    // [FEAT 1.6.23] Sparkline — pagamentos por mês nos últimos 12 meses
    $spark_rows = $wpdb->get_results(
        "SELECT DATE_FORMAT(paid_at, '%Y-%m') AS ym, SUM(amount_usd) AS total
           FROM $t_payouts
          WHERE status = 'completed' AND reverted_at IS NULL
            AND paid_at >= DATE_SUB(CURRENT_DATE(), INTERVAL 12 MONTH)
          GROUP BY ym ORDER BY ym ASC"
    );
    $spark_data = [];
    $spark_max = 0;
    for ( $i = 11; $i >= 0; $i-- ) {
        $ym = date('Y-m', strtotime("-{$i} months"));
        $spark_data[$ym] = 0.0;
    }
    foreach ( $spark_rows as $sr ) {
        if ( isset($spark_data[$sr->ym]) ) {
            $spark_data[$sr->ym] = (float) $sr->total;
            if ( (float) $sr->total > $spark_max ) $spark_max = (float) $sr->total;
        }
    }

    // [FEAT 1.6.23] Top 5 artistas mais pagos
    $top_artists = $wpdb->get_results(
        "SELECT p.artist_telemovel,
                w.user_nome,
                SUM(p.amount_usd) AS total,
                COUNT(*) AS n_payments
           FROM $t_payouts p
      LEFT JOIN $t_wallets w ON w.user_telemovel = p.artist_telemovel
          WHERE p.status = 'completed' AND p.reverted_at IS NULL
          GROUP BY p.artist_telemovel
          ORDER BY total DESC
          LIMIT 5"
    );

    // ── Filtros ─────────────────────────────────────────────────────────────
    $f_artist = isset($_GET['p_artist']) ? sanitize_text_field($_GET['p_artist']) : '';
    $f_method = isset($_GET['p_method']) ? sanitize_text_field($_GET['p_method']) : '';
    $f_status = isset($_GET['p_status']) ? sanitize_text_field($_GET['p_status']) : '';

    $where = ['1=1'];
    $params = [];
    if ( $f_artist ) {
        // Pesquisa também no nome do artista — não só telemóvel
        $where[] = '(artist_telemovel LIKE %s OR artist_telemovel IN (SELECT user_telemovel FROM '.$t_wallets.' WHERE user_nome LIKE %s))';
        $params[] = '%' . $wpdb->esc_like($f_artist) . '%';
        $params[] = '%' . $wpdb->esc_like($f_artist) . '%';
    }
    if ( $f_method ) { $where[] = 'method = %s'; $params[] = $f_method; }
    if ( $f_status ) { $where[] = 'status = %s'; $params[] = $f_status; }
    $where_sql = implode(' AND ', $where);
    $sql = "SELECT * FROM $t_payouts WHERE $where_sql ORDER BY paid_at DESC LIMIT 200";
    $payouts = $params ? $wpdb->get_results( $wpdb->prepare($sql, $params) ) : $wpdb->get_results($sql);

    // Pre-carregar nomes (evita N+1 queries)
    $tels = [];
    foreach ( $payouts as $p ) $tels[ $p->artist_telemovel ] = true;
    $name_map = [];
    if ( ! empty( $tels ) ) {
        $tel_list = array_keys($tels);
        $placeholders = implode(',', array_fill(0, count($tel_list), '%s'));
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT user_telemovel, user_nome FROM $t_wallets WHERE user_telemovel IN ($placeholders)",
            $tel_list
        ), OBJECT_K );
        foreach ( $rows as $tel => $row ) $name_map[$tel] = $row->user_nome;
    }

    // ── Ícones por método ───────────────────────────────────────────────────
    $method_icons = [
        'mpesa'         => '📱',
        'emola'         => '🟢',
        'bank_transfer' => '🏦',
        'cash'          => '💵',
        'paypal'        => '🅿️',
    ];
    $method_labels = [
        'mpesa'         => 'M-Pesa',
        'emola'         => 'e-Mola',
        'bank_transfer' => 'Banco',
        'cash'          => 'Dinheiro',
        'paypal'        => 'PayPal',
    ];
    ?>

    <div class="rop-page">

        <?php // ── KPIs ─────────────────────────────────────────────────── ?>
        <div class="rop-kpis">
            <div class="rop-kpi green">
                <div class="lbl">💰 Total pago</div>
                <div class="val">$<?php echo number_format($total_paid, 2); ?></div>
                <div class="sub"><?php echo $count_paid; ?> pagamento(s) · acumulado</div>
            </div>
            <div class="rop-kpi blue-light">
                <div class="lbl">📅 Este mês</div>
                <div class="val">$<?php echo number_format($month_paid, 2); ?></div>
                <div class="sub"><?php echo $month_count; ?> pagamento(s) em <?php echo esc_html( date('M/Y') ); ?></div>
            </div>
            <div class="rop-kpi amber">
                <div class="lbl">⏳ Pendente</div>
                <div class="val">$<?php echo number_format($total_pending, 2); ?></div>
                <div class="sub">aguarda confirmação</div>
            </div>
            <div class="rop-kpi purple">
                <div class="lbl">👥 Artistas únicos</div>
                <div class="val"><?php echo $unique_artists; ?></div>
                <div class="sub">já receberam pagamento</div>
            </div>
            <div class="rop-kpi action" onclick="document.getElementById('rop-pay-form').style.display='block'; document.querySelector('#rop-pay-form input[name=artist_phone]').focus();">
                <div class="lbl">➕ Novo pagamento</div>
                <div class="val" style="font-size:14px; line-height:1.3;">Registar saque a artista</div>
                <div class="sub">atalho: <kbd>N</kbd></div>
            </div>
        </div>

        <?php // ── Sparkline + Top 5 ────────────────────────────────────── ?>
        <?php if ( $spark_max > 0 ): ?>
        <div class="rop-bottom-row">
            <div class="rop-spark-card">
                <div class="rop-spark-head">
                    <strong>📈 Tendência mensal · últimos 12 meses</strong>
                    <span class="rop-spark-stat">pico $<?php echo number_format($spark_max, 0); ?></span>
                </div>
                <svg class="rop-spark" viewBox="0 0 600 80" preserveAspectRatio="none">
                    <?php
                    $w = 600; $h = 80; $pad = 4;
                    $n = count($spark_data);
                    $step = ($w - 2*$pad) / max(1, $n - 1);
                    $points = [];
                    $i = 0;
                    foreach ( $spark_data as $ym => $v ) {
                        $x = $pad + $i * $step;
                        $y = $h - $pad - ( $spark_max > 0 ? ($v / $spark_max) * ($h - 2*$pad) : 0 );
                        $points[] = "$x,$y";
                        $i++;
                    }
                    $polyline = implode(' ', $points);
                    // Área (mesma linha + fechar até base)
                    $area = $polyline . " {$points[count($points)-1]} " . ($w - $pad) . ",{$h} " . $pad . ",{$h}";
                    ?>
                    <polyline points="<?php echo esc_attr( $pad . ',' . $h . ' ' . $polyline . ' ' . ($w-$pad) . ',' . $h ); ?>" fill="rgba(46,204,113,0.15)" stroke="none"/>
                    <polyline points="<?php echo esc_attr($polyline); ?>" fill="none" stroke="#10b981" stroke-width="2"/>
                    <?php
                    // Marcadores nos meses
                    $j = 0;
                    foreach ( $spark_data as $ym => $v ) {
                        $x = $pad + $j * $step;
                        $y = $h - $pad - ( $spark_max > 0 ? ($v / $spark_max) * ($h - 2*$pad) : 0 );
                        $title = $ym . ' · $' . number_format($v, 2);
                        echo '<circle cx="'.$x.'" cy="'.$y.'" r="3" fill="#10b981"><title>'.esc_html($title).'</title></circle>';
                        $j++;
                    }
                    ?>
                </svg>
                <div class="rop-spark-axis">
                    <?php
                    // Labels: primeiro, meio e último
                    $keys_sp = array_keys($spark_data);
                    $first = $keys_sp[0] ?? '';
                    $mid = $keys_sp[(int)(count($keys_sp)/2)] ?? '';
                    $last = end($keys_sp);
                    ?>
                    <span><?php echo esc_html($first); ?></span>
                    <span><?php echo esc_html($mid); ?></span>
                    <span><?php echo esc_html($last); ?></span>
                </div>
            </div>

            <?php if ( ! empty( $top_artists ) ): ?>
            <div class="rop-top-card">
                <div class="rop-top-head">
                    <strong>🏆 Top 5 artistas mais pagos</strong>
                </div>
                <div class="rop-top-list">
                    <?php $rank = 1; foreach ( $top_artists as $ta ):
                        $medal = $rank === 1 ? '🥇' : ($rank === 2 ? '🥈' : ($rank === 3 ? '🥉' : '  '));
                        $summary_url = add_query_arg([
                            'page'   => 'rmbz-admin-distribution',
                            'tab'    => 'royalties',
                            'rsub'   => 'artist_summary',
                            'artist' => $ta->artist_telemovel,
                        ], admin_url('admin.php'));
                    ?>
                        <a class="rop-top-row" href="<?php echo esc_url($summary_url); ?>" title="Ver resumo financeiro mensal">
                            <span class="rop-top-medal"><?php echo $medal; ?></span>
                            <span class="rop-top-name">
                                <strong><?php echo esc_html($ta->user_nome ?: $ta->artist_telemovel); ?></strong>
                                <small><?php echo (int)$ta->n_payments; ?> pagamento(s)</small>
                            </span>
                            <span class="rop-top-amount">$<?php echo number_format( (float) $ta->total, 2); ?></span>
                        </a>
                    <?php $rank++; endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php // ── Formulário novo pagamento (mantido igual) ──────────────── ?>
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="rop-pay-form" style="display:none; background:#fff; border:1px solid #e5e5e5; border-radius:8px; padding:16px; margin-bottom:16px;">
            <h3 style="margin:0 0 12px 0;">💸 Registar pagamento</h3>
            <input type="hidden" name="action" value="rmbz_payout_create">
            <?php wp_nonce_field('rmbz_payout_create_nonce'); ?>
            <div style="display:grid; grid-template-columns: 1fr 1fr 1fr; gap:12px; margin-bottom:12px;">
                <div>
                    <label style="display:block; font-size:11px; font-weight:600; color:#666; margin-bottom:4px;">Telemóvel artista</label>
                    <input type="text" name="artist_phone" required placeholder="+258..." style="width:100%; padding:6px;">
                </div>
                <div>
                    <label style="display:block; font-size:11px; font-weight:600; color:#666; margin-bottom:4px;">Valor USD</label>
                    <input type="number" name="amount_usd" step="0.01" required placeholder="100.00" style="width:100%; padding:6px;">
                </div>
                <div>
                    <label style="display:block; font-size:11px; font-weight:600; color:#666; margin-bottom:4px;">Método</label>
                    <select name="method" required style="width:100%; padding:6px;">
                        <option value="mpesa">📱 M-Pesa</option>
                        <option value="emola">🟢 e-Mola</option>
                        <option value="bank_transfer">🏦 Banco</option>
                        <option value="cash">💵 Dinheiro</option>
                        <option value="paypal">🅿️ PayPal</option>
                    </select>
                </div>
                <div>
                    <label style="display:block; font-size:11px; font-weight:600; color:#666; margin-bottom:4px;">Referência</label>
                    <input type="text" name="reference_number" placeholder="ID transacção" style="width:100%; padding:6px;">
                </div>
                <div>
                    <label style="display:block; font-size:11px; font-weight:600; color:#666; margin-bottom:4px;">Status</label>
                    <select name="status" required style="width:100%; padding:6px;">
                        <option value="completed">✓ Concluído</option>
                        <option value="pending">⏳ Pendente</option>
                        <option value="failed">✗ Falhado</option>
                    </select>
                </div>
                <div>
                    <label style="display:block; font-size:11px; font-weight:600; color:#666; margin-bottom:4px;">Pago em</label>
                    <input type="datetime-local" name="paid_at" required value="<?php echo esc_attr( date('Y-m-d\TH:i') ); ?>" style="width:100%; padding:6px;">
                </div>
            </div>
            <div style="display:flex; gap:8px;">
                <button type="submit" class="button button-primary">💾 Registar pagamento</button>
                <button type="button" class="button" onclick="document.getElementById('rop-pay-form').style.display='none';">Cancelar</button>
            </div>
        </form>

        <?php // ── Filtros ──────────────────────────────────────────────── ?>
        <form method="get" class="rop-filters" id="rop-filters-form">
            <input type="hidden" name="page" value="rmbz-admin-distribution">
            <input type="hidden" name="tab" value="royalties">
            <input type="hidden" name="rsub" value="payouts">
            <div class="fg">
                <label>🔍 Pesquisa <small>(nome ou telemóvel)</small></label>
                <input type="text" name="p_artist" id="rop-search" value="<?php echo esc_attr($f_artist); ?>" placeholder="Nome do artista ou +258...">
            </div>
            <div class="fg">
                <label>Método</label>
                <select name="p_method">
                    <option value="">Todos</option>
                    <?php foreach ( $method_labels as $mk => $ml ): ?>
                        <option value="<?php echo esc_attr($mk); ?>" <?php selected($f_method, $mk); ?>><?php echo esc_html(($method_icons[$mk] ?? '') . ' ' . $ml); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="fg">
                <label>Status</label>
                <select name="p_status">
                    <option value="">Todos</option>
                    <option value="completed" <?php selected($f_status, 'completed'); ?>>✓ Concluído</option>
                    <option value="pending" <?php selected($f_status, 'pending'); ?>>⏳ Pendente</option>
                    <option value="failed" <?php selected($f_status, 'failed'); ?>>✗ Falhado</option>
                </select>
            </div>
            <div class="fa">
                <button type="submit" class="button button-primary">🔍 Filtrar</button>
                <?php if ( $f_artist || $f_method || $f_status ): ?>
                    <a href="<?php echo esc_url( admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=payouts') ); ?>" class="button">✗ Limpar</a>
                <?php endif; ?>
            </div>
        </form>

        <?php // ── Tabela ───────────────────────────────────────────────── ?>
        <div class="rop-table-wrap">
            <table class="rop-table">
                <thead>
                    <tr>
                        <th>Data</th>
                        <th>Artista</th>
                        <th>Método</th>
                        <th>Referência</th>
                        <th style="text-align:right;">Valor USD</th>
                        <th>Status</th>
                        <th>Pago por</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ( empty($payouts) ): ?>
                        <tr><td colspan="7" class="rop-empty">
                            <?php if ( $f_artist || $f_method || $f_status ): ?>
                                Nenhum pagamento bate com os filtros activos.
                            <?php else: ?>
                                Nenhum pagamento registado ainda. Carrega "Novo pagamento" para começar.
                            <?php endif; ?>
                        </td></tr>
                    <?php else: foreach ( $payouts as $p ):
                        $artist_name = $name_map[ $p->artist_telemovel ] ?? '';
                        $micon = $method_icons[ $p->method ] ?? '💳';
                        $mlabel = $method_labels[ $p->method ] ?? $p->method;
                    ?>
                        <tr class="<?php echo $p->reverted_at ? 'reverted' : ''; ?>">
                            <td>
                                <?php echo esc_html(date('d/m/Y', strtotime($p->paid_at))); ?>
                                <div class="muted"><?php echo esc_html(date('H:i', strtotime($p->paid_at))); ?></div>
                            </td>
                            <td>
                                <?php
                                $row_summary_url = add_query_arg([
                                    'page'   => 'rmbz-admin-distribution',
                                    'tab'    => 'royalties',
                                    'rsub'   => 'artist_summary',
                                    'artist' => $p->artist_telemovel,
                                    'period' => date('Y-m', strtotime($p->paid_at)),
                                ], admin_url('admin.php'));
                                ?>
                                <a href="<?php echo esc_url($row_summary_url); ?>" class="rop-artist-link" title="Ver resumo financeiro deste mês">
                                    <strong><?php echo esc_html($artist_name ?: '—'); ?></strong>
                                </a>
                                <div class="muted"><?php echo esc_html($p->artist_telemovel); ?></div>
                            </td>
                            <td>
                                <span class="method-pill method-<?php echo esc_attr($p->method); ?>">
                                    <?php echo $micon; ?> <?php echo esc_html($mlabel); ?>
                                </span>
                            </td>
                            <td><?php if ($p->reference_number): ?><code><?php echo esc_html($p->reference_number); ?></code><?php else: ?><span class="muted">—</span><?php endif; ?></td>
                            <td style="text-align:right;">
                                <strong>$<?php echo number_format($p->amount_usd, 2); ?></strong>
                            </td>
                            <td>
                                <?php
                                $status_pills = [
                                    'completed' => '✓ Concluído',
                                    'pending'   => '⏳ Pendente',
                                    'failed'    => '✗ Falhado',
                                ];
                                $label = $status_pills[$p->status] ?? $p->status;
                                ?>
                                <span class="status-pill status-<?php echo esc_attr($p->status); ?>"><?php echo esc_html($label); ?></span>
                                <?php if ( $p->reverted_at ): ?> <small style="color:#c00; display:block;">⚠ revertido</small><?php endif; ?>
                            </td>
                            <td><small><?php echo esc_html($p->paid_by ?: '—'); ?></small></td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
            <?php if ( count($payouts) >= 200 ): ?>
                <div class="rop-table-foot">
                    <small>⚠ Mostrando os 200 mais recentes. Use filtros para refinar.</small>
                </div>
            <?php endif; ?>
        </div>

        <div class="rop-shortcuts">
            <span><kbd>N</kbd> Novo pagamento</span>
            <span><kbd>/</kbd> Focar pesquisa</span>
            <span><kbd>Esc</kbd> Fechar formulário</span>
        </div>
    </div>

    <style>
    .rop-page { font-family: -apple-system, system-ui, sans-serif; }
    .rop-kpis {
        display:grid;
        grid-template-columns:repeat(auto-fit, minmax(180px, 1fr));
        gap:10px;
        margin-bottom:16px;
    }
    .rop-kpi {
        background:#fff; border:1px solid #e5e5e5;
        border-left:3px solid #ccc; border-radius:8px;
        padding:12px 16px;
        transition: all 0.15s;
    }
    .rop-kpi.green { border-left-color:#10b981; }
    .rop-kpi.amber { border-left-color:#f0b90b; }
    .rop-kpi.blue-light { border-left-color:#3b82f6; }
    .rop-kpi.purple { border-left-color:#8b5cf6; }
    .rop-kpi.action {
        border-left-color:#f0b90b;
        background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
        cursor:pointer;
    }
    .rop-kpi.action:hover { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); transform: translateY(-1px); }
    .rop-kpi .lbl { font-size:10px; color:#888; text-transform:uppercase; letter-spacing:0.3px; font-weight:600; }
    .rop-kpi .val { font-size:22px; font-weight:600; color:#222; margin:4px 0 2px 0; font-variant-numeric: tabular-nums; }
    .rop-kpi .sub { font-size:11px; color:#666; }

    .rop-bottom-row {
        display: grid;
        grid-template-columns: 1.5fr 1fr;
        gap: 12px;
        margin-bottom: 16px;
    }
    @media (max-width: 900px) { .rop-bottom-row { grid-template-columns: 1fr; } }

    .rop-spark-card, .rop-top-card {
        background:#fff; border:1px solid #e5e5e5;
        border-radius:8px; padding:14px 16px;
    }
    .rop-spark-head, .rop-top-head {
        display: flex; justify-content: space-between;
        align-items: center; margin-bottom: 8px;
    }
    .rop-spark-head strong, .rop-top-head strong { font-size: 13px; color: #1a1a1a; }
    .rop-spark-stat {
        font-size: 11px; color: #6b7280;
        font-family: ui-monospace, monospace;
    }
    .rop-spark { width: 100%; height: 70px; display: block; }
    .rop-spark-axis {
        display: flex; justify-content: space-between;
        font-size: 10px; color: #9ca3af;
        font-family: ui-monospace, monospace;
        margin-top: 4px;
    }

    .rop-top-list { display: flex; flex-direction: column; gap: 6px; }
    .rop-top-row {
        display: flex; align-items: center; gap: 10px;
        padding: 5px 0; border-bottom: 1px solid #f3f4f6;
        font-size: 12px;
        color: inherit; text-decoration: none;
        transition: background 0.1s;
    }
    .rop-top-row:hover { background: #fffbeb; }
    .rop-artist-link {
        color: #1a1a1a; text-decoration: none;
        border-bottom: 1px dashed transparent;
        transition: border-color 0.15s;
    }
    .rop-artist-link:hover { border-bottom-color: #f0b90b; color: #92400e; }
    .rop-top-row:last-child { border-bottom: none; }
    .rop-top-medal { font-size: 16px; width: 22px; text-align: center; }
    .rop-top-name { flex: 1; }
    .rop-top-name strong { display: block; font-size: 12.5px; color: #1a1a1a; }
    .rop-top-name small { color: #888; font-size: 10px; }
    .rop-top-amount {
        font-weight: 700; color: #065f46;
        font-variant-numeric: tabular-nums;
    }

    .rop-filters {
        background:#fff; border:1px solid #e5e5e5;
        border-radius:8px; padding:10px 14px;
        margin-bottom:12px;
        display:flex; gap:10px; align-items:flex-end;
        flex-wrap:wrap;
    }
    .rop-filters .fg label {
        display:block; font-size:10px; color:#666;
        text-transform:uppercase; font-weight:600; margin-bottom:4px;
    }
    .rop-filters .fg label small { text-transform: none; font-weight: 400; opacity: 0.7; }
    .rop-filters .fg input, .rop-filters .fg select {
        padding:6px 9px; border:1px solid #ddd;
        border-radius:4px; font-size:12px; min-width:160px;
    }
    .rop-filters .fa { margin-left:auto; display: flex; gap: 6px; }

    .rop-table-wrap { background: #fff; border:1px solid #e5e5e5; border-radius: 8px; overflow: hidden; }
    .rop-table { width:100%; border-collapse:collapse; font-size:12px; }
    .rop-table th {
        background:#fafafa; padding:10px 12px; text-align:left;
        font-size:10px; text-transform:uppercase;
        color:#666; font-weight:600;
        border-bottom:1px solid #e5e5e5;
    }
    .rop-table td { padding:10px 12px; border-bottom:1px solid #f3f4f6; vertical-align:middle; }
    .rop-table tr:last-child td { border-bottom:none; }
    .rop-table tr:hover { background:#fffbeb; }
    .rop-table tr.reverted { opacity:0.5; background: #f9fafb; }
    .rop-table .muted { font-size:10px; color:#888; margin-top:2px; }
    .rop-table code { background:#f5f5f5; padding:2px 6px; border-radius:3px; font-size:10px; }

    .method-pill {
        padding:3px 9px; border-radius:10px;
        font-size:11px; font-weight:600;
        white-space: nowrap;
    }
    .method-pill.method-mpesa { background:#fee2e2; color:#991b1b; }
    .method-pill.method-emola { background:#d1fae5; color:#065f46; }
    .method-pill.method-bank_transfer { background:#dbeafe; color:#1e40af; }
    .method-pill.method-cash { background:#fef3c7; color:#92400e; }
    .method-pill.method-paypal { background:#e0e7ff; color:#3730a3; }

    .status-pill.status-completed { background:#d4edda; color:#155724; padding:3px 9px; border-radius:10px; font-size:11px; font-weight:600; }
    .status-pill.status-pending { background:#fff3cd; color:#856404; padding:3px 9px; border-radius:10px; font-size:11px; font-weight:600; }
    .status-pill.status-failed { background:#f8d7da; color:#721c24; padding:3px 9px; border-radius:10px; font-size:11px; font-weight:600; }

    .rop-empty {
        text-align:center; padding:40px 20px;
        color:#888; font-size:13px;
    }
    .rop-table-foot {
        padding: 8px 14px;
        background: #fafafa;
        border-top: 1px solid #e5e5e5;
        color: #888;
        text-align: center;
    }
    .rop-shortcuts {
        display: flex; gap: 14px;
        margin-top: 12px;
        font-size: 10px; color: #9ca3af;
        justify-content: flex-end;
    }
    .rop-shortcuts kbd {
        background: #fff; border: 1px solid #ddd;
        padding: 1px 6px; border-radius: 3px;
        font-family: ui-monospace, monospace;
        margin-right: 4px;
    }
    </style>

    <script>
    // [FEAT 1.6.23] Atalhos de teclado + pesquisa instantânea
    (function(){
        // N = novo pagamento
        // / = focar pesquisa
        // Esc = fechar formulário
        document.addEventListener('keydown', function(e){
            // não interceptar se utilizador está a escrever
            var tag = (e.target.tagName || '').toLowerCase();
            if (tag === 'input' || tag === 'textarea' || tag === 'select') {
                if (e.key === 'Escape') {
                    var f = document.getElementById('rop-pay-form');
                    if (f && f.style.display !== 'none') f.style.display = 'none';
                }
                return;
            }
            if (e.key === 'n' || e.key === 'N') {
                e.preventDefault();
                var f = document.getElementById('rop-pay-form');
                if (f) {
                    f.style.display = 'block';
                    var inp = f.querySelector('input[name=artist_phone]');
                    if (inp) inp.focus();
                }
            } else if (e.key === '/') {
                e.preventDefault();
                var s = document.getElementById('rop-search');
                if (s) s.focus();
            } else if (e.key === 'Escape') {
                var f = document.getElementById('rop-pay-form');
                if (f && f.style.display !== 'none') f.style.display = 'none';
            }
        });

        // Pesquisa instantânea (filtra a tabela cliente-side enquanto escreves)
        var search = document.getElementById('rop-search');
        if (search) {
            search.addEventListener('input', function(){
                var q = this.value.trim().toLowerCase();
                var rows = document.querySelectorAll('.rop-table tbody tr');
                rows.forEach(function(row){
                    if (row.classList.contains('rop-empty-row')) return;
                    var txt = row.textContent.toLowerCase();
                    row.style.display = (q === '' || txt.indexOf(q) !== -1) ? '' : 'none';
                });
            });
        }
    })();
    </script>
    <?php
}



/* ============================================================================
 * HANDLER — registar pagamento
 * ============================================================================ */
function rmbz_handle_payout_create() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');
    check_admin_referer('rmbz_payout_create_nonce');

    global $wpdb;
    $phone   = preg_replace('/[^0-9+]/', '', (string) ($_POST['artist_phone'] ?? ''));
    $amount  = (float) ($_POST['amount_usd'] ?? 0);
    $method  = sanitize_key($_POST['method'] ?? 'manual');
    $ref     = sanitize_text_field($_POST['reference_number'] ?? '');
    $status  = sanitize_key($_POST['status'] ?? 'completed');
    $notes   = sanitize_textarea_field($_POST['notes'] ?? '');

    $base = admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=payouts');

    if ( empty($phone) || $amount <= 0 ) {
        wp_safe_redirect( add_query_arg('pay_error', urlencode('Telemóvel e valor positivo são obrigatórios.'), $base) );
        exit;
    }

    $artist = $wpdb->get_row( $wpdb->prepare(
        "SELECT id, user_nome FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s LIMIT 1", $phone
    ) );
    if ( ! $artist ) {
        wp_safe_redirect( add_query_arg('pay_error', urlencode('Artista não encontrado: ' . $phone), $base) );
        exit;
    }

    $current_user = wp_get_current_user();
    $admin_login  = $current_user && $current_user->exists() ? $current_user->user_login : 'admin';
    $now = current_time('mysql');

    $wpdb->query('START TRANSACTION');
    try {
        $wpdb->insert( $wpdb->prefix . 'rmbz_distro_payouts', [
            'artist_telemovel'  => $phone,
            'amount_usd'        => $amount,
            'amount_original'   => $amount,
            'original_currency' => 'USD',
            'exchange_rate'     => 1.0,
            'method'            => $method,
            'reference_number'  => $ref,
            'status'            => $status,
            'notes'             => $notes,
            'paid_by'           => $admin_login,
            'paid_at'           => $now,
        ] );

        // Apenas debitar a wallet se o pagamento está marcado como concluído
        if ( $status === 'completed' ) {
            $wpdb->insert( $wpdb->prefix . 'rmbz_distro_ledger', [
                'artist_telemovel'  => $phone,
                'amount'            => -$amount,
                'currency'          => 'USD',
                'original_amount'   => -$amount,
                'original_currency' => 'USD',
                'exchange_rate'     => 1.0,
                'source_name'       => 'Payout',
                'reporting_period'  => date('Y-m'),
                'type'              => 'payout',
                'description'       => sprintf('Pagamento %s (%s) por %s', $method, $ref ?: 'sem ref', $admin_login),
                'reference_id'      => 'PAY_' . date('YmdHis'),
                'created_at'        => $now,
            ] );

            // Subtrai do total do artista
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}rmbz_distro_stats
                 SET total_earnings = GREATEST(0, total_earnings - %f), last_updated = %s
                 WHERE artist_telemovel = %s",
                $amount, $now, $phone
            ) );
        }

        $wpdb->query('COMMIT');
    } catch ( Exception $e ) {
        $wpdb->query('ROLLBACK');
        wp_safe_redirect( add_query_arg('pay_error', urlencode($e->getMessage()), $base) );
        exit;
    }

    wp_safe_redirect( add_query_arg('pay_done', '1', $base) );
    exit;
}
add_action('admin_post_rmbz_payout_create', 'rmbz_handle_payout_create');
