<?php
// includes/admin/admin-distribution-advanced.php
//
// Tabs avançadas: Catálogo de Faixas, Splits, Auditoria, Estatísticas Globais.

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

/* ============================================================================
 * TAB 5 — Catálogo de Faixas (todas as faixas com ISRC)
 * ============================================================================ */
function rmbz_admin_render_tracks_catalog() {
    global $wpdb;
    $t_tracks   = $wpdb->prefix . 'rmbz_distro_tracks';
    $t_releases = $wpdb->prefix . 'rmbz_distro_releases';
    $t_wallets  = $wpdb->prefix . 'rmbz_wallets';
    $t_daily    = $wpdb->prefix . 'rmbz_distro_daily_stats';

    $f_search = isset($_GET['f_search']) ? sanitize_text_field($_GET['f_search']) : '';

    // [FEAT 1.6.4] Ordenação clicável nas colunas Streams/Receita/Duração
    $f_sort = isset($_GET['f_sort']) ? sanitize_key($_GET['f_sort']) : 'id_desc';
    $sort_map = [
        'id_desc'        => 't.id DESC',
        'id_asc'         => 't.id ASC',
        'streams_desc'   => 'streams_total DESC, t.id DESC',
        'streams_asc'    => 'streams_total ASC, t.id DESC',
        'earnings_desc'  => 'earnings_total DESC, t.id DESC',
        'earnings_asc'   => 'earnings_total ASC, t.id DESC',
        'title_asc'      => 't.track_title ASC',
        'title_desc'     => 't.track_title DESC',
    ];
    $order_by = $sort_map[ $f_sort ] ?? $sort_map['id_desc'];

    // [ESCALA] Por página configurável — 40 por defeito, até 200.
    $per_page_options = [ 40, 100, 200 ];
    $per_page = (int) ( $_GET['f_pp'] ?? 40 );
    if ( ! in_array( $per_page, $per_page_options, true ) ) $per_page = 40;
    $paged    = max(1, (int) ($_GET['paged'] ?? 1));
    $offset   = ($paged - 1) * $per_page;

    $where = ['1=1'];
    $params = [];
    if ( $f_search ) {
        $like = '%' . $wpdb->esc_like($f_search) . '%';
        $where[] = '(t.track_title LIKE %s OR t.isrc_code LIKE %s OR r.title LIKE %s OR w.user_nome LIKE %s)';
        $params[] = $like; $params[] = $like; $params[] = $like; $params[] = $like;
    }
    $where_sql = implode(' AND ', $where);

    // Totais (por faixa, agregados do daily stats se existir)
    $has_daily = $wpdb->get_var("SHOW TABLES LIKE '$t_daily'") === $t_daily;
    $stats_cols = $has_daily ? ', COALESCE(s.streams, 0) AS streams_total, COALESCE(s.earnings, 0) AS earnings_total' : ', 0 AS streams_total, 0 AS earnings_total';

    // [DS 1.5.98] JOIN para contar aliases activos (ISRC + UPC) por faixa.
    $t_aliases = $wpdb->prefix . 'rmbz_distro_isrc_overrides';
    $has_aliases = $wpdb->get_var("SHOW TABLES LIKE '$t_aliases'") === $t_aliases;
    $aliases_cols = $has_aliases
        ? ', COALESCE(al.isrc_aliases_count, 0) AS isrc_aliases_count,
            COALESCE(al.upc_aliases_count, 0) AS upc_aliases_count,
            COALESCE(al.total_aliases_count, 0) AS total_aliases_count'
        : ', 0 AS isrc_aliases_count, 0 AS upc_aliases_count, 0 AS total_aliases_count';
    // Sub-join de aliases, opcionalmente limitado aos IDs da página.
    $aliases_join_for = function( $scope_sql ) use ( $t_aliases, $has_aliases ) {
        if ( ! $has_aliases ) return '';
        return "LEFT JOIN (
            SELECT track_id,
                   SUM(CASE WHEN alias_type = 'isrc' THEN 1 ELSE 0 END) AS isrc_aliases_count,
                   SUM(CASE WHEN alias_type = 'upc'  THEN 1 ELSE 0 END) AS upc_aliases_count,
                   COUNT(*) AS total_aliases_count
            FROM $t_aliases
            WHERE deleted_at IS NULL $scope_sql
            GROUP BY track_id
        ) al ON al.track_id = t.id";
    };

    $sql_count = "SELECT COUNT(*) FROM $t_tracks t
                  JOIN $t_releases r ON t.release_id = r.id
                  LEFT JOIN $t_wallets w ON r.artist_telemovel = w.user_telemovel
                  WHERE $where_sql";
    $total = $params ? (int) $wpdb->get_var( $wpdb->prepare($sql_count, $params) ) : (int) $wpdb->get_var($sql_count);

    // [ESCALA 50k] Duas estratégias de query:
    //   (a) ordenação por streams/receita: exige agregar o daily_stats inteiro
    //       ANTES de ordenar — caminho pesado, mas só corre quando o admin
    //       clica nessas colunas.
    //   (b) restantes ordenações (id, título): busca primeiro só os IDs da
    //       página (rápido, usa índices) e depois agrega stats/aliases APENAS
    //       para essas N faixas. Com 50 mil lançamentos continua instantâneo.
    $sort_needs_stats = strpos($f_sort, 'streams_') === 0 || strpos($f_sort, 'earnings_') === 0;

    if ( $sort_needs_stats && $has_daily ) {
        $stats_join  = "LEFT JOIN (SELECT track_id, SUM(streams) AS streams, SUM(sales) AS earnings FROM $t_daily GROUP BY track_id) s ON s.track_id = t.id";
        $sql = "SELECT t.*, r.title AS release_title, r.id AS release_id, r.cover_image, w.user_nome AS artist_name $stats_cols $aliases_cols
                FROM $t_tracks t
                JOIN $t_releases r ON t.release_id = r.id
                LEFT JOIN $t_wallets w ON r.artist_telemovel = w.user_telemovel
                $stats_join
                " . $aliases_join_for('') . "
                WHERE $where_sql
                ORDER BY $order_by
                LIMIT %d OFFSET %d";
        $rows = $wpdb->get_results( $wpdb->prepare($sql, array_merge($params, [$per_page, $offset])) );
    } else {
        if ( $sort_needs_stats ) $order_by = $sort_map['id_desc']; // sem daily_stats não há por onde ordenar
        $sql_ids = "SELECT t.id FROM $t_tracks t
                    JOIN $t_releases r ON t.release_id = r.id
                    LEFT JOIN $t_wallets w ON r.artist_telemovel = w.user_telemovel
                    WHERE $where_sql
                    ORDER BY $order_by
                    LIMIT %d OFFSET %d";
        $page_ids = array_map('intval', (array) $wpdb->get_col(
            $wpdb->prepare($sql_ids, array_merge($params, [$per_page, $offset]))
        ));
        if ( empty($page_ids) ) {
            $rows = [];
        } else {
            $ids_in = implode(',', $page_ids);
            $stats_join = $has_daily
                ? "LEFT JOIN (SELECT track_id, SUM(streams) AS streams, SUM(sales) AS earnings FROM $t_daily WHERE track_id IN ($ids_in) GROUP BY track_id) s ON s.track_id = t.id"
                : '';
            $rows = $wpdb->get_results(
                "SELECT t.*, r.title AS release_title, r.id AS release_id, r.cover_image, w.user_nome AS artist_name $stats_cols $aliases_cols
                 FROM $t_tracks t
                 JOIN $t_releases r ON t.release_id = r.id
                 LEFT JOIN $t_wallets w ON r.artist_telemovel = w.user_telemovel
                 $stats_join
                 " . $aliases_join_for("AND track_id IN ($ids_in)") . "
                 WHERE t.id IN ($ids_in)
                 ORDER BY FIELD(t.id, $ids_in)"
            );
        }
    }

    ?>
    <form method="get" class="rmbz-filters">
        <input type="hidden" name="page" value="rmbz-admin-distribution">
        <input type="hidden" name="tab" value="tracks">
        <div class="filter-group">
            <label>Pesquisar (título, ISRC, artista)</label>
            <input type="text" name="f_search" value="<?php echo esc_attr($f_search); ?>" placeholder="Ex: Cansei, MZAB2400001..." style="min-width:280px;">
        </div>
        <div class="filter-group">
            <label>Por página</label>
            <select name="f_pp" onchange="this.form.submit()">
                <?php foreach ( $per_page_options as $pp ): ?>
                    <option value="<?php echo $pp; ?>" <?php selected($per_page, $pp); ?>><?php echo $pp; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="filter-actions">
            <button type="submit" class="button button-primary">🔍 Pesquisar</button>
            <a href="?page=rmbz-admin-distribution&tab=tracks" class="button">Limpar</a>
        </div>
    </form>

    <p style="color:var(--rmbz-text-muted, #666);"><?php echo $total; ?> faixa(s) no catálogo<?php if ( $f_search ) echo ' (filtrado)'; ?></p>

    <?php
    // Helper para construir URL de ordenação preservando filtro
    $sort_url = function( $key ) use ( $f_search, $f_sort, $per_page ) {
        $base = '?page=rmbz-admin-distribution&tab=tracks';
        if ( $f_search ) $base .= '&f_search=' . urlencode($f_search);
        if ( $per_page !== 40 ) $base .= '&f_pp=' . $per_page;
        // Toggle asc/desc se já estiver na coluna
        $current_dir = preg_match("/^{$key}_(asc|desc)$/", $f_sort, $m) ? $m[1] : '';
        $next = $current_dir === 'desc' ? 'asc' : 'desc';
        return esc_url( $base . '&f_sort=' . $key . '_' . $next );
    };
    $sort_indicator = function( $key ) use ( $f_sort ) {
        if ( strpos($f_sort, $key . '_') !== 0 ) return '<span class="rmbz-sort-icon">↕</span>';
        $dir = substr($f_sort, strlen($key) + 1);
        return '<span class="rmbz-sort-icon active">' . ( $dir === 'desc' ? '↓' : '↑' ) . '</span>';
    };

    // Format helpers
    $fmt_num_compact = function( $n ) {
        $n = (int) $n;
        if ( $n >= 1000000 ) return number_format( $n / 1000000, 1 ) . 'M';
        if ( $n >= 1000 )    return number_format( $n / 1000, 1 ) . 'k';
        return number_format_i18n( $n );
    };
    ?>

    <div class="rmbz-cat-wrap">
        <table class="rmbz-cat">
            <colgroup>
                <col class="c-title"><col class="c-release"><col class="c-artist"><col class="c-isrc"><col class="c-aliases"><col class="c-streams"><col class="c-earn">
            </colgroup>
            <thead>
                <tr>
                    <th><a href="<?php echo $sort_url('title'); ?>" class="rmbz-th-sort">Título <?php echo $sort_indicator('title'); ?></a></th>
                    <th>Lançamento</th>
                    <th>Artista</th>
                    <th>ISRC</th>
                    <th>Aliases</th>
                    <th class="rmbz-th-num"><a href="<?php echo $sort_url('streams'); ?>" class="rmbz-th-sort">Streams <?php echo $sort_indicator('streams'); ?></a></th>
                    <th class="rmbz-th-num"><a href="<?php echo $sort_url('earnings'); ?>" class="rmbz-th-sort">Receita <?php echo $sort_indicator('earnings'); ?></a></th>
                </tr>
            </thead>
            <tbody>
            <?php if ( empty($rows) ): ?>
                <tr><td colspan="7" class="rmbz-cat-empty">Nenhuma faixa encontrada.</td></tr>
            <?php else: foreach ( $rows as $t ):
                $extra = [];
                if ( ! empty($t->extra_data) ) {
                    $d = json_decode($t->extra_data, true);
                    if ( is_array($d) ) $extra = $d;
                }
                $dur = (int) ($extra['duration_seconds'] ?? 0);
                $isrc_n  = (int) ($t->isrc_aliases_count ?? 0);
                $upc_n   = (int) ($t->upc_aliases_count ?? 0);
                $total_n = $isrc_n + $upc_n;
                $streams = (int) $t->streams_total;
                $earnings = (float) $t->earnings_total;
                $has_money = $earnings > 0;
            ?>
                <tr class="rmbz-cat-tr<?php echo $has_money ? ' is-earning' : ''; ?>">
                    <td class="td-title">
                        <div class="td-title-flex">
                            <?php if ( ! empty($t->cover_image) ): ?>
                                <img src="<?php echo esc_url($t->cover_image); ?>" class="rmbz-td-cover" alt="" loading="lazy">
                            <?php else: ?>
                                <div class="rmbz-td-cover rmbz-td-cover-empty">🎵</div>
                            <?php endif; ?>
                            <div class="td-title-text">
                                <div class="rmbz-td-track-name" title="<?php echo esc_attr($t->track_title); ?>"><?php echo esc_html($t->track_title); ?></div>
                                <?php
                                $subs = [];
                                if ( ! empty($extra['collaborators']) ) {
                                    $feats = array_slice(array_column($extra['collaborators'], 'name'), 0, 2);
                                    if ( $feats ) $subs[] = 'feat. ' . implode(', ', $feats);
                                }
                                if ( $dur > 0 ) $subs[] = sprintf('%d:%02d', floor($dur/60), $dur%60);
                                if ( $subs ): ?>
                                    <div class="rmbz-td-sub"><?php echo esc_html( implode(' · ', $subs) ); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </td>
                    <td class="td-ellipsis">
                        <a class="rmbz-cat-release" href="?page=rmbz-admin-distribution&tab=releases&view=detail&id=<?php echo (int) $t->release_id; ?>" title="<?php echo esc_attr($t->release_title); ?>">
                            <?php echo esc_html($t->release_title); ?>
                        </a>
                    </td>
                    <td class="td-ellipsis rmbz-cat-artist"><?php echo esc_html($t->artist_name ?: '—'); ?></td>
                    <td>
                        <?php if ( $t->isrc_code ): ?>
                            <code class="rmbz-isrc-pill" title="<?php echo esc_attr($t->isrc_code); ?>"><?php echo esc_html($t->isrc_code); ?></code>
                        <?php else: ?>
                            <span class="rmbz-isrc-pending">⏳ Pendente</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ( $total_n > 0 ): ?>
                            <button type="button"
                                    class="button button-small rmbz-toggle-aliases"
                                    data-target="rmbz-aliases-<?php echo (int) $t->id; ?>"
                                    data-track-id="<?php echo (int) $t->id; ?>">
                                <?php if ( $isrc_n > 0 ): ?><span class="rmbz-chip rmbz-chip-isrc">ISRC ×<?php echo $isrc_n; ?></span><?php endif; ?>
                                <?php if ( $upc_n > 0 ): ?><span class="rmbz-chip rmbz-chip-upc">UPC ×<?php echo $upc_n; ?></span><?php endif; ?>
                                <span class="rmbz-toggle-arrow">▾</span>
                            </button>
                        <?php else: ?>
                            <button type="button"
                                    class="button button-small rmbz-add-alias-btn"
                                    data-track-id="<?php echo (int) $t->id; ?>"
                                    data-track-title="<?php echo esc_attr($t->track_title); ?>"
                                    title="Adicionar ISRC ou UPC alternativo">
                                + Adicionar
                            </button>
                        <?php endif; ?>
                    </td>
                    <td class="td-num">
                        <?php if ( $streams > 0 ): ?>
                            <span class="rmbz-streams-pill" title="<?php echo esc_attr( number_format_i18n($streams) ); ?> streams"><?php echo $fmt_num_compact($streams); ?></span>
                        <?php else: ?>
                            <span class="rmbz-streams-zero">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="td-num">
                        <?php if ( $has_money ): ?>
                            <span class="rmbz-earnings-pill"><?php echo '$' . number_format( $earnings, 2 ); ?></span>
                        <?php else: ?>
                            <span class="rmbz-earnings-zero">$0.00</span>
                        <?php endif; ?>
                    </td>
                </tr>

                <?php // Sub-linha de aliases: <tr colspan> — alinhamento garantido pela própria tabela ?>
                <?php if ( $total_n > 0 ): ?>
                    <tr id="rmbz-aliases-<?php echo (int) $t->id; ?>" class="rmbz-cat-subrow" style="display:none;">
                        <td colspan="7">
                            <div class="rmbz-aliases-inner">
                                <div class="rmbz-aliases-head">
                                    <strong>🔗 Aliases activos para "<?php echo esc_html($t->track_title); ?>"</strong>
                                    <button type="button"
                                            class="button button-small rmbz-add-alias-btn"
                                            data-track-id="<?php echo (int) $t->id; ?>"
                                            data-track-title="<?php echo esc_attr($t->track_title); ?>">
                                        + Adicionar alias
                                    </button>
                                </div>
                                <table class="rmbz-aliases-table">
                                <thead>
                                    <tr>
                                        <th style="width:60px;">Tipo</th>
                                        <th>Valor (CSV)</th>
                                        <th style="width:140px;">Criado em</th>
                                        <th style="width:100px;">Por</th>
                                        <th style="width:100px; text-align:right;">Acção</th>
                                    </tr>
                                </thead>
                                <tbody class="rmbz-aliases-tbody" data-loaded="0">
                                    <tr><td colspan="5" class="rmbz-aliases-loading">A carregar…</td></tr>
                                </tbody>
                                </table>
                            </div>
                        </td>
                    </tr>
                <?php endif; ?>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <?php
    $total_pages = (int) ceil( $total / $per_page );
    if ( $total_pages > 1 ) {
        echo '<div class="tablenav" style="margin-top:15px;"><div class="tablenav-pages">';
        echo paginate_links([
            'base'    => add_query_arg('paged', '%#%'),
            'format'  => '',
            'current' => $paged,
            'total'   => $total_pages,
            'prev_text' => '‹',
            'next_text' => '›',
        ]);
        echo '</div></div>';
    }

    // [DS 1.5.98] JS + CSS para os controlos de aliases (toggle, listar, apagar, adicionar)
    ?>
    <style>
    .rmbz-toggle-aliases { cursor:pointer; }
    .rmbz-toggle-aliases.is-open .rmbz-toggle-arrow { transform: rotate(180deg); display:inline-block; }
    .rmbz-toggle-arrow { display:inline-block; transition:transform .15s; margin-left:3px; font-size:9px; color:var(--rmbz-text-faint, #888); }
    .rmbz-aliases-row td { border-top:1px solid #e5e5e5 !important; }
    .rmbz-add-alias-btn:hover { background:#f0f7ff; border-color:var(--rmbz-info, #3b82f6); color:#1a5490; }

    /* ════════ CATÁLOGO DE FAIXAS — tabela de larguras fixas ════════
       table-layout:fixed + colgroup: TODAS as linhas partilham as mesmas
       colunas, por isso é estruturalmente impossível desalinharem —
       independentemente de chips de aliases, títulos longos ou ISRCs. */
    .rmbz-cat-wrap {
        margin-top: 14px;
        background: #fff;
        border: 1px solid #e6e8eb;
        border-radius: 12px;
        overflow-x: auto;
        box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04);
    }
    .rmbz-cat {
        width: 100%;
        min-width: 980px; /* em ecrãs estreitos faz scroll horizontal, nunca parte */
        border-collapse: separate;
        border-spacing: 0;
        table-layout: fixed;
        font-size: 13px;
    }
    .rmbz-cat col.c-title   { width: 30%; }
    .rmbz-cat col.c-release { width: 17%; }
    .rmbz-cat col.c-artist  { width: 12%; }
    .rmbz-cat col.c-isrc    { width: 13%; }
    .rmbz-cat col.c-aliases { width: 14%; }
    .rmbz-cat col.c-streams { width: 7%; }
    .rmbz-cat col.c-earn    { width: 7%; }

    .rmbz-cat thead th {
        position: sticky;
        top: 0;
        z-index: 2;
        background: linear-gradient(180deg, #fafbfc 0%, #f3f4f6 100%);
        border-bottom: 1px solid #e6e8eb;
        padding: 10px 14px;
        text-align: left;
        font-size: 10px;
        text-transform: uppercase;
        letter-spacing: 0.06em;
        color: #6b7280;
        font-weight: 700;
        white-space: nowrap;
    }
    .rmbz-cat thead th.rmbz-th-num { text-align: right; }
    .rmbz-th-sort { text-decoration: none; color: inherit; display: inline-flex; align-items: center; gap: 5px; }
    .rmbz-th-sort:hover { color: #f0b90b; }
    .rmbz-sort-icon { opacity: 0.4; font-size: 11px; }
    .rmbz-sort-icon.active { opacity: 1; color: #f0b90b; }

    .rmbz-cat tbody td {
        padding: 9px 14px;
        border-bottom: 1px solid #f3f4f6;
        vertical-align: middle;
        overflow: hidden;
    }
    .rmbz-cat tbody tr.rmbz-cat-tr:hover td { background: #fafbfc; }
    .rmbz-cat tbody tr.is-earning td { background: linear-gradient(90deg, #fffbeb, rgba(255,255,255,0) 60%); }
    .rmbz-cat tbody tr.is-earning:hover td { background: #fef9e7; }
    .rmbz-cat-empty, .rmbz-aliases-loading { text-align: center; padding: 36px 16px !important; color: #9ca3af; font-size: 13px; }

    .td-ellipsis { white-space: nowrap; text-overflow: ellipsis; }
    .td-num { text-align: right; white-space: nowrap; }

    /* Título com capa */
    .td-title-flex { display: flex; align-items: center; gap: 10px; min-width: 0; }
    .rmbz-td-cover {
        width: 40px; height: 40px;
        border-radius: 8px;
        object-fit: cover;
        background: #e5e7eb;
        flex-shrink: 0;
    }
    .rmbz-td-cover-empty { display: flex; align-items: center; justify-content: center; font-size: 16px; color: #9ca3af; }
    .td-title-text { min-width: 0; }
    .rmbz-td-track-name { font-weight: 600; color: #1a1a1a; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .rmbz-td-sub { font-size: 11px; color: #9ca3af; margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

    .rmbz-cat-release { text-decoration: none; color: #1a1a1a; font-weight: 500; }
    .rmbz-cat-release:hover { color: #f0b90b; }
    .rmbz-cat-artist { color: #4b5563; font-size: 12.5px; }

    /* ISRC */
    .rmbz-isrc-pill {
        background: #f3f4f6;
        color: #1a1a1a;
        padding: 3px 8px;
        border-radius: 5px;
        font-family: ui-monospace, monospace;
        font-size: 11px;
        font-weight: 500;
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: middle;
        box-sizing: border-box;
    }
    .rmbz-isrc-pending { background: #fef3c7; color: #92400e; padding: 3px 8px; border-radius: 5px; font-size: 11px; font-weight: 600; }

    /* Aliases: chips quebram linha DENTRO da célula em vez de a esticar */
    .rmbz-chip { color: #fff; padding: 1px 6px; border-radius: 3px; font-size: 10px; }
    .rmbz-chip-isrc { background: var(--rmbz-accent, #a855f7); }
    .rmbz-chip-upc  { background: var(--rmbz-info-strong, #0073aa); }
    .rmbz-toggle-aliases {
        display: inline-flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 3px;
        max-width: 100%;
        height: auto;
        min-height: 24px;
        white-space: normal;
        line-height: 1.4;
        font-size: 11px;
        padding: 2px 8px;
    }
    .rmbz-add-alias-btn { font-size: 11px; padding: 2px 8px; color: var(--rmbz-text-muted, #666); }

    /* Streams / Receita */
    .rmbz-streams-pill { background: #e0e7ff; color: #3730a3; padding: 4px 10px; border-radius: 12px; font-weight: 700; font-size: 12px; font-variant-numeric: tabular-nums; }
    .rmbz-streams-zero { color: #d1d5db; font-size: 14px; }
    .rmbz-earnings-pill { background: linear-gradient(135deg, #10b981, #059669); color: #fff; padding: 4px 10px; border-radius: 12px; font-weight: 800; font-size: 12px; font-variant-numeric: tabular-nums; box-shadow: 0 1px 3px rgba(16, 185, 129, 0.25); }
    .rmbz-earnings-zero { color: #d1d5db; font-size: 12px; font-variant-numeric: tabular-nums; }

    /* Sub-linha de aliases */
    .rmbz-cat-subrow > td { background: #fafbfc; padding: 0; border-bottom: 1px solid #e6e8eb; }
    .rmbz-aliases-inner { padding: 12px 16px; }
    .rmbz-aliases-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; font-size: 12px; color: var(--rmbz-text-muted, #666); }
    .rmbz-aliases-table { width: 100%; font-size: 11px; background: var(--rmbz-bg-card, #fff); border: 1px solid #e5e5e5; border-radius: 6px; border-collapse: separate; border-spacing: 0; }
    .rmbz-aliases-table thead th { text-align: left; padding: 6px 10px; background: #f0f0f0; font-size: 10px; text-transform: uppercase; color: #6b7280; }
    </style>
    <script>
    (function() {
        var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
        var nonceList = '<?php echo wp_create_nonce('rmbz_list_aliases'); ?>';
        var nonceDelete = '<?php echo wp_create_nonce('rmbz_delete_alias'); ?>';
        var nonceAdd = '<?php echo wp_create_nonce('rmbz_map_isrc'); ?>';

        // Toggle expansão de aliases
        document.querySelectorAll('.rmbz-toggle-aliases').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var targetId = btn.dataset.target;
                var trackId  = btn.dataset.trackId;
                var row = document.getElementById(targetId);
                if (!row) return;

                var isOpen = row.style.display !== 'none';
                row.style.display = isOpen ? 'none' : '';
                btn.classList.toggle('is-open', !isOpen);

                // Lazy load dos aliases na primeira abertura
                var tbody = row.querySelector('.rmbz-aliases-tbody');
                if (!isOpen && tbody && tbody.dataset.loaded === '0') {
                    loadAliases(trackId, tbody);
                }
            });
        });

        function loadAliases(trackId, tbody) {
            var fd = new FormData();
            fd.append('action', 'rmbz_list_track_aliases');
            fd.append('track_id', trackId);
            fd.append('_nonce', nonceList);
            fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' })
                .then(function(r){ return r.json(); })
                .then(function(res){
                    if (!res.success) {
                        tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; padding:14px; color:var(--rmbz-danger, #cc0000);">Erro a carregar.</td></tr>';
                        return;
                    }
                    renderAliases(tbody, res.data.aliases || [], trackId);
                    tbody.dataset.loaded = '1';
                });
        }

        function renderAliases(tbody, aliases, trackId) {
            if (!aliases.length) {
                tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; padding:14px; color:var(--rmbz-text-faint, #888);">Sem aliases activos.</td></tr>';
                return;
            }
            var html = '';
            aliases.forEach(function(a) {
                var color = a.alias_type === 'upc' ? '#0073aa' : '#9b59b6';
                html += '<tr data-alias-id="' + a.id + '">' +
                    '<td style="padding:6px 10px;">' +
                      '<span style="background:' + color + '; color:var(--rmbz-text-on-color, #fff); padding:2px 7px; border-radius:3px; font-size:10px; text-transform:uppercase;">' +
                        a.alias_type +
                      '</span>' +
                    '</td>' +
                    '<td style="padding:6px 10px;"><code>' + escapeHtml(a.csv_value) + '</code></td>' +
                    '<td style="padding:6px 10px; color:var(--rmbz-text-muted, #666);">' + escapeHtml(a.created_at_human || a.created_at) + '</td>' +
                    '<td style="padding:6px 10px; color:var(--rmbz-text-muted, #666);">' + escapeHtml(a.created_by || '—') + '</td>' +
                    '<td style="padding:6px 10px; text-align:right;">' +
                      '<button type="button" class="button button-link-delete rmbz-del-alias" ' +
                        'data-alias-id="' + a.id + '" data-track-id="' + trackId + '" ' +
                        'style="font-size:11px; color:var(--rmbz-danger-strong, #aa0000);">🗑 Remover</button>' +
                    '</td>' +
                  '</tr>';
            });
            tbody.innerHTML = html;

            tbody.querySelectorAll('.rmbz-del-alias').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var reason = prompt('Razão para remover este alias (opcional, fica em auditoria):');
                    if (reason === null) return;
                    if (!confirm('Tens a certeza? Este alias vai deixar de funcionar nos próximos imports.\n\n(O registo é mantido em arquivo para auditoria.)')) return;
                    deleteAlias(btn.dataset.aliasId, btn.dataset.trackId, reason, btn.closest('tr'));
                });
            });
        }

        function deleteAlias(aliasId, trackId, reason, rowEl) {
            var fd = new FormData();
            fd.append('action', 'rmbz_delete_track_alias');
            fd.append('alias_id', aliasId);
            fd.append('reason', reason || '');
            fd.append('_nonce', nonceDelete);
            fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' })
                .then(function(r){ return r.json(); })
                .then(function(res){
                    if (res.success) {
                        rowEl.style.transition = 'opacity .3s';
                        rowEl.style.opacity = '0';
                        setTimeout(function() {
                            var parent = rowEl.parentNode;
                            rowEl.remove();
                            if (parent && parent.children.length === 0) {
                                parent.innerHTML = '<tr><td colspan="5" style="text-align:center; padding:14px; color:var(--rmbz-text-faint, #888);">Sem aliases activos.</td></tr>';
                            }
                        }, 300);
                    } else {
                        alert('Erro: ' + ((res.data && res.data.msg) || 'desconhecido'));
                    }
                });
        }

        // Botões "+ Adicionar alias" — abre modal manual (utilizador escreve o valor)
        document.querySelectorAll('.rmbz-add-alias-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                openAddAliasModal(btn.dataset.trackId, btn.dataset.trackTitle);
            });
        });

        function openAddAliasModal(trackId, trackTitle) {
            var existing = document.getElementById('rmbz-add-alias-modal');
            if (existing) existing.remove();
            var modal = document.createElement('div');
            modal.id = 'rmbz-add-alias-modal';
            modal.innerHTML = '<div style="position:fixed; inset:0; background:rgba(0,0,0,0.5); z-index:99999; display:flex; align-items:center; justify-content:center;">' +
                '<div style="background:var(--rmbz-bg-card, #fff); border-radius:10px; padding:24px; max-width:520px; width:90%; box-shadow:0 8px 24px rgba(0,0,0,0.2);">' +
                  '<h3 style="margin:0 0 6px;">+ Adicionar alias à faixa</h3>' +
                  '<p style="margin:0 0 14px; color:var(--rmbz-text-muted, #666); font-size:13px;">Faixa: <strong>' + escapeHtml(trackTitle) + '</strong></p>' +
                  '<div style="margin-bottom:14px; padding:12px; background:#f8f9fa; border-radius:6px;">' +
                    '<div style="font-size:12px; color:var(--rmbz-text-muted, #666); margin-bottom:8px; font-weight:600;">Tipo de identificador:</div>' +
                    '<label style="display:inline-flex; align-items:center; gap:6px; margin-right:18px; cursor:pointer;">' +
                      '<input type="radio" name="add-alias-type" value="isrc" checked> <span><strong>ISRC</strong></span>' +
                    '</label>' +
                    '<label style="display:inline-flex; align-items:center; gap:6px; cursor:pointer;">' +
                      '<input type="radio" name="add-alias-type" value="upc"> <span><strong>UPC</strong></span>' +
                    '</label>' +
                  '</div>' +
                  '<label style="display:block; font-size:12px; color:var(--rmbz-text-muted, #666); margin-bottom:6px; font-weight:600;">Valor (como aparece no CSV das distribuidoras):</label>' +
                  '<input type="text" id="rmbz-new-alias-value" placeholder="Ex: TCAHB2328707 ou 884505829293" ' +
                    'style="width:100%; padding:10px; font-size:14px; border:1px solid #ccc; border-radius:6px; box-sizing:border-box; font-family:monospace;" autofocus>' +
                  '<p style="margin:8px 0 14px; font-size:11px; color:var(--rmbz-text-faint, #888);">Este valor será reconhecido em futuros imports e mapeado automaticamente para esta faixa.</p>' +
                  '<div style="text-align:right;">' +
                    '<button type="button" class="button" id="rmbz-add-cancel" style="margin-right:6px;">Cancelar</button>' +
                    '<button type="button" class="button button-primary" id="rmbz-add-save">Guardar alias</button>' +
                  '</div>' +
                '</div></div>';
            document.body.appendChild(modal);
            document.getElementById('rmbz-add-cancel').onclick = function() { modal.remove(); };
            document.getElementById('rmbz-add-save').onclick = function() {
                var val = document.getElementById('rmbz-new-alias-value').value.trim();
                if (val.length < 4) { alert('Valor demasiado curto.'); return; }
                var type = modal.querySelector('input[name="add-alias-type"]:checked').value;
                var fd = new FormData();
                fd.append('action', 'rmbz_save_isrc_mapping');
                fd.append('csv_isrc', val);
                fd.append('alias_type', type);
                fd.append('track_id', trackId);
                fd.append('_nonce', nonceAdd);
                fetch(ajaxUrl, { method:'POST', body:fd, credentials:'same-origin' })
                    .then(function(r){ return r.json(); })
                    .then(function(res){
                        if (res.success) {
                            alert('✓ Alias guardado. A página vai recarregar.');
                            modal.remove();
                            window.location.reload();
                        } else {
                            alert('Erro: ' + ((res.data && res.data.msg) || 'desconhecido'));
                        }
                    });
            };
        }

        function escapeHtml(s) {
            return String(s == null ? '' : s).replace(/[&<>"']/g, function(c) {
                return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
            });
        }
    })();
    </script>
    <?php
}


/* ============================================================================
 * TAB 6 — Splits Pendentes
 * ============================================================================ */
function rmbz_admin_render_splits_page() {
    global $wpdb;
    $t_splits   = $wpdb->prefix . 'rmbz_track_splits';
    $t_tracks   = $wpdb->prefix . 'rmbz_distro_tracks';
    $t_releases = $wpdb->prefix . 'rmbz_distro_releases';
    $t_wallets  = $wpdb->prefix . 'rmbz_wallets';

    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_splits'") !== $t_splits ) {
        echo '<div class="notice notice-warning"><p>A tabela de splits ainda não foi criada. Será criada automaticamente quando o primeiro split for guardado.</p></div>';
        return;
    }

    // Messages
    if ( ! empty($_GET['msg']) ) {
        $msgs = [
            'forced_accept' => '✓ Split marcado como aceite.',
            'forced_reject' => '✗ Split marcado como rejeitado.',
            'deleted'       => '🗑 Split apagado.',
        ];
        if ( isset($msgs[$_GET['msg']]) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($msgs[$_GET['msg']]) . '</p></div>';
        }
    }

    $f_status = isset($_GET['f_status']) ? sanitize_key($_GET['f_status']) : 'pending';

    $where = ['1=1'];
    $params = [];
    if ( $f_status && $f_status !== 'all' ) {
        $where[] = 's.invite_status = %s';
        $params[] = $f_status;
    }
    $where_sql = implode(' AND ', $where);

    $sql = "SELECT s.*, t.track_title, r.title AS release_title, r.id AS release_id, w.user_nome AS artist_name,
                   cw.user_nome AS collab_registered_name
            FROM $t_splits s
            LEFT JOIN $t_tracks t   ON s.track_id = t.id
            LEFT JOIN $t_releases r ON s.release_id = r.id
            LEFT JOIN $t_wallets w  ON r.artist_telemovel = w.user_telemovel
            LEFT JOIN $t_wallets cw ON s.collaborator_telemovel = cw.user_telemovel
            WHERE $where_sql
            ORDER BY s.created_at DESC";
    $splits = $params ? $wpdb->get_results( $wpdb->prepare($sql, $params) ) : $wpdb->get_results($sql);

    $totals = $wpdb->get_row(
        "SELECT
            SUM(CASE WHEN invite_status='pending' THEN 1 ELSE 0 END) AS pending,
            SUM(CASE WHEN invite_status='accepted' THEN 1 ELSE 0 END) AS accepted,
            SUM(CASE WHEN invite_status='rejected' THEN 1 ELSE 0 END) AS rejected,
            COUNT(*) AS total
         FROM $t_splits"
    );

    ?>
    <div class="rmbz-kpi-grid">
        <div class="rmbz-kpi amber">
            <p class="lbl">Pendentes</p>
            <p class="val"><?php echo (int) ($totals->pending ?? 0); ?></p>
            <p class="sub">À espera de aceite</p>
        </div>
        <div class="rmbz-kpi green">
            <p class="lbl">Aceites</p>
            <p class="val"><?php echo (int) ($totals->accepted ?? 0); ?></p>
            <p class="sub">Activos no importer</p>
        </div>
        <div class="rmbz-kpi red">
            <p class="lbl">Rejeitados</p>
            <p class="val"><?php echo (int) ($totals->rejected ?? 0); ?></p>
            <p class="sub">Não recebem</p>
        </div>
        <div class="rmbz-kpi blue">
            <p class="lbl">Total</p>
            <p class="val"><?php echo (int) ($totals->total ?? 0); ?></p>
            <p class="sub">Splits declarados</p>
        </div>
    </div>

    <form method="get" class="rmbz-filters">
        <input type="hidden" name="page" value="rmbz-admin-distribution">
        <input type="hidden" name="tab" value="splits">
        <div class="filter-group">
            <label>Status</label>
            <select name="f_status" onchange="this.form.submit()">
                <option value="all"      <?php selected($f_status, 'all'); ?>>Todos</option>
                <option value="pending"  <?php selected($f_status, 'pending'); ?>>Pendentes</option>
                <option value="accepted" <?php selected($f_status, 'accepted'); ?>>Aceites</option>
                <option value="rejected" <?php selected($f_status, 'rejected'); ?>>Rejeitados</option>
            </select>
        </div>
    </form>

    <div class="rmbz-table-wrap">
        <table class="rmbz-table">
            <thead>
                <tr>
                    <th>Lançamento / Faixa</th>
                    <th>Artista principal</th>
                    <th>Colaborador</th>
                    <th>Contacto</th>
                    <th>Função</th>
                    <th>%</th>
                    <th>Status</th>
                    <th>Acções</th>
                </tr>
            </thead>
            <tbody>
            <?php if ( empty($splits) ): ?>
                <tr><td colspan="8" style="text-align:center; padding:30px; color:var(--rmbz-text-faint, #888);">Nenhum split nesta categoria.</td></tr>
            <?php else: foreach ( $splits as $s ): ?>
                <tr>
                    <td>
                        <a href="?page=rmbz-admin-distribution&tab=releases&view=detail&id=<?php echo (int) $s->release_id; ?>">
                            <strong><?php echo esc_html($s->release_title); ?></strong>
                        </a>
                        <div style="font-size:11px; color:var(--rmbz-text-muted, #666);"><?php echo esc_html($s->track_title); ?></div>
                    </td>
                    <td><?php echo esc_html($s->artist_name ?: '—'); ?></td>
                    <td>
                        <?php echo esc_html($s->collaborator_name); ?>
                        <?php if ( $s->collab_registered_name ): ?>
                            <div style="font-size:10px; color:var(--rmbz-success, #10b981);">✓ Tem conta 1MZ (<?php echo esc_html($s->collab_registered_name); ?>)</div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ( $s->collaborator_telemovel ): ?>
                            <code><?php echo esc_html($s->collaborator_telemovel); ?></code>
                        <?php elseif ( $s->collaborator_email ): ?>
                            <?php echo esc_html($s->collaborator_email); ?>
                        <?php else: ?>
                            <em style="color:var(--rmbz-text-faint, #aaa);">sem contacto</em>
                        <?php endif; ?>
                    </td>
                    <td><?php echo esc_html($s->role); ?></td>
                    <td><strong><?php echo number_format((float) $s->percentage, 2); ?>%</strong></td>
                    <td>
                        <?php
                        $map = [
                            'pending'  => ['color:#856404; background:#fff3cd; padding:2px 8px; border-radius:10px;', 'Pendente'],
                            'accepted' => ['color:var(--rmbz-success-strong, #166534); background:#d4edda; padding:2px 8px; border-radius:10px;', 'Aceite'],
                            'rejected' => ['color:var(--rmbz-danger-strong, #721c24); background:#f8d7da; padding:2px 8px; border-radius:10px;', 'Rejeitado'],
                        ];
                        $m = $map[$s->invite_status] ?? ['', $s->invite_status];
                        ?>
                        <span style="font-size:11px; font-weight:600; <?php echo esc_attr($m[0]); ?>"><?php echo esc_html($m[1]); ?></span>
                    </td>
                    <td style="white-space:nowrap;">
                        <?php if ( $s->invite_status !== 'accepted' ): ?>
                            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline;">
                                <?php wp_nonce_field('rmbz_split_action_' . $s->id); ?>
                                <input type="hidden" name="action" value="rmbz_split_force_accept">
                                <input type="hidden" name="split_id" value="<?php echo (int) $s->id; ?>">
                                <button type="submit" class="button button-small button-primary"
                                        title="Marcar como aceite manualmente">✓</button>
                            </form>
                        <?php endif; ?>
                        <?php if ( $s->invite_status !== 'rejected' ): ?>
                            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline;">
                                <?php wp_nonce_field('rmbz_split_action_' . $s->id); ?>
                                <input type="hidden" name="action" value="rmbz_split_force_reject">
                                <input type="hidden" name="split_id" value="<?php echo (int) $s->id; ?>">
                                <button type="submit" class="button button-small"
                                        title="Rejeitar manualmente">✗</button>
                            </form>
                        <?php endif; ?>
                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display:inline;">
                            <?php wp_nonce_field('rmbz_split_action_' . $s->id); ?>
                            <input type="hidden" name="action" value="rmbz_split_delete">
                            <input type="hidden" name="split_id" value="<?php echo (int) $s->id; ?>">
                            <button type="submit" class="button button-small"
                                    onclick="return confirm('Apagar este split?');" title="Apagar">🗑</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <div class="rmbz-section" style="margin-top:20px; background:#f8f9fa; border-left:4px solid var(--rmbz-info, #3498db);">
        <h3>ℹ️ Como funcionam os splits</h3>
        <p style="margin:0;">Quando um artista configura um split para uma faixa, o colaborador começa com status <strong>Pendente</strong>. Apenas splits <strong>Aceites</strong> são aplicados pelo importer de CSV mensal. Se o colaborador não tem conta 1MZ, pode marcar manualmente como aceite aqui — mas terá de pagar fora do sistema.</p>
    </div>
    <?php
}


/* ============================================================================
 * TAB 7 — Log de Auditoria
 * ============================================================================ */
function rmbz_admin_render_audit_log() {
    global $wpdb;
    $t_history = $wpdb->prefix . 'rmbz_distro_status_history';
    $t_releases = $wpdb->prefix . 'rmbz_distro_releases';

    if ( $wpdb->get_var("SHOW TABLES LIKE '$t_history'") !== $t_history ) {
        echo '<div class="notice notice-warning"><p>Tabela de auditoria não existe ainda. Será criada automaticamente na próxima transição de status.</p></div>';
        return;
    }

    $per_page = 50;
    $paged = max(1, (int) ($_GET['paged'] ?? 1));
    $offset = ($paged - 1) * $per_page;

    $total = (int) $wpdb->get_var("SELECT COUNT(*) FROM $t_history");

    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT h.*, r.title AS release_title
         FROM $t_history h
         LEFT JOIN $t_releases r ON h.release_id = r.id
         ORDER BY h.created_at DESC
         LIMIT %d OFFSET %d",
        $per_page, $offset
    ) );

    ?>
    <p style="color:var(--rmbz-text-muted, #666);">Histórico de todas as transições de status dos lançamentos. <?php echo $total; ?> entrada(s) no total.</p>

    <div class="rmbz-table-wrap">
        <table class="rmbz-table">
            <thead>
                <tr>
                    <th>Data</th>
                    <th>Lançamento</th>
                    <th>Transição</th>
                    <th>Por</th>
                    <th>Motivo</th>
                </tr>
            </thead>
            <tbody>
            <?php if ( empty($rows) ): ?>
                <tr><td colspan="5" style="text-align:center; padding:30px; color:var(--rmbz-text-faint, #888);">Sem entradas ainda.</td></tr>
            <?php else: foreach ( $rows as $h ): ?>
                <tr>
                    <td style="white-space:nowrap; color:var(--rmbz-text-muted, #666);">
                        <?php echo esc_html( date('d/m/Y H:i', strtotime($h->created_at)) ); ?>
                    </td>
                    <td>
                        <?php if ( $h->release_title ): ?>
                            <a href="?page=rmbz-admin-distribution&tab=releases&view=detail&id=<?php echo (int) $h->release_id; ?>">
                                <strong><?php echo esc_html($h->release_title); ?></strong>
                            </a>
                        <?php else: ?>
                            <em>#<?php echo (int) $h->release_id; ?> (apagado)</em>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="rmbz-status-pill rmbz-status-<?php echo esc_attr($h->from_status); ?>"><?php echo esc_html($h->from_status ?: '—'); ?></span>
                        →
                        <span class="rmbz-status-pill rmbz-status-<?php echo esc_attr($h->to_status); ?>"><?php echo esc_html($h->to_status); ?></span>
                    </td>
                    <td><?php echo esc_html($h->changed_by ?: 'sistema'); ?></td>
                    <td style="max-width:300px; color:var(--rmbz-text-muted, #666); font-size:12px;">
                        <?php
                        $txt = $h->reason_text ?: '';
                        if ( ! empty($h->reason_code) ) $txt = '[' . $h->reason_code . '] ' . $txt;
                        echo esc_html($txt ?: '—');
                        ?>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <?php
    $total_pages = (int) ceil( $total / $per_page );
    if ( $total_pages > 1 ) {
        echo '<div class="tablenav" style="margin-top:15px;"><div class="tablenav-pages">';
        echo paginate_links([
            'base'    => add_query_arg('paged', '%#%'),
            'format'  => '',
            'current' => $paged,
            'total'   => $total_pages,
            'prev_text' => '‹',
            'next_text' => '›',
        ]);
        echo '</div></div>';
    }
}


/* ============================================================================
 * SPLIT HANDLERS
 * ============================================================================ */

function rmbz_admin_split_force_accept_handler() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');
    $split_id = (int) ($_POST['split_id'] ?? 0);
    if ( ! $split_id ) wp_die('ID inválido.');
    check_admin_referer('rmbz_split_action_' . $split_id);

    global $wpdb;
    $wpdb->update(
        $wpdb->prefix . 'rmbz_track_splits',
        [ 'invite_status' => 'accepted', 'accepted_at' => current_time('mysql') ],
        [ 'id' => $split_id ],
        [ '%s', '%s' ],
        [ '%d' ]
    );
    wp_safe_redirect( add_query_arg('msg', 'forced_accept', wp_get_referer() ?: admin_url('admin.php?page=rmbz-admin-distribution&tab=splits')) );
    exit;
}
add_action('admin_post_rmbz_split_force_accept', 'rmbz_admin_split_force_accept_handler');

function rmbz_admin_split_force_reject_handler() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');
    $split_id = (int) ($_POST['split_id'] ?? 0);
    if ( ! $split_id ) wp_die('ID inválido.');
    check_admin_referer('rmbz_split_action_' . $split_id);

    global $wpdb;
    $wpdb->update(
        $wpdb->prefix . 'rmbz_track_splits',
        [ 'invite_status' => 'rejected' ],
        [ 'id' => $split_id ],
        [ '%s' ],
        [ '%d' ]
    );
    wp_safe_redirect( add_query_arg('msg', 'forced_reject', wp_get_referer() ?: admin_url('admin.php?page=rmbz-admin-distribution&tab=splits')) );
    exit;
}
add_action('admin_post_rmbz_split_force_reject', 'rmbz_admin_split_force_reject_handler');

function rmbz_admin_split_delete_handler() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');
    $split_id = (int) ($_POST['split_id'] ?? 0);
    if ( ! $split_id ) wp_die('ID inválido.');
    check_admin_referer('rmbz_split_action_' . $split_id);

    global $wpdb;
    $wpdb->delete( $wpdb->prefix . 'rmbz_track_splits', [ 'id' => $split_id ], [ '%d' ] );
    wp_safe_redirect( add_query_arg('msg', 'deleted', wp_get_referer() ?: admin_url('admin.php?page=rmbz-admin-distribution&tab=splits')) );
    exit;
}
add_action('admin_post_rmbz_split_delete', 'rmbz_admin_split_delete_handler');
