<?php
// includes/admin/admin-views.php
if ( ! defined( 'ABSPATH' ) ) { exit; }

if ( ! function_exists( 'rmbz_safe_date_format' ) ) {
    function rmbz_safe_date_format( $date_string, $format = 'd/m/y H:i' ) {
        if ( empty( $date_string ) || $date_string === '0000-00-00 00:00:00' ) return '-';
        try { return date_format( date_create( $date_string ), $format ); } catch ( Exception $e ) { return '-'; }
    }
}

/**
 * CSS MODERNO GLOBAL PARA A ADMINISTRAÇÃO 1MZ
 *
 * Estilos partilhados pelas várias páginas do admin do plugin. As classes
 * `.rmbz-admin-wrap`, `.rmbz-card`, `.rmbz-table`, `.rmbz-badge` etc. são
 * usadas em todas as funções abaixo. Mantemo-las estáveis para não partir
 * páginas que não estão a ser tocadas neste redesign (Projetos, Depósitos,
 * Levantamentos, Cupões, etc.).
 *
 * == 1.5.192 — Material Design + fullbleed + histórico do artista ==
 *   - Hero header SEM gradient escuro (texto invisível em temas dark do WP)
 *     → background neutro + sombra Material Design
 *   - Layout fullbleed (max-width 1400px) com grid 3 colunas no detalhe
 *   - Novo card "Histórico do artista" com agregação de envios anteriores
 *   - Type scale Material 3 (Roboto), elevation 0/1/2/3 com sombras precisas
 *   - State layers (hover/focus) com ::before pseudo-elementos
 */
function rmbz_admin_modern_styles() {
    ?>
    <style>
        /* ─────────────────────────────────────────────────────────────────
         * CLASSES LEGADAS — mantidas para outras páginas no mesmo ficheiro
         * (Projetos, Cupões, Depósitos, etc.) que ainda usam estas.
         * ───────────────────────────────────────────────────────────────── */
        .rmbz-admin-wrap { max-width: 1200px; margin: 20px 20px 20px 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        .rmbz-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        .rmbz-header h1 { font-size: 28px; font-weight: 800; color: var(--wp-components-color-foreground, #1d2327); margin: 0; }
        .rmbz-header p { margin: 5px 0 0 0; color: #646970; font-size: 14px; }
        .rmbz-card { background: var(--rmbz-bg-card, #fff); border-radius: 12px; box-shadow: 0 2px 15px rgba(0,0,0,0.05); padding: 25px; border: 1px solid #e1e4e8; margin-bottom: 25px; }
        .rmbz-card-dark { background: var(--rmbz-bg-elevated, #111); color: var(--rmbz-text-on-color, #fff); border: 1px solid #333; }
        .rmbz-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        .rmbz-table th { background: #f6f7f9; color: #2c3338; padding: 15px; text-align: left; font-weight: 600; font-size: 13px; text-transform: uppercase; border-bottom: 2px solid #ddd; }
        .rmbz-table td { padding: 15px; border-bottom: 1px solid #f0f0f1; vertical-align: middle; font-size: 14px; color: #3c434a; }
        .rmbz-table tr:hover td { background: #fbfbfc; }
        .rmbz-badge { padding: 5px 10px; border-radius: 20px; font-size: 11px; font-weight: bold; text-transform: uppercase; }
        .bg-pending { background: #fff3cd; color: var(--rmbz-warning-strong, #856404); }
        .bg-success { background: #d4edda; color: #155724; }
        .bg-dark { background: var(--rmbz-bg-elevated, #222); color: var(--rmbz-brand, #f0b90b); }
        .rmbz-btn { display: inline-flex; align-items: center; justify-content: center; padding: 8px 16px; border-radius: 6px; font-size: 13px; font-weight: 600; text-decoration: none; cursor: pointer; transition: 0.2s; border: none; }
        .btn-gold { background: var(--rmbz-brand, #f0b90b); color: #000; box-shadow: 0 2px 5px rgba(240, 185, 11, 0.3); }
        .btn-gold:hover { background: var(--rmbz-brand-strong, #d4a000); color: #000; transform: translateY(-1px); }
        .btn-danger { background: var(--rmbz-danger, #ef4444); color: var(--rmbz-text-on-color, #fff); }
        .btn-danger:hover { background: var(--rmbz-danger-strong, #b91c1c); color: var(--rmbz-text-on-color, #fff); }
        .btn-outline { background: transparent; border: 1px solid #ccc; color: var(--rmbz-text-secondary, #555); }
        .btn-outline:hover { background: #f1f1f1; }
        .chat-container { background: #f9f9f9; border: 1px solid #ddd; border-radius: 8px; padding: 20px; max-height: 400px; overflow-y: auto; display: flex; flex-direction: column; gap: 15px; }
        .chat-bubble { max-width: 80%; padding: 12px 18px; border-radius: 12px; font-size: 14px; line-height: 1.5; position: relative; }
        .chat-artist { background: var(--rmbz-bg-card, #fff); border: 1px solid #eee; align-self: flex-start; border-bottom-left-radius: 2px; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
        .chat-admin { background: var(--rmbz-info-strong, #2563eb); color: var(--rmbz-text-on-color, #fff); align-self: flex-end; border-bottom-right-radius: 2px; box-shadow: 0 2px 5px rgba(34,113,177,0.2); }
        .chat-meta { font-size: 10px; opacity: 0.7; margin-bottom: 5px; display: block; font-weight: bold; }
        .chat-reply-box { display: flex; gap: 10px; margin-top: 15px; }
        .chat-reply-box input { flex: 1; padding: 12px; border: 1px solid #ccc; border-radius: 6px; }

        /* =====================================================================
         * MODERATION (Música Site + Vídeos Redes) — Material Design [1.5.192]
         *
         * Tokens MD3 inspirados (light surface):
         *   surface         #ffffff
         *   surface-cont    #f7f7fb   container baixo, lista de items
         *   surface-cont-hi #eceff5   elevation +1
         *   surface-cont-h+ #e1e4ed   elevation +2
         *   primary         #1a1a1f   ink
         *   on-primary      #f0b90b   acento 1MZ (gold)
         *   outline         #d8dae0
         *   outline-var     #ebecf0
         *   shadow          rgba(0,0,0,0.12)
         * ===================================================================== */
        .rmbz-mod-wrap {
            max-width: 1400px;
            margin: 16px 16px 32px 0;
            font-family: "Roboto", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            color: #1a1a1f;
            line-height: 1.5;
        }
        .rmbz-mod-wrap *,
        .rmbz-mod-wrap *::before,
        .rmbz-mod-wrap *::after { box-sizing: border-box; }

        /* ── Page header (sem fundos escuros — visível em qualquer tema WP) */
        .rmbz-mod-page-head {
            display: flex; justify-content: space-between; align-items: flex-end;
            gap: 20px; margin-bottom: 24px; flex-wrap: wrap;
        }
        .rmbz-mod-page-head h1 {
            font-size: 28px; font-weight: 700; margin: 0; color: #1a1a1f;
            display: flex; align-items: center; gap: 12px;
            letter-spacing: -0.02em;
        }
        .rmbz-mod-page-head .sub {
            margin: 4px 0 0 0; color: #5f6368; font-size: 14px;
        }
        .rmbz-mod-page-head .head-actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }

        /* ── Hero (no detalhe): MATERIAL — surface tonal, NUNCA gradient escuro */
        .rmbz-mod-hero {
            background: #f7f7fb;
            border: 1px solid #ebecf0;
            border-radius: 16px;
            padding: 20px 24px;
            margin-bottom: 20px;
            display: flex;
            gap: 18px;
            align-items: center;
            box-shadow: 0 1px 2px rgba(0,0,0,0.04);
        }
        .rmbz-mod-hero-thumb {
            width: 80px; height: 80px; border-radius: 14px; flex-shrink: 0;
            background: #1a1a1f center/cover no-repeat;
            border: 1px solid #ebecf0;
            display: flex; align-items: center; justify-content: center;
            font-size: 30px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.10);
            overflow: hidden;
        }
        .rmbz-mod-hero-thumb .icon { color: #f0b90b; }
        .rmbz-mod-hero-body { flex: 1; min-width: 0; }
        .rmbz-mod-hero-title {
            font-size: 22px; font-weight: 700; margin: 0 0 6px 0; color: #1a1a1f;
            letter-spacing: -0.01em; word-break: break-word;
        }
        .rmbz-mod-hero-meta {
            font-size: 13px; color: #5f6368; margin: 0;
            display: flex; gap: 14px; flex-wrap: wrap; align-items: center;
        }
        .rmbz-mod-hero-meta strong { color: #1a1a1f; font-weight: 500; }
        .rmbz-mod-hero-meta code {
            background: #fff; border: 1px solid #ebecf0;
            padding: 2px 8px; border-radius: 6px; font-size: 12px;
            font-family: "Roboto Mono", ui-monospace, monospace;
        }
        .rmbz-mod-hero .status-chip-big {
            display: inline-flex; align-items: center; gap: 8px;
            padding: 8px 14px; border-radius: 999px; font-size: 12px;
            font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;
            white-space: nowrap; align-self: flex-start;
        }

        /* ── Toolbar (lista) */
        .rmbz-mod-toolbar {
            display: flex; gap: 12px; align-items: center; flex-wrap: wrap;
            margin-bottom: 18px;
        }
        .rmbz-mod-search {
            flex: 1; min-width: 280px; position: relative;
            background: #f7f7fb; border: 1px solid #ebecf0; border-radius: 28px;
            transition: 0.15s;
        }
        .rmbz-mod-search:focus-within {
            background: #fff; border-color: #1a1a1f;
            box-shadow: 0 0 0 3px rgba(26,26,31,0.08);
        }
        .rmbz-mod-search input {
            width: 100%; padding: 12px 44px 12px 44px;
            border: none; background: transparent; font-size: 14px;
            color: #1a1a1f; outline: none;
        }
        .rmbz-mod-search::before {
            content: ""; position: absolute; left: 14px; top: 50%; transform: translateY(-50%);
            width: 18px; height: 18px;
            background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%235f6368'><path d='M15.5 14h-.79l-.28-.27a6.5 6.5 0 0 0 1.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 0 0-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 0 0 5.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'/></svg>") center/contain no-repeat;
        }
        .rmbz-mod-search-clear {
            position: absolute; right: 8px; top: 50%; transform: translateY(-50%);
            border: none; background: rgba(0,0,0,0.06); cursor: pointer;
            width: 28px; height: 28px; border-radius: 50%;
            font-size: 14px; color: #5f6368; padding: 0;
            display: none; align-items: center; justify-content: center;
        }
        .rmbz-mod-search-clear:hover { background: rgba(0,0,0,0.12); }

        .rmbz-mod-filters { display: flex; gap: 8px; flex-wrap: wrap; }
        .rmbz-mod-filter {
            display: inline-flex; align-items: center; gap: 6px;
            padding: 8px 16px;
            border: 1px solid #d8dae0; background: #fff; color: #1a1a1f;
            border-radius: 8px; font-size: 13px; font-weight: 500;
            cursor: pointer; transition: 0.15s; font-family: inherit;
            position: relative; overflow: hidden;
        }
        .rmbz-mod-filter::before {
            content: ""; position: absolute; inset: 0;
            background: currentColor; opacity: 0; transition: opacity 0.15s;
            pointer-events: none;
        }
        .rmbz-mod-filter:hover::before { opacity: 0.06; }
        .rmbz-mod-filter:focus-visible {
            outline: 2px solid #1a1a1f; outline-offset: 2px;
        }
        .rmbz-mod-filter.is-active {
            background: #1a1a1f; color: #fff; border-color: #1a1a1f;
        }
        .rmbz-mod-filter-count {
            background: rgba(0,0,0,0.08); color: inherit;
            padding: 1px 7px; border-radius: 999px; font-size: 11px;
            min-width: 20px; text-align: center; font-weight: 600;
        }
        .rmbz-mod-filter.is-active .rmbz-mod-filter-count { background: rgba(255,255,255,0.22); }
        .rmbz-mod-filter[data-status="pendente"] .rmbz-mod-filter-count {
            background: #f0b90b; color: #1a1a1f;
        }
        .rmbz-mod-filter[data-status="pendente"].is-active {
            background: #f0b90b; border-color: #f0b90b; color: #1a1a1f;
        }

        /* ── List of items (cards) */
        .rmbz-mod-list { display: grid; gap: 10px; }
        .rmbz-mod-row {
            display: grid;
            grid-template-columns: 72px minmax(0,1fr) auto auto;
            gap: 18px; align-items: center;
            padding: 14px 18px;
            background: #fff;
            border: 1px solid #ebecf0;
            border-radius: 12px;
            transition: box-shadow 0.15s, border-color 0.15s, transform 0.15s;
            cursor: pointer;
            position: relative;
        }
        .rmbz-mod-row:hover {
            border-color: #d8dae0;
            box-shadow: 0 4px 12px rgba(0,0,0,0.06), 0 1px 3px rgba(0,0,0,0.04);
            transform: translateY(-1px);
        }
        .rmbz-mod-row.is-focused {
            border-color: #1a1a1f;
            box-shadow: 0 0 0 3px rgba(26,26,31,0.10);
            outline: none;
        }
        .rmbz-mod-row.is-pending {
            background: #fffbeb;
            border-color: #fde68a;
        }
        .rmbz-mod-thumb {
            width: 72px; height: 72px; border-radius: 10px;
            background: #f7f7fb center/cover no-repeat;
            border: 1px solid #ebecf0;
            display: flex; align-items: center; justify-content: center;
            font-size: 28px; color: #5f6368; overflow: hidden;
        }
        .rmbz-mod-thumb img { width: 100%; height: 100%; object-fit: cover; }

        .rmbz-mod-info { min-width: 0; }
        .rmbz-mod-title {
            font-size: 15px; font-weight: 600; color: #1a1a1f;
            margin: 0 0 4px 0;
            overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
        }
        .rmbz-mod-sub {
            font-size: 13px; color: #5f6368;
            display: flex; gap: 12px; flex-wrap: wrap; align-items: center;
        }
        .rmbz-mod-sub .sep { opacity: 0.4; }
        .rmbz-mod-sub a { color: inherit; }

        /* ── Status chip (consistent everywhere) */
        .rmbz-mod-status {
            display: inline-flex; align-items: center; gap: 6px;
            padding: 5px 12px; border-radius: 999px;
            font-size: 11px; font-weight: 600;
            text-transform: uppercase; letter-spacing: 0.4px;
            white-space: nowrap;
            border: 1px solid transparent;
        }
        .rmbz-mod-status .dot {
            width: 7px; height: 7px; border-radius: 50%; background: currentColor;
        }
        .rmbz-mod-status--pendente      { background: #fef3c7; color: #92400e; border-color: #fde68a; }
        .rmbz-mod-status--aprovado      { background: #dbeafe; color: #1e40af; border-color: #bfdbfe; }
        .rmbz-mod-status--em_publicacao { background: #e0f2fe; color: #075985; border-color: #bae6fd; }
        .rmbz-mod-status--finalizado    { background: #d1fae5; color: #065f46; border-color: #a7f3d0; }
        .rmbz-mod-status--correcao      { background: #fed7aa; color: #9a3412; border-color: #fdba74; }
        .rmbz-mod-status--rejeitado     { background: #fee2e2; color: #991b1b; border-color: #fca5a5; }

        /* ── Icon buttons */
        .rmbz-mod-actions { display: flex; gap: 6px; align-items: center; }
        .rmbz-mod-icon-btn {
            display: inline-flex; align-items: center; justify-content: center;
            min-width: 38px; height: 38px; padding: 0 10px;
            border: 1px solid #ebecf0; background: #fff; color: #1a1a1f;
            border-radius: 10px; cursor: pointer; font-size: 16px;
            text-decoration: none; transition: 0.15s; font-family: inherit;
            position: relative; overflow: hidden;
        }
        .rmbz-mod-icon-btn::before {
            content: ""; position: absolute; inset: 0;
            background: currentColor; opacity: 0; transition: opacity 0.15s;
            pointer-events: none;
        }
        .rmbz-mod-icon-btn:hover::before { opacity: 0.06; }
        .rmbz-mod-icon-btn:focus-visible {
            outline: 2px solid #1a1a1f; outline-offset: 2px;
        }
        .rmbz-mod-icon-btn--filled {
            background: #f0b90b; border-color: #f0b90b; color: #1a1a1f;
            font-weight: 600;
        }
        .rmbz-mod-icon-btn--filled:hover {
            background: #d4a000; border-color: #d4a000;
            box-shadow: 0 2px 6px rgba(240,185,11,0.30);
        }
        .rmbz-mod-icon-btn.is-danger:hover {
            background: #fee2e2; border-color: #fca5a5; color: #991b1b;
        }
        .rmbz-mod-icon-btn.is-danger:hover::before { opacity: 0; }

        /* ── Empty state */
        .rmbz-mod-empty {
            padding: 60px 24px; text-align: center; color: #5f6368;
        }
        .rmbz-mod-empty-icon { font-size: 48px; opacity: 0.4; margin-bottom: 12px; }

        /* ── Keyboard hints */
        .rmbz-mod-kbdtip {
            font-size: 12px; color: #5f6368; margin-top: 16px;
            display: flex; gap: 16px; flex-wrap: wrap; align-items: center;
            padding-top: 14px; border-top: 1px solid #ebecf0;
        }
        .rmbz-mod-kbd {
            display: inline-block; padding: 2px 7px;
            background: #fff; border: 1px solid #d8dae0;
            border-bottom-width: 2px;
            border-radius: 5px; font-family: ui-monospace, "SF Mono", Menlo, monospace;
            font-size: 11px; color: #1a1a1f; font-weight: 600;
            min-width: 18px; text-align: center;
        }

        /* =====================================================================
         * DETAIL VIEW — 3 colunas (escala em ecrãs menores)
         * ===================================================================== */
        .rmbz-mod-detail {
            display: grid;
            grid-template-columns: minmax(0, 300px) minmax(0, 1fr) minmax(360px, 440px);
            gap: 18px;
            align-items: start;
        }
        @media (max-width: 1180px) {
            .rmbz-mod-detail { grid-template-columns: minmax(0, 1fr) minmax(360px, 440px); }
            .rmbz-mod-detail .col-files { grid-column: 1 / -1; }
        }
        @media (max-width: 820px) {
            .rmbz-mod-detail { grid-template-columns: 1fr; }
            .rmbz-mod-detail .col-files,
            .rmbz-mod-detail .col-meta,
            .rmbz-mod-detail .col-form { grid-column: 1 / -1; }
        }

        .rmbz-mod-section {
            background: #fff;
            border: 1px solid #ebecf0;
            border-radius: 14px;
            padding: 20px;
            margin-bottom: 14px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.03);
        }
        .rmbz-mod-section h3 {
            margin: 0 0 14px 0; font-size: 14px; font-weight: 600;
            color: #1a1a1f; display: flex; align-items: center; gap: 10px;
            text-transform: uppercase; letter-spacing: 0.5px;
        }
        .rmbz-mod-section h3 .sect-icon {
            width: 28px; height: 28px;
            display: inline-flex; align-items: center; justify-content: center;
            background: #f7f7fb; border-radius: 8px; font-size: 14px;
            border: 1px solid #ebecf0;
        }
        .rmbz-mod-section--accent {
            background: #fff;
            border-color: #1a1a1f;
            border-width: 1px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.06);
        }

        /* ── Meta rows */
        .rmbz-mod-meta-row {
            display: grid; grid-template-columns: 110px 1fr;
            gap: 12px; align-items: baseline;
            padding: 9px 0; border-bottom: 1px dashed #ebecf0;
        }
        .rmbz-mod-meta-row:last-child { border-bottom: none; }
        .rmbz-mod-meta-label {
            font-size: 11px; color: #5f6368; font-weight: 600;
            text-transform: uppercase; letter-spacing: 0.4px;
        }
        .rmbz-mod-meta-value { font-size: 14px; color: #1a1a1f; }

        /* ── Cover / preview */
        .rmbz-mod-cover {
            width: 100%; aspect-ratio: 1/1; max-height: 320px;
            object-fit: contain; background: #1a1a1f;
            border-radius: 12px; margin-bottom: 12px;
        }
        .rmbz-mod-cover-actions {
            display: flex; gap: 8px; margin-bottom: 16px; flex-wrap: wrap;
        }

        /* ── Audio box */
        .rmbz-mod-audio-box {
            background: #f7f7fb; border: 1px solid #ebecf0;
            border-radius: 12px; padding: 14px; margin-bottom: 10px;
        }
        .rmbz-mod-audio-box audio { width: 100%; height: 36px; }
        .rmbz-mod-audio-title {
            font-size: 13px; font-weight: 600; color: #1a1a1f;
            margin-bottom: 10px; display: flex; gap: 8px; align-items: center;
        }
        .rmbz-mod-audio-num {
            background: #1a1a1f; color: #f0b90b;
            padding: 2px 9px; border-radius: 999px;
            font-size: 11px; font-weight: 700; min-width: 24px; text-align: center;
        }
        .rmbz-mod-audio-actions {
            display: flex; gap: 6px; margin-top: 10px; flex-wrap: wrap;
        }

        /* ── Link rows */
        .rmbz-mod-link-row {
            display: flex; gap: 8px; align-items: center;
            padding: 10px 14px;
            background: #f7f7fb; border: 1px solid #ebecf0;
            border-radius: 10px; margin-bottom: 8px;
            transition: 0.15s;
        }
        .rmbz-mod-link-row:hover { background: #eceff5; border-color: #d8dae0; }
        .rmbz-mod-link-row .ico {
            font-size: 16px; flex-shrink: 0;
            width: 28px; height: 28px;
            display: flex; align-items: center; justify-content: center;
            background: #fff; border: 1px solid #ebecf0; border-radius: 7px;
        }
        .rmbz-mod-link-row a {
            flex: 1; color: #1a1a1f; font-weight: 500; font-size: 13px;
            text-decoration: none; overflow: hidden; text-overflow: ellipsis;
            white-space: nowrap;
        }
        .rmbz-mod-link-row a:hover { text-decoration: underline; color: #0b57d0; }

        /* =====================================================================
         * NEW: ARTIST HISTORY CARD  [1.5.192]
         * ===================================================================== */
        .rmbz-mod-artist-card {
            background: linear-gradient(180deg, #fff 0%, #f7f7fb 100%);
            border: 1px solid #ebecf0;
            border-radius: 14px;
            padding: 18px;
            margin-bottom: 14px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.03);
        }
        .rmbz-mod-artist-head {
            display: flex; gap: 14px; align-items: center; margin-bottom: 14px;
        }
        .rmbz-mod-artist-avatar {
            width: 52px; height: 52px; border-radius: 50%;
            background: linear-gradient(135deg, #1a1a1f, #3a3a45);
            color: #f0b90b;
            display: flex; align-items: center; justify-content: center;
            font-size: 20px; font-weight: 700;
            flex-shrink: 0;
            box-shadow: 0 2px 6px rgba(0,0,0,0.15);
        }
        .rmbz-mod-artist-id { flex: 1; min-width: 0; }
        .rmbz-mod-artist-name {
            font-size: 16px; font-weight: 600; color: #1a1a1f;
            margin: 0 0 2px 0;
            overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
        }
        .rmbz-mod-artist-contact {
            font-size: 12px; color: #5f6368;
            display: flex; gap: 6px; flex-wrap: wrap; align-items: center;
        }
        .rmbz-mod-artist-contact .pill {
            display: inline-flex; align-items: center; gap: 5px;
            padding: 3px 9px; background: #fff; border: 1px solid #ebecf0;
            border-radius: 999px;
            cursor: pointer; transition: 0.15s;
            font-family: ui-monospace, "SF Mono", monospace; font-size: 11px;
            color: #1a1a1f;
        }
        .rmbz-mod-artist-contact .pill:hover {
            background: #1a1a1f; color: #f0b90b; border-color: #1a1a1f;
        }
        .rmbz-mod-artist-stats {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 8px;
        }
        .rmbz-mod-stat {
            background: #fff; border: 1px solid #ebecf0; border-radius: 10px;
            padding: 10px 12px;
        }
        .rmbz-mod-stat-label {
            font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px;
            color: #5f6368; font-weight: 600; margin-bottom: 2px;
        }
        .rmbz-mod-stat-value {
            font-size: 18px; font-weight: 700; color: #1a1a1f; line-height: 1.2;
        }
        .rmbz-mod-stat-value .unit { font-size: 11px; font-weight: 500; color: #5f6368; margin-left: 3px; }
        .rmbz-mod-stat.is-good .rmbz-mod-stat-value { color: #065f46; }
        .rmbz-mod-stat.is-bad  .rmbz-mod-stat-value { color: #991b1b; }
        .rmbz-mod-stat.is-warn .rmbz-mod-stat-value { color: #9a3412; }
        .rmbz-mod-stat.is-new .rmbz-mod-stat-value::before {
            content: "★"; color: #f0b90b; margin-right: 4px; font-size: 14px;
        }

        .rmbz-mod-artist-bar {
            display: flex; gap: 2px; height: 6px; border-radius: 3px;
            overflow: hidden; margin-top: 12px; background: #ebecf0;
        }
        .rmbz-mod-artist-bar-seg { height: 100%; }
        .rmbz-mod-artist-bar-seg--good { background: #10b981; }
        .rmbz-mod-artist-bar-seg--warn { background: #f59e0b; }
        .rmbz-mod-artist-bar-seg--bad  { background: #ef4444; }
        .rmbz-mod-artist-bar-seg--pend { background: #1a1a1f; }
        .rmbz-mod-artist-bar-legend {
            display: flex; gap: 10px; flex-wrap: wrap;
            font-size: 11px; color: #5f6368; margin-top: 8px;
        }
        .rmbz-mod-artist-bar-legend span::before {
            content: ""; display: inline-block; width: 8px; height: 8px;
            border-radius: 2px; margin-right: 5px; vertical-align: middle;
        }
        .rmbz-mod-artist-bar-legend .lg-good::before { background: #10b981; }
        .rmbz-mod-artist-bar-legend .lg-warn::before { background: #f59e0b; }
        .rmbz-mod-artist-bar-legend .lg-bad::before  { background: #ef4444; }
        .rmbz-mod-artist-bar-legend .lg-pend::before { background: #1a1a1f; }

        /* ── Recent submissions list inside artist card */
        .rmbz-mod-artist-recent {
            margin-top: 14px; padding-top: 14px; border-top: 1px solid #ebecf0;
        }
        .rmbz-mod-artist-recent h4 {
            font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px;
            color: #5f6368; font-weight: 600; margin: 0 0 8px 0;
        }
        .rmbz-mod-recent-item {
            display: flex; gap: 10px; align-items: center;
            padding: 7px 0; font-size: 12px;
            border-bottom: 1px dashed #ebecf0;
            text-decoration: none; color: inherit;
        }
        .rmbz-mod-recent-item:last-child { border-bottom: none; }
        .rmbz-mod-recent-item:hover .rec-title { text-decoration: underline; }
        .rmbz-mod-recent-item .rec-title {
            flex: 1; min-width: 0;
            overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
            color: #1a1a1f; font-weight: 500;
        }
        .rmbz-mod-recent-item .rec-date {
            color: #5f6368; font-size: 11px;
        }

        /* =====================================================================
         * FORM (coluna direita do detalhe)
         * ===================================================================== */
        .rmbz-mod-status-pills {
            display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 18px;
        }
        .rmbz-mod-status-pill {
            display: inline-flex; align-items: center; gap: 7px;
            padding: 10px 14px;
            border: 1px solid #d8dae0; background: #fff;
            border-radius: 10px; font-size: 13px; font-weight: 500;
            cursor: pointer; transition: 0.15s; color: #1a1a1f;
            font-family: inherit;
            position: relative; overflow: hidden;
        }
        .rmbz-mod-status-pill::before {
            content: ""; position: absolute; inset: 0;
            background: currentColor; opacity: 0; transition: opacity 0.15s;
            pointer-events: none;
        }
        .rmbz-mod-status-pill:hover::before { opacity: 0.06; }
        .rmbz-mod-status-pill:focus-visible {
            outline: 2px solid #1a1a1f; outline-offset: 2px;
        }
        .rmbz-mod-status-pill.is-active {
            background: #1a1a1f; color: #fff; border-color: #1a1a1f;
        }
        .rmbz-mod-status-pill.is-active::before { opacity: 0; }
        .rmbz-mod-status-pill .kbdhint {
            opacity: 0.7; font-size: 10px;
            padding: 2px 5px; background: rgba(0,0,0,0.06);
            border-radius: 4px; font-family: ui-monospace, monospace;
            font-weight: 600;
        }
        .rmbz-mod-status-pill.is-active .kbdhint {
            background: rgba(255,255,255,0.15); color: #fff;
        }

        .rmbz-mod-input-group {
            display: flex; gap: 6px; align-items: stretch;
            margin-bottom: 14px;
        }
        .rmbz-mod-input-group input[type="url"],
        .rmbz-mod-input-group input[type="text"] {
            flex: 1; min-width: 0;
            padding: 11px 14px;
            border: 1px solid #d8dae0; background: #fff;
            border-radius: 10px; font-size: 14px;
            font-family: inherit; color: #1a1a1f;
        }
        .rmbz-mod-input-group input:focus {
            outline: none; border-color: #1a1a1f;
            box-shadow: 0 0 0 3px rgba(26,26,31,0.08);
        }
        .rmbz-mod-input-group .rmbz-mod-icon-btn {
            min-width: 42px; height: auto;
        }

        .rmbz-mod-field-label {
            display: flex; align-items: center; gap: 8px;
            font-weight: 600; font-size: 13px; color: #1a1a1f;
            margin-bottom: 6px;
        }
        .rmbz-mod-field-label .ico { font-size: 14px; }

        .rmbz-mod-rejbox {
            border-radius: 12px; padding: 16px; border: 1px solid;
            margin-bottom: 16px;
        }
        .rmbz-mod-rejbox--correcao  { background: #fff7ed; border-color: #fdba74; }
        .rmbz-mod-rejbox--rejeitado { background: #fef2f2; border-color: #fca5a5; }
        .rmbz-mod-fixflags {
            background: #fff; border: 1px solid #fbbf24;
            border-radius: 10px; padding: 12px; margin-bottom: 12px;
        }
        .rmbz-mod-fixflags-title {
            font-weight: 600; font-size: 11px; color: #92400e;
            margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.5px;
        }
        .rmbz-mod-fixflags label {
            display: inline-flex; align-items: center; gap: 6px;
            margin-right: 14px; font-size: 13px; cursor: pointer;
        }
        .rmbz-mod-textarea {
            width: 100%; padding: 12px 14px;
            border: 1px solid #d8dae0; background: #fff;
            border-radius: 10px; font-size: 14px;
            resize: vertical; font-family: inherit;
            min-height: 80px; color: #1a1a1f;
        }
        .rmbz-mod-textarea:focus {
            outline: none; border-color: #1a1a1f;
            box-shadow: 0 0 0 3px rgba(26,26,31,0.08);
        }

        .rmbz-mod-save-row {
            display: flex; gap: 10px; align-items: center; margin-top: 14px;
        }
        .rmbz-mod-save-btn {
            flex: 1; padding: 14px 22px;
            font-size: 14px; font-weight: 600;
            background: #1a1a1f; color: #fff;
            border: none; border-radius: 12px; cursor: pointer;
            transition: 0.15s;
            display: inline-flex; align-items: center; justify-content: center;
            gap: 8px;
            box-shadow: 0 1px 3px rgba(26,26,31,0.18), 0 1px 2px rgba(26,26,31,0.10);
            font-family: inherit;
            letter-spacing: 0.2px;
        }
        .rmbz-mod-save-btn:hover {
            background: #2c3338;
            box-shadow: 0 4px 12px rgba(26,26,31,0.24), 0 2px 4px rgba(26,26,31,0.12);
            transform: translateY(-1px);
        }
        .rmbz-mod-save-btn .ico {
            color: #f0b90b; font-size: 16px;
        }
        .rmbz-mod-save-hint { font-size: 11px; color: #5f6368; white-space: nowrap; }

        /* Back button */
        .rmbz-mod-back-btn {
            display: inline-flex; align-items: center; gap: 8px;
            padding: 9px 16px; border-radius: 999px;
            border: 1px solid #d8dae0; background: #fff; color: #1a1a1f;
            font-size: 13px; font-weight: 500; text-decoration: none;
            cursor: pointer; transition: 0.15s; font-family: inherit;
        }
        .rmbz-mod-back-btn:hover {
            background: #f7f7fb; border-color: #1a1a1f;
            color: #1a1a1f;
        }

        /* Toast */
        .rmbz-mod-toast {
            position: fixed; bottom: 28px; left: 50%; transform: translateX(-50%) translateY(12px);
            background: #1a1a1f; color: #fff;
            padding: 12px 22px; border-radius: 999px;
            font-size: 13px; font-weight: 500;
            box-shadow: 0 8px 24px rgba(0,0,0,0.22), 0 3px 8px rgba(0,0,0,0.14);
            z-index: 99999; opacity: 0;
            transition: opacity 0.20s, transform 0.20s;
            pointer-events: none;
        }
        .rmbz-mod-toast.is-show { opacity: 1; transform: translateX(-50%) translateY(0); }
        .rmbz-mod-toast .ico { color: #f0b90b; margin-right: 6px; }

        /* Big "Descarregar" button on cover */
        .rmbz-mod-btn-primary {
            display: inline-flex; align-items: center; justify-content: center;
            gap: 8px; padding: 11px 18px;
            background: #1a1a1f; color: #fff;
            border: none; border-radius: 10px;
            font-size: 13px; font-weight: 600; text-decoration: none;
            cursor: pointer; transition: 0.15s; font-family: inherit;
            box-shadow: 0 1px 3px rgba(26,26,31,0.18), 0 1px 2px rgba(26,26,31,0.10);
        }
        .rmbz-mod-btn-primary:hover {
            background: #2c3338; color: #fff;
            box-shadow: 0 4px 12px rgba(26,26,31,0.24), 0 2px 4px rgba(26,26,31,0.12);
            transform: translateY(-1px);
        }
        .rmbz-mod-btn-primary .ico { color: #f0b90b; font-size: 15px; }

        /* Campos modernos usados nos formulários do admin. */
        .rmbz-field { margin-bottom: 16px; }
        .rmbz-label {
            display: block; font-weight: 600; font-size: 13px;
            color: #1d2327; margin-bottom: 6px; letter-spacing: 0.2px;
        }
        .rmbz-input, .rmbz-select {
            width: 100%; padding: 11px 13px; font-size: 14px;
            border: 1.5px solid #dcdcde; border-radius: 8px;
            background: #fff; color: #1d2327; box-sizing: border-box;
            transition: border-color .15s, box-shadow .15s;
        }
        .rmbz-input:focus, .rmbz-select:focus {
            outline: none; border-color: #f0b90b;
            box-shadow: 0 0 0 3px rgba(240,185,11,0.18);
        }
        .rmbz-input::placeholder { color: #a7aaad; }
        .rmbz-hint { font-size: 11px; color: #787c82; margin-top: 5px; line-height: 1.4; }
        .rmbz-option-box {
            padding: 15px; border-radius: 10px; margin-bottom: 16px;
            background: #f6f7f7; border: 1px solid #e2e4e7;
        }
        .rmbz-option-box--green { border-left: 4px solid #2ecc71; }
        .rmbz-option-box--gold  { border-left: 4px solid #f0b90b; }
        .rmbz-btn-block { width: 100%; justify-content: center; padding: 13px; font-size: 15px; }

    </style>
    <script>function onemz_reject_prompt(u){let r=prompt("Motivo da rejeição:"); if(r&&r.trim()!=="") window.location.href=u+"&reason="+encodeURIComponent(r);}</script>
    <?php
}

/**
 * Helper partilhado: mapa estado → label/icon. Centralizado.
 */
function rmbz_mod_status_meta() {
    return [
        'pendente'      => [ 'label' => 'Em Análise',     'icon' => '⏱', 'short' => 'Pend.' ],
        'aprovado'      => [ 'label' => 'Aprovado',       'icon' => '✓',  'short' => 'OK'    ],
        'em_publicacao' => [ 'label' => 'Em Publicação',  'icon' => '⟳', 'short' => 'Pub.'  ],
        'finalizado'    => [ 'label' => 'Finalizado',     'icon' => '✦', 'short' => 'Fim'   ],
        'correcao'      => [ 'label' => 'Correção',       'icon' => '✎', 'short' => 'Corr.' ],
        'rejeitado'     => [ 'label' => 'Rejeitado',      'icon' => '✕', 'short' => 'Rej.'  ],
    ];
}

/**
 * Calcula histórico/contexto do artista para a sidebar do detalhe.
 *
 * Faz UMA query agregada à tabela rmbz_artist_submissions agrupada por estado,
 * mais uma query rápida para listar as últimas 3 submissões. Resultado:
 *
 *   [
 *     'total'      => int,
 *     'publicados' => int,
 *     'aprovados'  => int,
 *     'em_pub'     => int,
 *     'correcao'   => int,
 *     'rejeitados' => int,
 *     'pendentes'  => int,
 *     'taxa_pub'   => float (0..100) — % publicados+aprovados sobre total
 *     'first_at'   => string|null  — data da primeira submissão
 *     'last_at'    => string|null  — última submissão
 *     'recent'     => array         — últimas 3 (id, title, status, date)
 *   ]
 *
 * Inclui o registo actual nas contagens (o admin vê o total incluindo este).
 * Scope: scenario_type fornecido (Publicação Site ou Redes Sociais).
 */
function rmbz_mod_get_artist_history( $telemovel, $scenario_type, $exclude_id = 0 ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_artist_submissions';
    $out = [
        'total' => 0, 'publicados' => 0, 'aprovados' => 0, 'em_pub' => 0,
        'correcao' => 0, 'rejeitados' => 0, 'pendentes' => 0, 'taxa_pub' => 0.0,
        'first_at' => null, 'last_at' => null, 'recent' => [],
    ];
    if ( empty( $telemovel ) ) return $out;

    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT review_status, COUNT(*) c FROM {$t}
         WHERE artist_telemovel = %s AND scenario_type = %s
         GROUP BY review_status",
        $telemovel, $scenario_type
    ) );
    if ( $rows ) {
        foreach ( $rows as $r ) {
            $n = (int) $r->c;
            $out['total'] += $n;
            switch ( $r->review_status ) {
                case 'finalizado':    $out['publicados'] = $n; break;
                case 'aprovado':      $out['aprovados']  = $n; break;
                case 'em_publicacao': $out['em_pub']     = $n; break;
                case 'correcao':      $out['correcao']   = $n; break;
                case 'rejeitado':     $out['rejeitados'] = $n; break;
                case 'pendente':      $out['pendentes']  = $n; break;
            }
        }
    }

    $dates = $wpdb->get_row( $wpdb->prepare(
        "SELECT MIN(submission_date) AS first_at, MAX(submission_date) AS last_at
         FROM {$t}
         WHERE artist_telemovel = %s AND scenario_type = %s",
        $telemovel, $scenario_type
    ) );
    if ( $dates ) {
        $out['first_at'] = $dates->first_at;
        $out['last_at']  = $dates->last_at;
    }

    if ( $out['total'] > 0 ) {
        $ok = $out['publicados'] + $out['aprovados'] + $out['em_pub'];
        $out['taxa_pub'] = round( ( $ok / $out['total'] ) * 100, 1 );
    }

    // Últimas 3 submissões (excluindo a actual)
    $where_excl = $exclude_id > 0 ? $wpdb->prepare( "AND id != %d", $exclude_id ) : '';
    $recent = $wpdb->get_results( $wpdb->prepare(
        "SELECT id, music_title, review_status, submission_date
         FROM {$t}
         WHERE artist_telemovel = %s AND scenario_type = %s {$where_excl}
         ORDER BY submission_date DESC LIMIT 3",
        $telemovel, $scenario_type
    ) );
    $out['recent'] = $recent ?: [];

    return $out;
}

/**
 * Renderiza o card de "Histórico do artista" (sidebar do detalhe).
 *
 * Recebe os dados básicos do artista + scenario_type para query agregada.
 * Retorna HTML (echo).
 */
function rmbz_mod_render_artist_card( $artist_nm, $telemovel, $user_email, $scenario_type, $current_sub_id, $current_page_slug ) {
    $hist = rmbz_mod_get_artist_history( $telemovel, $scenario_type, $current_sub_id );

    // Iniciais do nome para o avatar
    $initials = '';
    $words = preg_split( '/\s+/', trim( (string) $artist_nm ) );
    foreach ( array_slice( $words, 0, 2 ) as $w ) {
        if ( $w !== '' ) $initials .= mb_strtoupper( mb_substr( $w, 0, 1 ) );
    }
    if ( $initials === '' ) $initials = '?';

    $status_meta = rmbz_mod_status_meta();

    // Determinar se é "primeiro envio" (total inclui o actual; se total == 1 é novato)
    $is_new = ( $hist['total'] <= 1 );
    ?>
    <div class="rmbz-mod-artist-card">
        <div class="rmbz-mod-artist-head">
            <div class="rmbz-mod-artist-avatar"><?php echo esc_html( $initials ); ?></div>
            <div class="rmbz-mod-artist-id">
                <p class="rmbz-mod-artist-name"><?php echo esc_html( $artist_nm ?: '—' ); ?></p>
                <div class="rmbz-mod-artist-contact">
                    <?php if ( $telemovel ): ?>
                        <span class="pill" data-copy="<?php echo esc_attr( $telemovel ); ?>" title="Clica para copiar">📱 <?php echo esc_html( $telemovel ); ?></span>
                    <?php endif; ?>
                    <?php if ( $user_email && strpos( (string) $user_email, '@1mz.local' ) === false ): ?>
                        <span class="pill" data-copy="<?php echo esc_attr( $user_email ); ?>" title="Clica para copiar">✉ <?php echo esc_html( $user_email ); ?></span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="rmbz-mod-artist-stats">
            <?php if ( $is_new ): ?>
                <div class="rmbz-mod-stat is-new" style="grid-column: 1 / -1;">
                    <div class="rmbz-mod-stat-label">Primeira submissão</div>
                    <div class="rmbz-mod-stat-value">Novo artista</div>
                </div>
            <?php else: ?>
                <div class="rmbz-mod-stat">
                    <div class="rmbz-mod-stat-label">Total enviado</div>
                    <div class="rmbz-mod-stat-value"><?php echo (int) $hist['total']; ?><span class="unit">submissões</span></div>
                </div>
                <div class="rmbz-mod-stat is-good">
                    <div class="rmbz-mod-stat-label">Taxa de aprovação</div>
                    <div class="rmbz-mod-stat-value"><?php echo number_format( $hist['taxa_pub'], 1 ); ?><span class="unit">%</span></div>
                </div>
                <?php if ( $hist['publicados'] > 0 ): ?>
                <div class="rmbz-mod-stat is-good">
                    <div class="rmbz-mod-stat-label">Publicadas</div>
                    <div class="rmbz-mod-stat-value"><?php echo (int) $hist['publicados']; ?></div>
                </div>
                <?php endif; ?>
                <?php if ( $hist['pendentes'] > 0 ): ?>
                <div class="rmbz-mod-stat">
                    <div class="rmbz-mod-stat-label">Pendentes</div>
                    <div class="rmbz-mod-stat-value"><?php echo (int) $hist['pendentes']; ?></div>
                </div>
                <?php endif; ?>
                <?php if ( $hist['correcao'] > 0 ): ?>
                <div class="rmbz-mod-stat is-warn">
                    <div class="rmbz-mod-stat-label">Em correção</div>
                    <div class="rmbz-mod-stat-value"><?php echo (int) $hist['correcao']; ?></div>
                </div>
                <?php endif; ?>
                <?php if ( $hist['rejeitados'] > 0 ): ?>
                <div class="rmbz-mod-stat is-bad">
                    <div class="rmbz-mod-stat-label">Rejeitadas</div>
                    <div class="rmbz-mod-stat-value"><?php echo (int) $hist['rejeitados']; ?></div>
                </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <?php if ( ! $is_new && $hist['total'] > 0 ):
            // Barra de proporção
            $t = max( 1, (int) $hist['total'] );
            $w_good = ( $hist['publicados'] / $t ) * 100;
            $w_ok   = ( ( $hist['aprovados'] + $hist['em_pub'] ) / $t ) * 100;
            $w_warn = ( $hist['correcao'] / $t ) * 100;
            $w_bad  = ( $hist['rejeitados'] / $t ) * 100;
            $w_pend = ( $hist['pendentes'] / $t ) * 100;
        ?>
        <div class="rmbz-mod-artist-bar" title="Distribuição de submissões anteriores">
            <?php if ( $w_good > 0 ): ?><div class="rmbz-mod-artist-bar-seg rmbz-mod-artist-bar-seg--good" style="width: <?php echo number_format( $w_good + $w_ok, 2 ); ?>%;"></div><?php endif; ?>
            <?php if ( $w_warn > 0 ): ?><div class="rmbz-mod-artist-bar-seg rmbz-mod-artist-bar-seg--warn" style="width: <?php echo number_format( $w_warn, 2 ); ?>%;"></div><?php endif; ?>
            <?php if ( $w_bad  > 0 ): ?><div class="rmbz-mod-artist-bar-seg rmbz-mod-artist-bar-seg--bad"  style="width: <?php echo number_format( $w_bad,  2 ); ?>%;"></div><?php endif; ?>
            <?php if ( $w_pend > 0 ): ?><div class="rmbz-mod-artist-bar-seg rmbz-mod-artist-bar-seg--pend" style="width: <?php echo number_format( $w_pend, 2 ); ?>%;"></div><?php endif; ?>
        </div>
        <div class="rmbz-mod-artist-bar-legend">
            <?php if ( $hist['publicados'] + $hist['aprovados'] + $hist['em_pub'] > 0 ): ?><span class="lg-good">OK <?php echo (int)( $hist['publicados'] + $hist['aprovados'] + $hist['em_pub'] ); ?></span><?php endif; ?>
            <?php if ( $hist['correcao'] > 0 ): ?><span class="lg-warn">Correção <?php echo (int) $hist['correcao']; ?></span><?php endif; ?>
            <?php if ( $hist['rejeitados'] > 0 ): ?><span class="lg-bad">Rejeit. <?php echo (int) $hist['rejeitados']; ?></span><?php endif; ?>
            <?php if ( $hist['pendentes'] > 0 ): ?><span class="lg-pend">Pend. <?php echo (int) $hist['pendentes']; ?></span><?php endif; ?>
        </div>
        <?php endif; ?>

        <?php if ( ! empty( $hist['recent'] ) ): ?>
        <div class="rmbz-mod-artist-recent">
            <h4>Outras submissões recentes</h4>
            <?php foreach ( $hist['recent'] as $r ):
                $st  = $r->review_status ?: 'pendente';
                $sm  = $status_meta[ $st ] ?? $status_meta['pendente'];
                $url = admin_url( 'admin.php?page=' . $current_page_slug . '&action=edit&id=' . (int) $r->id );
            ?>
                <a class="rmbz-mod-recent-item" href="<?php echo esc_url( $url ); ?>">
                    <span class="rmbz-mod-status rmbz-mod-status--<?php echo esc_attr( $st ); ?>" style="font-size:10px; padding:2px 8px;">
                        <span class="dot"></span><?php echo esc_html( $sm['short'] ); ?>
                    </span>
                    <span class="rec-title"><?php echo esc_html( $r->music_title ); ?></span>
                    <span class="rec-date"><?php echo esc_html( date( 'd/m/y', strtotime( $r->submission_date ) ) ); ?></span>
                </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * --------------------------------------------------------------------------
 * 1. PÁGINA: GESTÃO DE MÚSICAS (SITE)                       [1.5.192 redesign]
 * --------------------------------------------------------------------------
 */
function rmbz_pagina_envios_site() {
    rmbz_admin_modern_styles();
    global $wpdb;
    $table_sub = $wpdb->prefix . 'rmbz_artist_submissions';
    $table_wal = $wpdb->prefix . 'rmbz_wallets';

    // ── DETALHE ─────────────────────────────────────────────────────────
    if ( isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id']) ) {
        $sub_id = absint($_GET['id']);
        $envio = $wpdb->get_row( $wpdb->prepare(
            "SELECT s.*, w.user_nome, w.user_email
             FROM {$table_sub} s
             LEFT JOIN {$table_wal} w ON s.artist_telemovel = w.user_telemovel
             WHERE s.id = %d", $sub_id
        ) );
        if ( !$envio ) { echo '<div class="rmbz-mod-wrap">Envio não encontrado.</div>'; return; }

        $extra      = !empty($envio->extra_data) ? json_decode($envio->extra_data, true) : [];
        $cover_url  = !empty($extra['cover_image']) ? $extra['cover_image'] : '';
        $is_album   = isset($extra['is_album']) && $extra['is_album'] == true;
        $artist_nm  = $extra['artist_name'] ?? $envio->user_nome ?? 'Artista';
        $status_meta = rmbz_mod_status_meta();
        $cur_status = $envio->review_status ?: 'pendente';

        rmbz_render_envio_site_detail( $sub_id, $envio, $extra, $cover_url, $is_album, $artist_nm, $status_meta, $cur_status );
        return;
    }

    // ── LISTA ───────────────────────────────────────────────────────────
    $audicoes = $wpdb->get_results( "SELECT s.*, w.user_nome FROM {$table_sub} s LEFT JOIN {$table_wal} w ON s.artist_telemovel = w.user_telemovel WHERE s.scenario_type = 'Publicação Site' ORDER BY s.submission_date DESC" );

    $status_meta = rmbz_mod_status_meta();
    $counts = [ 'all' => count( $audicoes ) ];
    foreach ( array_keys( $status_meta ) as $k ) $counts[ $k ] = 0;
    foreach ( $audicoes as $a ) {
        $s = $a->review_status ?: 'pendente';
        if ( isset( $counts[ $s ] ) ) $counts[ $s ]++;
    }
    ?>
    <div class="rmbz-mod-wrap">
        <div class="rmbz-mod-page-head">
            <div>
                <h1>🎵 Gestão de Músicas (Site)</h1>
                <p class="sub">Acompanhe todos os envios de músicas e álbuns, desde a análise até à publicação final.</p>
            </div>
        </div>

        <div class="rmbz-mod-section">
            <div class="rmbz-mod-toolbar">
                <div class="rmbz-mod-search">
                    <input type="text" id="rmbz-mod-q" placeholder="Pesquisar por artista, título ou género…" autocomplete="off">
                    <button type="button" class="rmbz-mod-search-clear" id="rmbz-mod-q-clear" aria-label="Limpar pesquisa">×</button>
                </div>
                <div class="rmbz-mod-filters" role="tablist" aria-label="Filtrar por estado">
                    <button type="button" class="rmbz-mod-filter is-active" data-status="all">
                        Todos <span class="rmbz-mod-filter-count"><?php echo (int)$counts['all']; ?></span>
                    </button>
                    <?php foreach ( $status_meta as $key => $meta ): ?>
                        <button type="button" class="rmbz-mod-filter" data-status="<?php echo esc_attr($key); ?>">
                            <?php echo esc_html( $meta['label'] ); ?>
                            <span class="rmbz-mod-filter-count"><?php echo (int)$counts[$key]; ?></span>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <?php if ( empty( $audicoes ) ) : ?>
                <div class="rmbz-mod-empty">
                    <div class="rmbz-mod-empty-icon">🎼</div>
                    <p style="margin:0;font-weight:600;font-size:15px;">Ainda não há envios de música.</p>
                    <p style="margin:5px 0 0 0;font-size:13px;">Quando um artista submeter uma música via app ou site, aparece aqui.</p>
                </div>
            <?php else : ?>
                <div class="rmbz-mod-list" id="rmbz-mod-list" role="list">
                    <?php foreach ( $audicoes as $item ) :
                        $extra      = !empty($item->extra_data) ? json_decode($item->extra_data, true) : [];
                        $st         = $item->review_status ?: 'pendente';
                        $meta       = $status_meta[$st] ?? $status_meta['pendente'];
                        $is_album   = isset($extra['is_album']) && $extra['is_album'] == true;
                        $cover      = !empty($extra['cover_image']) ? $extra['cover_image'] : '';
                        $artist_nm  = $extra['artist_name'] ?? $item->user_nome ?? '—';
                        $genre      = $item->music_genre ?? '';
                        $published  = $extra['published_url'] ?? '';
                        $audio_url  = $item->music_file_url ?? '';
                        $row_search = strtolower( implode( ' ', array_filter( [ $item->music_title, $artist_nm, $genre ] ) ) );
                        $edit_url   = admin_url('admin.php?page=rmbz-envios-site&action=edit&id='.$item->id);
                        $delete_url = wp_nonce_url(admin_url('admin-post.php?action=onemz_delete_submission&sub_id='.$item->id), 'onemz_delete_nonce_'.$item->id);
                    ?>
                    <div class="rmbz-mod-row <?php echo $st === 'pendente' ? 'is-pending' : ''; ?>"
                         role="listitem"
                         tabindex="0"
                         data-status="<?php echo esc_attr($st); ?>"
                         data-search="<?php echo esc_attr($row_search); ?>"
                         data-href="<?php echo esc_url($edit_url); ?>">
                        <div class="rmbz-mod-thumb">
                            <?php if ( $cover ): ?>
                                <img src="<?php echo esc_url($cover); ?>" alt="" loading="lazy">
                            <?php else: ?>
                                <?php echo $is_album ? '💿' : '🎵'; ?>
                            <?php endif; ?>
                        </div>
                        <div class="rmbz-mod-info">
                            <p class="rmbz-mod-title"><?php echo esc_html($item->music_title); ?>
                                <?php if ($is_album): ?><span class="rmbz-badge bg-dark" style="margin-left:6px;font-size:9px;padding:2px 6px;">ÁLBUM</span><?php endif; ?>
                            </p>
                            <div class="rmbz-mod-sub">
                                <span>👤 <?php echo esc_html($artist_nm); ?></span>
                                <?php if ($genre): ?><span class="sep">·</span><span><?php echo esc_html($genre); ?></span><?php endif; ?>
                                <span class="sep">·</span><span><?php echo esc_html( date('d/m/Y', strtotime($item->submission_date)) ); ?></span>
                                <?php if ($published): ?>
                                    <span class="sep">·</span><a href="<?php echo esc_url($published); ?>" target="_blank" rel="noopener" style="color:#10b981;font-weight:600;text-decoration:none;" onclick="event.stopPropagation();">✓ Post publicado</a>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div>
                            <span class="rmbz-mod-status rmbz-mod-status--<?php echo esc_attr($st); ?>">
                                <span class="dot"></span><?php echo esc_html( $meta['label'] ); ?>
                            </span>
                        </div>
                        <div class="rmbz-mod-actions" onclick="event.stopPropagation();">
                            <?php if ( $cover ): ?>
                                <a href="<?php echo esc_url($cover); ?>"
                                   download="capa-<?php echo esc_attr( sanitize_file_name( $item->music_title ) ); ?>.jpg"
                                   class="rmbz-mod-icon-btn"
                                   title="Descarregar capa"
                                   aria-label="Descarregar capa">🖼️</a>
                            <?php endif; ?>
                            <?php if ( ! $is_album && $audio_url ): ?>
                                <a href="<?php echo esc_url($audio_url); ?>"
                                   download="<?php echo esc_attr( sanitize_file_name( $item->music_title ) ); ?>.mp3"
                                   class="rmbz-mod-icon-btn"
                                   title="Descarregar áudio"
                                   aria-label="Descarregar áudio">🎧</a>
                            <?php endif; ?>
                            <a href="<?php echo esc_url($edit_url); ?>"
                               class="rmbz-mod-icon-btn rmbz-mod-icon-btn--filled"
                               title="Gerir envio"
                               aria-label="Gerir envio">⚙️</a>
                            <a href="<?php echo esc_url($delete_url); ?>"
                               class="rmbz-mod-icon-btn is-danger"
                               title="Apagar"
                               aria-label="Apagar"
                               onclick="return confirm('Apagar definitivamente este envio?\nEsta ação é irreversível.');">🗑</a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="rmbz-mod-kbdtip">
                    <span><span class="rmbz-mod-kbd">↑</span> <span class="rmbz-mod-kbd">↓</span> navegar</span>
                    <span><span class="rmbz-mod-kbd">Enter</span> abrir</span>
                    <span><span class="rmbz-mod-kbd">/</span> pesquisar</span>
                    <span><span class="rmbz-mod-kbd">Esc</span> limpar pesquisa</span>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php rmbz_mod_list_script(); ?>
    <?php
}

/**
 * Renderiza o detalhe (edit) da submissão de Música (Site).
 */
function rmbz_render_envio_site_detail( $sub_id, $envio, $extra, $cover_url, $is_album, $artist_nm, $status_meta, $cur_status ) {
    $back_url = admin_url('admin.php?page=rmbz-envios-site');
    $user_email = $envio->user_email ?? '';
    $cur_meta = $status_meta[ $cur_status ] ?? $status_meta['pendente'];
    ?>
    <div class="rmbz-mod-wrap">
        <div class="rmbz-mod-page-head">
            <div>
                <h1 style="font-size: 22px;"><?php echo $is_album ? '💿' : '🎧'; ?> Gerir Publicação</h1>
                <p class="sub">Volta atrás com <span class="rmbz-mod-kbd">Esc</span> · Guarda com <span class="rmbz-mod-kbd">Ctrl</span>+<span class="rmbz-mod-kbd">S</span></p>
            </div>
            <div class="head-actions">
                <a href="<?php echo esc_url($back_url); ?>" class="rmbz-mod-back-btn" id="rmbz-mod-back">← Voltar à lista</a>
            </div>
        </div>

        <div class="rmbz-mod-hero">
            <div class="rmbz-mod-hero-thumb" style="<?php echo $cover_url ? 'background-image:url(' . esc_url($cover_url) . ');' : ''; ?>">
                <?php if ( ! $cover_url ): ?>
                    <span class="icon"><?php echo $is_album ? '💿' : '🎵'; ?></span>
                <?php endif; ?>
            </div>
            <div class="rmbz-mod-hero-body">
                <h2 class="rmbz-mod-hero-title"><?php echo esc_html($envio->music_title); ?>
                    <?php if ($is_album): ?><span class="rmbz-badge bg-dark" style="margin-left:8px;font-size:10px;vertical-align:middle;">💿 ÁLBUM</span><?php endif; ?>
                </h2>
                <p class="rmbz-mod-hero-meta">
                    <span>Por <strong><?php echo esc_html($artist_nm); ?></strong></span>
                    <span>· Submetido <strong><?php echo esc_html( date('d/m/Y H:i', strtotime($envio->submission_date)) ); ?></strong></span>
                    <code><?php echo esc_html($envio->artist_telemovel); ?></code>
                </p>
            </div>
            <span class="status-chip-big rmbz-mod-status--<?php echo esc_attr($cur_status); ?>">
                <span class="dot"></span><?php echo esc_html( $cur_meta['label'] ); ?>
            </span>
        </div>

        <div class="rmbz-mod-detail">
            <!-- COLUNA 1: HISTÓRICO DO ARTISTA + LINKS DO ARTISTA -->
            <div class="col-meta">
                <?php
                rmbz_mod_render_artist_card(
                    $artist_nm,
                    $envio->artist_telemovel,
                    $user_email,
                    'Publicação Site',
                    $sub_id,
                    'rmbz-envios-site'
                );

                $has_video = ($extra['has_video'] ?? '') === 'sim';
                $on_plats  = ($extra['on_platforms'] ?? '') === 'sim';
                $any_link  = !empty($extra['youtube_link']) || !empty($extra['spotify_link']) || !empty($extra['apple_link']) || !empty($extra['social_link']);
                if ( $any_link ):
                ?>
                <div class="rmbz-mod-section">
                    <h3><span class="sect-icon">🔗</span> Presença do artista</h3>

                    <?php if ( ! empty( $extra['youtube_link'] ) ): ?>
                        <div class="rmbz-mod-link-row">
                            <span class="ico">▶️</span>
                            <a href="<?php echo esc_url($extra['youtube_link']); ?>" target="_blank" rel="noopener"><?php echo esc_html($extra['youtube_link']); ?></a>
                            <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($extra['youtube_link']); ?>" title="Copiar">📋</button>
                        </div>
                    <?php endif; ?>
                    <?php if ( ! empty( $extra['spotify_link'] ) ): ?>
                        <div class="rmbz-mod-link-row">
                            <span class="ico">🟢</span>
                            <a href="<?php echo esc_url($extra['spotify_link']); ?>" target="_blank" rel="noopener"><?php echo esc_html($extra['spotify_link']); ?></a>
                            <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($extra['spotify_link']); ?>" title="Copiar">📋</button>
                        </div>
                    <?php endif; ?>
                    <?php if ( ! empty( $extra['apple_link'] ) ): ?>
                        <div class="rmbz-mod-link-row">
                            <span class="ico">🍎</span>
                            <a href="<?php echo esc_url($extra['apple_link']); ?>" target="_blank" rel="noopener"><?php echo esc_html($extra['apple_link']); ?></a>
                            <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($extra['apple_link']); ?>" title="Copiar">📋</button>
                        </div>
                    <?php endif; ?>
                    <?php if ( ! empty( $extra['social_link'] ) ): ?>
                        <div class="rmbz-mod-link-row">
                            <span class="ico">👤</span>
                            <a href="<?php echo esc_url($extra['social_link']); ?>" target="_blank" rel="noopener"><?php echo esc_html($extra['social_link']); ?></a>
                            <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($extra['social_link']); ?>" title="Copiar">📋</button>
                        </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- COLUNA 2: FICHEIROS (capa + áudio + ficha) -->
            <div class="col-files">
                <div class="rmbz-mod-section">
                    <h3><span class="sect-icon">📋</span> Ficha da obra</h3>

                    <?php if ($cover_url): ?>
                        <img src="<?php echo esc_url($cover_url); ?>" class="rmbz-mod-cover" alt="Capa">
                        <div class="rmbz-mod-cover-actions">
                            <a href="<?php echo esc_url($cover_url); ?>"
                               download="capa-<?php echo esc_attr( sanitize_file_name( $envio->music_title ) ); ?>.jpg"
                               class="rmbz-mod-btn-primary"
                               style="flex:1;">
                                <span class="ico">📥</span> Descarregar capa
                            </a>
                            <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($cover_url); ?>" title="Copiar URL da capa">🔗</button>
                        </div>
                    <?php endif; ?>

                    <div class="rmbz-mod-meta-row">
                        <span class="rmbz-mod-meta-label">Género</span>
                        <span class="rmbz-mod-meta-value"><?php echo esc_html($envio->music_genre ?: '—'); ?></span>
                    </div>
                    <div class="rmbz-mod-meta-row">
                        <span class="rmbz-mod-meta-label">Feat</span>
                        <span class="rmbz-mod-meta-value"><?php echo esc_html($extra['feat_name'] ?? '—'); ?></span>
                    </div>
                    <div class="rmbz-mod-meta-row">
                        <span class="rmbz-mod-meta-label">Data desejada</span>
                        <span class="rmbz-mod-meta-value"><?php echo esc_html($extra['release_date'] ?? '—'); ?></span>
                    </div>
                    <div class="rmbz-mod-meta-row" style="align-items:flex-start;">
                        <span class="rmbz-mod-meta-label">Descrição</span>
                        <span class="rmbz-mod-meta-value" style="white-space:pre-wrap;line-height:1.5;"><?php echo esc_html($extra['description'] ?? '—'); ?></span>
                    </div>
                </div>

                <div class="rmbz-mod-section">
                    <h3><span class="sect-icon">🎵</span> Áudio</h3>

                    <?php if ($is_album && !empty($extra['album_tracks'])): ?>
                        <?php foreach ($extra['album_tracks'] as $idx => $track): ?>
                            <div class="rmbz-mod-audio-box">
                                <div class="rmbz-mod-audio-title">
                                    <span class="rmbz-mod-audio-num"><?php echo (int)($idx + 1); ?></span>
                                    <?php echo esc_html($track['title'] ?? 'Faixa ' . ($idx+1)); ?>
                                </div>
                                <audio controls preload="none">
                                    <source src="<?php echo esc_url($track['url']); ?>">
                                </audio>
                                <div class="rmbz-mod-audio-actions">
                                    <a href="<?php echo esc_url($track['url']); ?>"
                                       download="<?php echo esc_attr( sanitize_file_name( ($track['title'] ?? 'faixa-' . ($idx+1)) ) ); ?>.mp3"
                                       class="rmbz-mod-icon-btn">📥 Áudio</a>
                                    <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($track['url']); ?>" title="Copiar URL">🔗</button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php elseif ( ! empty( $envio->music_file_url ) ): ?>
                        <div class="rmbz-mod-audio-box">
                            <audio controls preload="none">
                                <source src="<?php echo esc_url($envio->music_file_url); ?>">
                            </audio>
                            <div class="rmbz-mod-audio-actions">
                                <a href="<?php echo esc_url($envio->music_file_url); ?>"
                                   download="<?php echo esc_attr( sanitize_file_name( $envio->music_title ) ); ?>.mp3"
                                   class="rmbz-mod-btn-primary">
                                    <span class="ico">📥</span> Descarregar áudio
                                </a>
                                <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($envio->music_file_url); ?>" title="Copiar URL">🔗</button>
                            </div>
                        </div>
                    <?php else: ?>
                        <p style="color:#9ca3af;font-size:13px;margin:0;">Sem ficheiro de áudio anexado.</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- COLUNA 3: GESTÃO -->
            <div class="col-form">
                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>" id="rmbz-mod-form" class="rmbz-mod-section rmbz-mod-section--accent" style="margin-bottom:0;">
                    <h3><span class="sect-icon">⚙️</span> Gestão e publicação</h3>

                    <input type="hidden" name="action" value="onemz_admin_update_site_submission">
                    <input type="hidden" name="sub_id" value="<?php echo (int)$sub_id; ?>">
                    <input type="hidden" name="review_status" id="rmbz-mod-status-value" value="<?php echo esc_attr($cur_status); ?>">
                    <?php wp_nonce_field('onemz_update_site_sub_nonce'); ?>

                    <div class="rmbz-mod-field-label">
                        <span class="ico">🚦</span> Estado da publicação
                    </div>
                    <div class="rmbz-mod-status-pills" id="rmbz-mod-status-pills" role="radiogroup" aria-label="Estado">
                        <?php $i = 1; foreach ( $status_meta as $key => $meta ):
                            $active = ($cur_status === $key);
                        ?>
                            <button type="button"
                                    class="rmbz-mod-status-pill <?php echo $active ? 'is-active' : ''; ?>"
                                    data-status="<?php echo esc_attr($key); ?>"
                                    aria-checked="<?php echo $active ? 'true' : 'false'; ?>"
                                    role="radio">
                                <?php echo esc_html( $meta['icon'] ); ?>
                                <?php echo esc_html( $meta['label'] ); ?>
                                <span class="kbdhint"><?php echo $i; ?></span>
                            </button>
                        <?php $i++; endforeach; ?>
                    </div>

                    <?php if ( function_exists( 'rmbz_render_site_publication_selector' ) ) : ?>
                        <?php rmbz_render_site_publication_selector( $envio, $extra ); ?>
                    <?php else : ?>
                        <div class="rmbz-mod-field-label">Publicação oficial no site</div>
                        <p>O seletor de publicações não está disponível nesta instalação.</p>
                    <?php endif; ?>

                    <?php
                    // [1.6.118.128] Agendamento de publicação. A data é guardada em
                    // UTC; aqui mostramos no fuso de Maputo para o admin escolher.
                    $sched_utc = $extra['scheduled_publish_at'] ?? '';
                    $sched_local_input = '';
                    if ( ! empty( $sched_utc ) ) {
                        $off = function_exists('rmbz_pub_site_offset_secs') ? rmbz_pub_site_offset_secs() : 0;
                        $sched_local_input = gmdate( 'Y-m-d\TH:i', strtotime( $sched_utc . ' UTC' ) + $off );
                    }
                    ?>
                    <div class="rmbz-mod-field-label">
                        <span class="ico">⏰</span> Agendar publicação (opcional)
                    </div>
                    <div class="rmbz-mod-input-group">
                        <input type="datetime-local" name="scheduled_publish_at"
                               value="<?php echo esc_attr($sched_local_input); ?>">
                    </div>
                    <p style="font-size:11px; color:#787c82; margin:4px 0 14px; line-height:1.4;">
                        Se definires uma data, o artista vê uma contagem decrescente e os links só
                        aparecem (sozinhos) quando der a hora. Hora de Moçambique (Maputo). Deixa
                        vazio para publicar já.
                    </p>

                    <!-- BOX REJEIÇÃO/CORREÇÃO -->
                    <div class="rmbz-mod-rejbox rmbz-mod-rejbox--<?php echo $cur_status; ?>"
                         id="rmbz-mod-rejbox"
                         style="display:<?php echo in_array($cur_status, ['rejeitado','correcao'], true) ? 'block' : 'none'; ?>;">
                        <div class="rmbz-mod-fixflags" id="rmbz-mod-fixflags" style="display:<?php echo $cur_status === 'correcao' ? 'block' : 'none'; ?>;">
                            <div class="rmbz-mod-fixflags-title">O que o artista precisa enviar de novo?</div>
                            <label><input type="checkbox" name="needs_audio_fix" value="1" <?php checked(!empty($extra['needs_audio_fix']), true); ?>> 🎵 Novo áudio</label>
                            <label><input type="checkbox" name="needs_cover_fix" value="1" <?php checked(!empty($extra['needs_cover_fix']), true); ?>> 🖼 Nova capa</label>
                            <label><input type="checkbox" name="needs_link_fix"  value="1" <?php checked(!empty($extra['needs_link_fix']),  true); ?>> 🔗 Novo link</label>
                        </div>
                        <label class="rmbz-mod-field-label" id="rmbz-mod-rejlabel" style="color:<?php echo $cur_status === 'correcao' ? '#9a3412' : '#991b1b'; ?>;">
                            <span class="ico">✉️</span>
                            <?php echo $cur_status === 'correcao' ? 'Instruções para o artista (irá no email):' : 'Motivo da rejeição (irá no email):'; ?>
                        </label>
                        <textarea name="rejection_reason" id="rmbz-mod-rejreason" rows="4" class="rmbz-mod-textarea"><?php echo esc_textarea($envio->rejection_reason ?? ''); ?></textarea>
                    </div>

                    <div class="rmbz-mod-save-row">
                        <button type="submit" class="rmbz-mod-save-btn">
                            <span class="ico">💾</span> Guardar alterações
                        </button>
                        <span class="rmbz-mod-save-hint"><span class="rmbz-mod-kbd">Ctrl</span>+<span class="rmbz-mod-kbd">S</span></span>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php rmbz_mod_detail_script( 'site' ); ?>
    <?php
}

/**
 * --------------------------------------------------------------------------
 * 2. PÁGINA: ENVIOS PARA REDES SOCIAIS (Vídeos)             [1.5.192 redesign]
 * --------------------------------------------------------------------------
 */
function rmbz_pagina_envios_social() {
    rmbz_admin_modern_styles();
    global $wpdb;
    $table_sub = $wpdb->prefix . 'rmbz_artist_submissions';
    $table_wal = $wpdb->prefix . 'rmbz_wallets';

    // ── DETALHE ─────────────────────────────────────────────────────────
    if ( isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['id']) ) {
        $sub_id = absint($_GET['id']);
        $envio = $wpdb->get_row( $wpdb->prepare(
            "SELECT s.*, w.user_nome, w.user_email
             FROM {$table_sub} s
             LEFT JOIN {$table_wal} w ON s.artist_telemovel = w.user_telemovel
             WHERE s.id = %d", $sub_id
        ) );
        if ( !$envio ) { echo '<div class="rmbz-mod-wrap">Envio não encontrado.</div>'; return; }

        $extra      = !empty($envio->extra_data) ? json_decode($envio->extra_data, true) : [];
        $thumb_url  = !empty($extra['thumbnail_url']) ? $extra['thumbnail_url'] : '';
        $artist_nm  = $extra['artist_name'] ?? $envio->user_nome ?? 'Artista';
        $status_meta = rmbz_mod_status_meta();
        $cur_status = $envio->review_status ?: 'pendente';

        rmbz_render_envio_social_detail( $sub_id, $envio, $extra, $thumb_url, $artist_nm, $status_meta, $cur_status );
        return;
    }

    // ── LISTA ───────────────────────────────────────────────────────────
    $audicoes = $wpdb->get_results( "SELECT s.*, w.user_nome FROM {$table_sub} s LEFT JOIN {$table_wal} w ON s.artist_telemovel = w.user_telemovel WHERE s.scenario_type = 'Redes Sociais' ORDER BY s.submission_date DESC" );

    $status_meta = rmbz_mod_status_meta();
    $counts = [ 'all' => count( $audicoes ) ];
    foreach ( array_keys( $status_meta ) as $k ) $counts[ $k ] = 0;
    foreach ( $audicoes as $a ) {
        $s = $a->review_status ?: 'pendente';
        if ( isset( $counts[ $s ] ) ) $counts[ $s ]++;
    }
    ?>
    <div class="rmbz-mod-wrap">
        <div class="rmbz-mod-page-head">
            <div>
                <h1>🎬 Promover Vídeos (Redes Sociais)</h1>
                <p class="sub">Vídeos enviados pelos artistas para postar no Facebook e YouTube da 1MZ.</p>
            </div>
        </div>

        <div class="rmbz-mod-section">
            <div class="rmbz-mod-toolbar">
                <div class="rmbz-mod-search">
                    <input type="text" id="rmbz-mod-q" placeholder="Pesquisar por artista, título, canal…" autocomplete="off">
                    <button type="button" class="rmbz-mod-search-clear" id="rmbz-mod-q-clear" aria-label="Limpar pesquisa">×</button>
                </div>
                <div class="rmbz-mod-filters" role="tablist" aria-label="Filtrar por estado">
                    <button type="button" class="rmbz-mod-filter is-active" data-status="all">
                        Todos <span class="rmbz-mod-filter-count"><?php echo (int)$counts['all']; ?></span>
                    </button>
                    <?php foreach ( $status_meta as $key => $meta ): ?>
                        <button type="button" class="rmbz-mod-filter" data-status="<?php echo esc_attr($key); ?>">
                            <?php echo esc_html( $meta['label'] ); ?>
                            <span class="rmbz-mod-filter-count"><?php echo (int)$counts[$key]; ?></span>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <?php if ( empty( $audicoes ) ) : ?>
                <div class="rmbz-mod-empty">
                    <div class="rmbz-mod-empty-icon">📹</div>
                    <p style="margin:0;font-weight:600;font-size:15px;">Ainda não há vídeos para promover.</p>
                    <p style="margin:5px 0 0 0;font-size:13px;">Submissões para Redes Sociais aparecem aqui.</p>
                </div>
            <?php else : ?>
                <div class="rmbz-mod-list" id="rmbz-mod-list" role="list">
                    <?php foreach ( $audicoes as $item ) :
                        $extra      = !empty($item->extra_data) ? json_decode($item->extra_data, true) : [];
                        $st         = $item->review_status ?: 'pendente';
                        $meta       = $status_meta[$st] ?? $status_meta['pendente'];
                        $thumb      = !empty($extra['thumbnail_url']) ? $extra['thumbnail_url'] : '';
                        $artist_nm  = $extra['artist_name'] ?? $item->user_nome ?? '—';
                        $channels   = $extra['channels'] ?? '';
                        $fb         = $extra['facebook_url'] ?? '';
                        $yt         = $extra['youtube_url'] ?? '';
                        $row_search = strtolower( implode( ' ', array_filter( [ $item->music_title, $artist_nm, $channels ] ) ) );
                        $edit_url   = admin_url('admin.php?page=rmbz-envios-social&action=edit&id='.$item->id);
                        $delete_url = wp_nonce_url(admin_url('admin-post.php?action=onemz_delete_submission&sub_id='.$item->id), 'onemz_delete_nonce_'.$item->id);
                    ?>
                    <div class="rmbz-mod-row <?php echo $st === 'pendente' ? 'is-pending' : ''; ?>"
                         role="listitem"
                         tabindex="0"
                         data-status="<?php echo esc_attr($st); ?>"
                         data-search="<?php echo esc_attr($row_search); ?>"
                         data-href="<?php echo esc_url($edit_url); ?>">
                        <div class="rmbz-mod-thumb">
                            <?php if ( $thumb ): ?>
                                <img src="<?php echo esc_url($thumb); ?>" alt="" loading="lazy">
                            <?php else: ?>
                                🎬
                            <?php endif; ?>
                        </div>
                        <div class="rmbz-mod-info">
                            <p class="rmbz-mod-title"><?php echo esc_html($item->music_title); ?></p>
                            <div class="rmbz-mod-sub">
                                <span>👤 <?php echo esc_html($artist_nm); ?></span>
                                <?php if ($channels): ?>
                                    <span class="sep">·</span><span>📡 <?php echo esc_html($channels); ?></span>
                                <?php endif; ?>
                                <span class="sep">·</span><span><?php echo esc_html( date('d/m/Y', strtotime($item->submission_date)) ); ?></span>
                                <?php if ($fb): ?>
                                    <span class="sep">·</span><a href="<?php echo esc_url($fb); ?>" target="_blank" rel="noopener" style="color:#3b5998;font-weight:600;text-decoration:none;" onclick="event.stopPropagation();">🔵 FB</a>
                                <?php endif; ?>
                                <?php if ($yt): ?>
                                    <a href="<?php echo esc_url($yt); ?>" target="_blank" rel="noopener" style="color:#ef4444;font-weight:600;text-decoration:none;" onclick="event.stopPropagation();">🔴 YT</a>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div>
                            <span class="rmbz-mod-status rmbz-mod-status--<?php echo esc_attr($st); ?>">
                                <span class="dot"></span><?php echo esc_html( $meta['label'] ); ?>
                            </span>
                        </div>
                        <div class="rmbz-mod-actions" onclick="event.stopPropagation();">
                            <?php if ( $thumb ): ?>
                                <a href="<?php echo esc_url($thumb); ?>"
                                   download="thumb-<?php echo esc_attr( sanitize_file_name( $item->music_title ) ); ?>.jpg"
                                   class="rmbz-mod-icon-btn"
                                   title="Descarregar thumbnail"
                                   aria-label="Descarregar thumbnail">🖼️</a>
                            <?php endif; ?>
                            <?php if ( ! empty( $extra['video_link_hd'] ) ): ?>
                                <a href="<?php echo esc_url($extra['video_link_hd']); ?>"
                                   target="_blank" rel="noopener"
                                   class="rmbz-mod-icon-btn"
                                   title="Abrir vídeo HD (Drive/Dropbox)"
                                   aria-label="Abrir vídeo HD">🎥</a>
                            <?php endif; ?>
                            <a href="<?php echo esc_url($edit_url); ?>"
                               class="rmbz-mod-icon-btn rmbz-mod-icon-btn--filled"
                               title="Gerir envio"
                               aria-label="Gerir envio">⚙️</a>
                            <a href="<?php echo esc_url($delete_url); ?>"
                               class="rmbz-mod-icon-btn is-danger"
                               title="Apagar"
                               aria-label="Apagar"
                               onclick="return confirm('Apagar definitivamente este envio?\nEsta ação é irreversível.');">🗑</a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="rmbz-mod-kbdtip">
                    <span><span class="rmbz-mod-kbd">↑</span> <span class="rmbz-mod-kbd">↓</span> navegar</span>
                    <span><span class="rmbz-mod-kbd">Enter</span> abrir</span>
                    <span><span class="rmbz-mod-kbd">/</span> pesquisar</span>
                    <span><span class="rmbz-mod-kbd">Esc</span> limpar pesquisa</span>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php rmbz_mod_list_script(); ?>
    <?php
}

/**
 * Renderiza o detalhe (edit) da submissão de Vídeo (Redes).
 */
function rmbz_render_envio_social_detail( $sub_id, $envio, $extra, $thumb_url, $artist_nm, $status_meta, $cur_status ) {
    $back_url = admin_url('admin.php?page=rmbz-envios-social');
    $user_email = $envio->user_email ?? '';
    $cur_meta = $status_meta[ $cur_status ] ?? $status_meta['pendente'];
    ?>
    <div class="rmbz-mod-wrap">
        <div class="rmbz-mod-page-head">
            <div>
                <h1 style="font-size: 22px;">🎬 Gerir Vídeo</h1>
                <p class="sub">Volta atrás com <span class="rmbz-mod-kbd">Esc</span> · Guarda com <span class="rmbz-mod-kbd">Ctrl</span>+<span class="rmbz-mod-kbd">S</span></p>
            </div>
            <div class="head-actions">
                <a href="<?php echo esc_url($back_url); ?>" class="rmbz-mod-back-btn" id="rmbz-mod-back">← Voltar à lista</a>
            </div>
        </div>

        <div class="rmbz-mod-hero">
            <div class="rmbz-mod-hero-thumb" style="<?php echo $thumb_url ? 'background-image:url(' . esc_url($thumb_url) . ');' : ''; ?>">
                <?php if ( ! $thumb_url ): ?>
                    <span class="icon">🎬</span>
                <?php endif; ?>
            </div>
            <div class="rmbz-mod-hero-body">
                <h2 class="rmbz-mod-hero-title"><?php echo esc_html($envio->music_title); ?></h2>
                <p class="rmbz-mod-hero-meta">
                    <span>Por <strong><?php echo esc_html($artist_nm); ?></strong></span>
                    <span>· Submetido <strong><?php echo esc_html( date('d/m/Y H:i', strtotime($envio->submission_date)) ); ?></strong></span>
                    <code><?php echo esc_html($envio->artist_telemovel); ?></code>
                </p>
            </div>
            <span class="status-chip-big rmbz-mod-status--<?php echo esc_attr($cur_status); ?>">
                <span class="dot"></span><?php echo esc_html( $cur_meta['label'] ); ?>
            </span>
        </div>

        <div class="rmbz-mod-detail">
            <!-- COLUNA 1: HISTÓRICO DO ARTISTA -->
            <div class="col-meta">
                <?php
                rmbz_mod_render_artist_card(
                    $artist_nm,
                    $envio->artist_telemovel,
                    $user_email,
                    'Redes Sociais',
                    $sub_id,
                    'rmbz-envios-social'
                );
                ?>

                <?php if ( ! empty( $extra['video_link_hd'] ) ): ?>
                <div class="rmbz-mod-section">
                    <h3><span class="sect-icon">🎥</span> Vídeo HD/4K</h3>
                    <div class="rmbz-mod-link-row">
                        <span class="ico">📦</span>
                        <a href="<?php echo esc_url($extra['video_link_hd']); ?>" target="_blank" rel="noopener"><?php echo esc_html($extra['video_link_hd']); ?></a>
                        <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($extra['video_link_hd']); ?>" title="Copiar URL">📋</button>
                    </div>
                    <a href="<?php echo esc_url($extra['video_link_hd']); ?>"
                       target="_blank" rel="noopener"
                       class="rmbz-mod-btn-primary"
                       style="margin-top:10px;width:100%;">
                        <span class="ico">🎬</span> Abrir vídeo (Drive/Dropbox)
                    </a>
                </div>
                <?php endif; ?>
            </div>

            <!-- COLUNA 2: FICHA + THUMB -->
            <div class="col-files">
                <div class="rmbz-mod-section">
                    <h3><span class="sect-icon">📋</span> Ficha do vídeo</h3>

                    <?php if ($thumb_url): ?>
                        <img src="<?php echo esc_url($thumb_url); ?>" class="rmbz-mod-cover" style="aspect-ratio:16/9;max-height:none;object-fit:cover;" alt="Thumbnail">
                        <div class="rmbz-mod-cover-actions">
                            <a href="<?php echo esc_url($thumb_url); ?>"
                               download="thumb-<?php echo esc_attr( sanitize_file_name( $envio->music_title ) ); ?>.jpg"
                               class="rmbz-mod-btn-primary"
                               style="flex:1;">
                                <span class="ico">📥</span> Descarregar thumbnail
                            </a>
                            <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($thumb_url); ?>" title="Copiar URL">🔗</button>
                        </div>
                    <?php endif; ?>

                    <div class="rmbz-mod-meta-row">
                        <span class="rmbz-mod-meta-label">Género</span>
                        <span class="rmbz-mod-meta-value"><?php echo esc_html($envio->music_genre ?: '—'); ?></span>
                    </div>
                    <div class="rmbz-mod-meta-row">
                        <span class="rmbz-mod-meta-label">Canais</span>
                        <span class="rmbz-mod-meta-value"><?php echo esc_html($extra['channels'] ?? '—'); ?></span>
                    </div>
                    <div class="rmbz-mod-meta-row">
                        <span class="rmbz-mod-meta-label">Feat</span>
                        <span class="rmbz-mod-meta-value"><?php echo esc_html($extra['feat_name'] ?? '—'); ?></span>
                    </div>
                    <div class="rmbz-mod-meta-row">
                        <span class="rmbz-mod-meta-label">Data desejada</span>
                        <span class="rmbz-mod-meta-value"><?php echo esc_html($extra['release_date'] ?? '—'); ?></span>
                    </div>
                    <div class="rmbz-mod-meta-row" style="align-items:flex-start;">
                        <span class="rmbz-mod-meta-label">Legenda</span>
                        <span class="rmbz-mod-meta-value" style="white-space:pre-wrap;line-height:1.5;"><?php echo esc_html($extra['social_caption'] ?? '—'); ?></span>
                    </div>
                </div>
            </div>

            <!-- COLUNA 3: GESTÃO -->
            <div class="col-form">
                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>" id="rmbz-mod-form" class="rmbz-mod-section rmbz-mod-section--accent" style="margin-bottom:0;">
                    <h3><span class="sect-icon">⚙️</span> Gestão nas redes</h3>

                    <input type="hidden" name="action" value="onemz_admin_update_site_submission">
                    <input type="hidden" name="sub_id" value="<?php echo (int)$sub_id; ?>">
                    <input type="hidden" name="review_status" id="rmbz-mod-status-value" value="<?php echo esc_attr($cur_status); ?>">
                    <?php wp_nonce_field('onemz_update_site_sub_nonce'); ?>

                    <div class="rmbz-mod-field-label">
                        <span class="ico">🚦</span> Estado da promoção
                    </div>
                    <div class="rmbz-mod-status-pills" id="rmbz-mod-status-pills" role="radiogroup" aria-label="Estado">
                        <?php $i = 1; foreach ( $status_meta as $key => $meta ):
                            $active = ($cur_status === $key);
                        ?>
                            <button type="button"
                                    class="rmbz-mod-status-pill <?php echo $active ? 'is-active' : ''; ?>"
                                    data-status="<?php echo esc_attr($key); ?>"
                                    aria-checked="<?php echo $active ? 'true' : 'false'; ?>"
                                    role="radio">
                                <?php echo esc_html( $meta['icon'] ); ?>
                                <?php echo esc_html( $meta['label'] ); ?>
                                <span class="kbdhint"><?php echo $i; ?></span>
                            </button>
                        <?php $i++; endforeach; ?>
                    </div>

                    <div class="rmbz-mod-field-label">
                        <span class="ico" style="color:#3b5998;">🔵</span> Link no Facebook
                    </div>
                    <div class="rmbz-mod-input-group">
                        <input type="url" name="facebook_url"
                               value="<?php echo esc_attr($extra['facebook_url'] ?? ''); ?>"
                               placeholder="https://facebook.com/1musicmoz/videos/…"
                               data-mod-cleanpaste>
                        <?php if ( ! empty( $extra['facebook_url'] ) ): ?>
                            <a href="<?php echo esc_url($extra['facebook_url']); ?>" target="_blank" rel="noopener" class="rmbz-mod-icon-btn" title="Abrir">↗</a>
                            <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($extra['facebook_url']); ?>" title="Copiar">📋</button>
                        <?php endif; ?>
                    </div>

                    <div class="rmbz-mod-field-label">
                        <span class="ico" style="color:#ef4444;">🔴</span> Link no YouTube
                    </div>
                    <div class="rmbz-mod-input-group">
                        <input type="url" name="youtube_url"
                               value="<?php echo esc_attr($extra['youtube_url'] ?? ''); ?>"
                               placeholder="https://youtube.com/watch?v=…"
                               data-mod-cleanpaste>
                        <?php if ( ! empty( $extra['youtube_url'] ) ): ?>
                            <a href="<?php echo esc_url($extra['youtube_url']); ?>" target="_blank" rel="noopener" class="rmbz-mod-icon-btn" title="Abrir">↗</a>
                            <button type="button" class="rmbz-mod-icon-btn" data-copy="<?php echo esc_attr($extra['youtube_url']); ?>" title="Copiar">📋</button>
                        <?php endif; ?>
                    </div>

                    <?php
                    // [1.6.118.128] Agendamento de publicação (Redes Sociais). UTC guardado;
                    // mostramos no fuso de Maputo.
                    $sched_utc_s = $extra['scheduled_publish_at'] ?? '';
                    $sched_local_s = '';
                    if ( ! empty( $sched_utc_s ) ) {
                        $off_s = function_exists('rmbz_pub_site_offset_secs') ? rmbz_pub_site_offset_secs() : 0;
                        $sched_local_s = gmdate( 'Y-m-d\TH:i', strtotime( $sched_utc_s . ' UTC' ) + $off_s );
                    }
                    ?>
                    <div class="rmbz-mod-field-label">
                        <span class="ico">⏰</span> Agendar publicação (opcional)
                    </div>
                    <div class="rmbz-mod-input-group">
                        <input type="datetime-local" name="scheduled_publish_at"
                               value="<?php echo esc_attr($sched_local_s); ?>">
                    </div>
                    <p style="font-size:11px; color:#787c82; margin:4px 0 14px; line-height:1.4;">
                        Se definires uma data, o artista vê uma contagem decrescente e os links
                        (Facebook/YouTube) só aparecem (sozinhos) quando der a hora. Hora de
                        Moçambique (Maputo). Deixa vazio para publicar já.
                    </p>

                    <!-- BOX REJEIÇÃO/CORREÇÃO -->
                    <div class="rmbz-mod-rejbox rmbz-mod-rejbox--<?php echo $cur_status; ?>"
                         id="rmbz-mod-rejbox"
                         style="display:<?php echo in_array($cur_status, ['rejeitado','correcao'], true) ? 'block' : 'none'; ?>;">
                        <div class="rmbz-mod-fixflags" id="rmbz-mod-fixflags" style="display:<?php echo $cur_status === 'correcao' ? 'block' : 'none'; ?>;">
                            <div class="rmbz-mod-fixflags-title">O que o artista precisa enviar de novo?</div>
                            <label><input type="checkbox" name="needs_audio_fix" value="1" <?php checked(!empty($extra['needs_audio_fix']), true); ?>> 🎥 Novo vídeo/áudio</label>
                            <label><input type="checkbox" name="needs_cover_fix" value="1" <?php checked(!empty($extra['needs_cover_fix']), true); ?>> 🖼 Nova thumbnail</label>
                            <label><input type="checkbox" name="needs_link_fix"  value="1" <?php checked(!empty($extra['needs_link_fix']),  true); ?>> 🔗 Novo link HD</label>
                        </div>
                        <label class="rmbz-mod-field-label" id="rmbz-mod-rejlabel" style="color:<?php echo $cur_status === 'correcao' ? '#9a3412' : '#991b1b'; ?>;">
                            <span class="ico">✉️</span>
                            <?php echo $cur_status === 'correcao' ? 'Instruções para o artista (irá no email):' : 'Motivo da rejeição (irá no email):'; ?>
                        </label>
                        <textarea name="rejection_reason" id="rmbz-mod-rejreason" rows="4" class="rmbz-mod-textarea"><?php echo esc_textarea($envio->rejection_reason ?? ''); ?></textarea>
                    </div>

                    <div class="rmbz-mod-save-row">
                        <button type="submit" class="rmbz-mod-save-btn">
                            <span class="ico">💾</span> Guardar alterações
                        </button>
                        <span class="rmbz-mod-save-hint"><span class="rmbz-mod-kbd">Ctrl</span>+<span class="rmbz-mod-kbd">S</span></span>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php rmbz_mod_detail_script( 'social' ); ?>
    <?php
}

/**
 * --------------------------------------------------------------------------
 * SCRIPTS DAS PÁGINAS DE MODERAÇÃO (lista + detalhe)
 * --------------------------------------------------------------------------
 */
function rmbz_mod_list_script() {
    ?>
    <script>
    (function(){
        var rows = Array.prototype.slice.call(document.querySelectorAll('#rmbz-mod-list .rmbz-mod-row'));
        var filters = document.querySelectorAll('.rmbz-mod-filter');
        var q = document.getElementById('rmbz-mod-q');
        var qClear = document.getElementById('rmbz-mod-q-clear');
        var currentStatus = 'all';
        var currentQuery = '';
        var focusedIdx = -1;

        function applyFilters() {
            var visible = [];
            rows.forEach(function(r){
                var matchStatus = (currentStatus === 'all') || (r.dataset.status === currentStatus);
                var matchQuery = !currentQuery || (r.dataset.search || '').indexOf(currentQuery) !== -1;
                if (matchStatus && matchQuery) {
                    r.style.display = '';
                    visible.push(r);
                } else {
                    r.style.display = 'none';
                }
            });
            if (focusedIdx >= visible.length) focusedIdx = -1;
            window.__rmbzModVisible = visible;
        }

        filters.forEach(function(btn){
            btn.addEventListener('click', function(){
                filters.forEach(function(b){ b.classList.remove('is-active'); });
                btn.classList.add('is-active');
                currentStatus = btn.dataset.status;
                applyFilters();
            });
        });

        if (q) {
            q.addEventListener('input', function(){
                currentQuery = q.value.trim().toLowerCase();
                qClear.style.display = q.value ? 'flex' : 'none';
                applyFilters();
            });
            qClear.addEventListener('click', function(){
                q.value = ''; currentQuery = '';
                qClear.style.display = 'none';
                applyFilters();
                q.focus();
            });
        }

        rows.forEach(function(r){
            r.addEventListener('click', function(){
                if (r.dataset.href) window.location.href = r.dataset.href;
            });
        });

        function setFocus(idx) {
            var visible = window.__rmbzModVisible || rows;
            if (!visible.length) return;
            if (idx < 0) idx = 0;
            if (idx >= visible.length) idx = visible.length - 1;
            rows.forEach(function(r){ r.classList.remove('is-focused'); });
            focusedIdx = idx;
            var el = visible[idx];
            el.classList.add('is-focused');
            el.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
        }

        document.addEventListener('keydown', function(e){
            var tag = (e.target.tagName || '').toLowerCase();
            var isTyping = (tag === 'input' || tag === 'textarea' || tag === 'select');

            if (e.key === '/' && !isTyping) { e.preventDefault(); if (q) q.focus(); return; }
            if (e.key === 'Escape') {
                if (document.activeElement === q) { q.blur(); }
                else if (q && q.value) { q.value = ''; currentQuery = ''; qClear.style.display='none'; applyFilters(); }
                return;
            }
            if (isTyping) return;

            if (e.key === 'ArrowDown' || e.key === 'j') { e.preventDefault(); setFocus(focusedIdx + 1); }
            else if (e.key === 'ArrowUp' || e.key === 'k') { e.preventDefault(); setFocus(focusedIdx - 1); }
            else if (e.key === 'Enter') {
                var visible = window.__rmbzModVisible || rows;
                if (focusedIdx >= 0 && visible[focusedIdx]) {
                    var href = visible[focusedIdx].dataset.href;
                    if (href) window.location.href = href;
                }
            }
        });

        // Toast + copiar nos pills de telemovel/email (lista usa este script também,
        // mas só dispara se houver elementos data-copy)
        function toast(msg) {
            var t = document.createElement('div');
            t.className = 'rmbz-mod-toast';
            t.innerHTML = '<span class="ico">✓</span>' + msg;
            document.body.appendChild(t);
            requestAnimationFrame(function(){ t.classList.add('is-show'); });
            setTimeout(function(){
                t.classList.remove('is-show');
                setTimeout(function(){ t.remove(); }, 250);
            }, 1500);
        }
        document.querySelectorAll('[data-copy]').forEach(function(btn){
            btn.addEventListener('click', function(e){
                e.stopPropagation();
                var txt = btn.getAttribute('data-copy') || '';
                if (!txt) return;
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(txt).then(function(){ toast('Copiado'); });
                } else {
                    var ta = document.createElement('textarea');
                    ta.value = txt; document.body.appendChild(ta); ta.select();
                    try { document.execCommand('copy'); toast('Copiado'); } catch(err) {}
                    document.body.removeChild(ta);
                }
            });
        });

        applyFilters();
    })();
    </script>
    <?php
}

function rmbz_mod_detail_script( $scope ) {
    ?>
    <script>
    (function(){
        var pills = document.querySelectorAll('#rmbz-mod-status-pills .rmbz-mod-status-pill');
        var hidden = document.getElementById('rmbz-mod-status-value');
        var rejbox = document.getElementById('rmbz-mod-rejbox');
        var flags  = document.getElementById('rmbz-mod-fixflags');
        var label  = document.getElementById('rmbz-mod-rejlabel');
        var rejTa  = document.getElementById('rmbz-mod-rejreason');
        var form   = document.getElementById('rmbz-mod-form');
        var back   = document.getElementById('rmbz-mod-back');

        function setStatus(key) {
            if (!key) return;
            hidden.value = key;
            pills.forEach(function(p){
                var active = (p.dataset.status === key);
                p.classList.toggle('is-active', active);
                p.setAttribute('aria-checked', active ? 'true' : 'false');
            });
            if (rejbox) {
                if (key === 'rejeitado' || key === 'correcao') {
                    rejbox.style.display = 'block';
                    rejbox.classList.remove('rmbz-mod-rejbox--rejeitado','rmbz-mod-rejbox--correcao');
                    rejbox.classList.add('rmbz-mod-rejbox--' + key);
                    if (rejTa) rejTa.required = true;
                    if (flags) flags.style.display = (key === 'correcao') ? 'block' : 'none';
                    if (label) {
                        if (key === 'correcao') {
                            label.innerHTML = '<span class="ico">✉️</span> Instruções para o artista (irá no email):';
                            label.style.color = '#9a3412';
                        } else {
                            label.innerHTML = '<span class="ico">✉️</span> Motivo da rejeição (irá no email):';
                            label.style.color = '#991b1b';
                        }
                    }
                } else {
                    rejbox.style.display = 'none';
                    if (rejTa) rejTa.required = false;
                }
            }
        }

        pills.forEach(function(p){
            p.addEventListener('click', function(){ setStatus(p.dataset.status); });
        });

        var statusOrder = ['pendente','aprovado','em_publicacao','finalizado','correcao','rejeitado'];
        document.addEventListener('keydown', function(e){
            var tag = (e.target.tagName || '').toLowerCase();
            var isTyping = (tag === 'input' || tag === 'textarea' || tag === 'select');

            if ((e.ctrlKey || e.metaKey) && (e.key === 's' || e.key === 'S')) {
                e.preventDefault(); if (form) form.submit(); return;
            }
            if (e.key === 'Escape' && !isTyping) {
                if (back) window.location.href = back.href; return;
            }
            if (isTyping) return;

            var num = parseInt(e.key, 10);
            if (!isNaN(num) && num >= 1 && num <= statusOrder.length) {
                e.preventDefault(); setStatus(statusOrder[num - 1]);
            }
        });

        function toast(msg) {
            var t = document.createElement('div');
            t.className = 'rmbz-mod-toast';
            t.innerHTML = '<span class="ico">✓</span>' + msg;
            document.body.appendChild(t);
            requestAnimationFrame(function(){ t.classList.add('is-show'); });
            setTimeout(function(){
                t.classList.remove('is-show');
                setTimeout(function(){ t.remove(); }, 250);
            }, 1500);
        }
        document.querySelectorAll('[data-copy]').forEach(function(btn){
            btn.addEventListener('click', function(e){
                e.stopPropagation();
                var txt = btn.getAttribute('data-copy') || '';
                if (!txt) return;
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(txt).then(function(){ toast('Copiado'); });
                } else {
                    var ta = document.createElement('textarea');
                    ta.value = txt; document.body.appendChild(ta); ta.select();
                    try { document.execCommand('copy'); toast('Copiado'); } catch(err) {}
                    document.body.removeChild(ta);
                }
            });
        });

        document.querySelectorAll('input[data-mod-cleanpaste]').forEach(function(inp){
            inp.addEventListener('paste', function(e){
                var txt = (e.clipboardData || window.clipboardData).getData('text');
                if (txt && /\s/.test(txt)) {
                    e.preventDefault();
                    inp.value = txt.replace(/\s+/g, '').trim();
                    inp.dispatchEvent(new Event('input', { bubbles: true }));
                }
            });
        });
    })();
    </script>
    <?php
}
/**
 * --------------------------------------------------------------------------
 * 3. PÁGINA: GESTÃO DE PROJETOS & CHAT (Candidaturas & Videoclipes)
 * --------------------------------------------------------------------------
 *
 * [1.5.193] Reescrita completa: full-screen, chat live (polling 3s),
 * anexos com toggle por projecto. A implementação está em
 * includes/admin/projects-admin-page.php para não tornar este ficheiro
 * gigante. Esta função apenas delega.
 */
function onemz_mostrar_pagina_projetos() {
    if ( function_exists( 'rmbz_pjv2_render_page' ) ) {
        rmbz_pjv2_render_page();
        return;
    }
    // Fallback: nunca deve cair aqui em produção (o ficheiro é carregado
    // pelo plugin principal). Apenas para o caso de o include falhar.
    echo '<div class="rmbz-admin-wrap"><h1>Projetos & Chat</h1>';
    echo '<p>Erro: módulo projects-admin-page.php não carregado.</p></div>';
}

/**
 * --------------------------------------------------------------------------
 * 4. PÁGINA: DEPÓSITOS DE CARTEIRA
 * --------------------------------------------------------------------------
 */
function rmbz_mostrar_pagina_depositos() {
    rmbz_admin_modern_styles();
    global $wpdb;
    $table_name = $wpdb->prefix . 'rmbz_deposit_requests';

    // [1.6.118.17] Filtros + paginação
    $filter_origin = isset($_GET['origin']) ? sanitize_text_field($_GET['origin']) : '';        // app|site|''
    $filter_type   = isset($_GET['type'])   ? sanitize_text_field($_GET['type'])   : '';        // first|topup|''
    $filter_hist_status = isset($_GET['hst']) ? sanitize_text_field($_GET['hst'])  : '';        // aprovado|rejeitado|''
    $search_tel    = isset($_GET['s'])      ? sanitize_text_field($_GET['s'])      : '';
    $page_hist     = max(1, isset($_GET['p']) ? absint($_GET['p']) : 1);
    $per_page_hist = 25;
    $offset_hist   = ($page_hist - 1) * $per_page_hist;

    // ─── Pendentes (sempre todos, sem paginação — admin precisa ver tudo) ─
    $where_pend = "WHERE status = 'pendente'";
    $params_pend = array();
    if ($filter_origin === 'app' || $filter_origin === 'site') {
        $where_pend .= " AND source_platform = %s";
        $params_pend[] = $filter_origin;
    }
    if ($filter_type === 'first')  $where_pend .= " AND is_first_deposit = 1";
    if ($filter_type === 'topup')  $where_pend .= " AND is_first_deposit = 0";
    if ($search_tel !== '') {
        $where_pend .= " AND user_telemovel LIKE %s";
        $params_pend[] = '%' . $wpdb->esc_like($search_tel) . '%';
    }
    $sql_pend = "SELECT * FROM {$table_name} $where_pend ORDER BY request_date ASC";
    $pendentes = empty($params_pend)
        ? $wpdb->get_results($sql_pend)
        : $wpdb->get_results($wpdb->prepare($sql_pend, $params_pend));

    // ─── Histórico (paginado + filtros) ────────────────────────────────
    $where_hist = "WHERE status != 'pendente'";
    $params_hist = array();
    if ($filter_hist_status === 'aprovado' || $filter_hist_status === 'rejeitado') {
        $where_hist .= " AND status = %s";
        $params_hist[] = $filter_hist_status;
    }
    if ($filter_origin === 'app' || $filter_origin === 'site') {
        $where_hist .= " AND source_platform = %s";
        $params_hist[] = $filter_origin;
    }
    if ($search_tel !== '') {
        $where_hist .= " AND user_telemovel LIKE %s";
        $params_hist[] = '%' . $wpdb->esc_like($search_tel) . '%';
    }

    // Contar total histórico para paginação
    $sql_count_hist = "SELECT COUNT(*) FROM {$table_name} $where_hist";
    $total_hist = empty($params_hist)
        ? (int) $wpdb->get_var($sql_count_hist)
        : (int) $wpdb->get_var($wpdb->prepare($sql_count_hist, $params_hist));
    $total_pages_hist = max(1, ceil($total_hist / $per_page_hist));

    $sql_hist = "SELECT * FROM {$table_name} $where_hist ORDER BY processed_date DESC LIMIT %d OFFSET %d";
    $params_hist_query = array_merge($params_hist, array($per_page_hist, $offset_hist));
    $historico = $wpdb->get_results($wpdb->prepare($sql_hist, $params_hist_query));

    // ─── Estatísticas globais (não filtradas) ──────────────────────────
    $stats = $wpdb->get_row(
        "SELECT
            SUM(CASE WHEN status='pendente' THEN 1 ELSE 0 END)  AS total_pendentes,
            SUM(CASE WHEN status='pendente' THEN amount ELSE 0 END) AS valor_pendentes,
            SUM(CASE WHEN status='pendente' AND is_first_deposit=1 THEN 1 ELSE 0 END) AS pendentes_first,
            SUM(CASE WHEN status='pendente' AND source_platform='app' THEN 1 ELSE 0 END) AS pendentes_app,
            SUM(CASE WHEN status='pendente' AND source_platform='site' THEN 1 ELSE 0 END) AS pendentes_site,
            SUM(CASE WHEN status='aprovado' THEN amount ELSE 0 END) AS total_aprovado_valor,
            SUM(CASE WHEN status='aprovado' THEN 1 ELSE 0 END) AS total_aprovado_cnt,
            SUM(CASE WHEN status='rejeitado' THEN 1 ELSE 0 END) AS total_rejeitado_cnt
         FROM {$table_name}"
    );

    // Helper para preservar query string ao mudar filtro/página
    $build_url = function( $overrides = array() ) use ( $filter_origin, $filter_type, $filter_hist_status, $search_tel, $page_hist ) {
        $args = array( 'page' => 'rmbz-depositos' );
        if ($filter_origin !== '')      $args['origin'] = $filter_origin;
        if ($filter_type !== '')        $args['type']   = $filter_type;
        if ($filter_hist_status !== '') $args['hst']    = $filter_hist_status;
        if ($search_tel !== '')         $args['s']      = $search_tel;
        if ($page_hist > 1)             $args['p']      = $page_hist;
        foreach ($overrides as $k => $v) {
            if ($v === null) unset($args[$k]);
            else $args[$k] = $v;
        }
        return admin_url('admin.php?' . http_build_query($args));
    };

    $has_filters = ($filter_origin || $filter_type || $filter_hist_status || $search_tel !== '');
    ?>
    <div class="rmbz-admin-wrap rmbz-deposits-modern">

        <?php if ( isset( $_GET['rmbz_dep_deleted'] ) && (int) $_GET['rmbz_dep_deleted'] > 0 ): ?>
            <div class="notice notice-success is-dismissible" style="margin-bottom:14px;">
                <p><strong>✓ Registo de depósito apagado.</strong> O ficheiro do comprovativo foi removido (quando local). Auditoria registada no error_log.</p>
            </div>
        <?php endif; ?>

        <!-- HEADER + STATS no padrão Gestão Artistas -->
        <div class="rmbz-dep-head">
            <h1>💰 Aprovar Depósitos</h1>
            <p>Valide as transferências M-Pesa/E-Mola e credite a carteira dos artistas.</p>
        </div>

        <div class="rmbz-dep-stats-grid">
            <div class="rmbz-dep-stat-card warn">
                <div class="label">Pendentes agora</div>
                <div class="value"><?php echo (int) $stats->total_pendentes; ?></div>
                <div class="sub"><?php echo number_format((float) $stats->valor_pendentes, 2, ',', '.'); ?> MT</div>
            </div>
            <div class="rmbz-dep-stat-card info">
                <div class="label">Pendentes 1º depósito</div>
                <div class="value"><?php echo (int) $stats->pendentes_first; ?></div>
                <div class="sub">precisam decisão em 24h</div>
            </div>
            <div class="rmbz-dep-stat-card">
                <div class="label">Por origem</div>
                <div class="value" style="font-size:14px; font-weight:600;">
                    📱 <?php echo (int) $stats->pendentes_app; ?>
                    &nbsp;·&nbsp;
                    🌐 <?php echo (int) $stats->pendentes_site; ?>
                </div>
            </div>
            <div class="rmbz-dep-stat-card success">
                <div class="label">Aprovados histórico</div>
                <div class="value"><?php echo number_format((int) $stats->total_aprovado_cnt, 0, ',', '.'); ?></div>
                <div class="sub"><?php echo number_format((float) $stats->total_aprovado_valor, 2, ',', '.'); ?> MT total</div>
            </div>
            <div class="rmbz-dep-stat-card danger">
                <div class="label">Rejeitados histórico</div>
                <div class="value"><?php echo number_format((int) $stats->total_rejeitado_cnt, 0, ',', '.'); ?></div>
            </div>
        </div>

        <!-- TOOLBAR: pesquisa + filtros -->
        <div class="rmbz-dep-toolbar">
            <form method="get" class="rmbz-dep-search">
                <input type="hidden" name="page" value="rmbz-depositos">
                <?php foreach (['origin'=>$filter_origin, 'type'=>$filter_type, 'hst'=>$filter_hist_status] as $k => $v):
                    if ($v !== ''): ?>
                        <input type="hidden" name="<?php echo esc_attr($k); ?>" value="<?php echo esc_attr($v); ?>">
                    <?php endif;
                endforeach; ?>
                <input type="text" name="s" value="<?php echo esc_attr($search_tel); ?>" placeholder="🔍 Pesquisar por telemóvel…" class="rmbz-dep-search-input">
                <button type="submit" class="rmbz-dep-btn">Procurar</button>
                <?php if ($has_filters): ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=rmbz-depositos')); ?>" class="rmbz-dep-btn ghost">Limpar filtros</a>
                <?php endif; ?>
            </form>

            <div class="rmbz-dep-filter-group">
                <span class="rmbz-dep-filter-label">Origem:</span>
                <a href="<?php echo esc_url($build_url(['origin'=>null,'p'=>null])); ?>" class="rmbz-dep-chip <?php echo $filter_origin === '' ? 'active' : ''; ?>">Todas</a>
                <a href="<?php echo esc_url($build_url(['origin'=>'app','p'=>null])); ?>" class="rmbz-dep-chip <?php echo $filter_origin === 'app' ? 'active' : ''; ?>">📱 App</a>
                <a href="<?php echo esc_url($build_url(['origin'=>'site','p'=>null])); ?>" class="rmbz-dep-chip <?php echo $filter_origin === 'site' ? 'active' : ''; ?>">🌐 Site</a>
            </div>

            <div class="rmbz-dep-filter-group">
                <span class="rmbz-dep-filter-label">Tipo:</span>
                <a href="<?php echo esc_url($build_url(['type'=>null,'p'=>null])); ?>" class="rmbz-dep-chip <?php echo $filter_type === '' ? 'active' : ''; ?>">Todos</a>
                <a href="<?php echo esc_url($build_url(['type'=>'first','p'=>null])); ?>" class="rmbz-dep-chip <?php echo $filter_type === 'first' ? 'active' : ''; ?>">🆕 1º Depósito</a>
                <a href="<?php echo esc_url($build_url(['type'=>'topup','p'=>null])); ?>" class="rmbz-dep-chip <?php echo $filter_type === 'topup' ? 'active' : ''; ?>">💼 Top-up</a>
            </div>
        </div>

        <!-- PENDENTES -->
        <div class="rmbz-dep-section">
            <h3 class="rmbz-dep-section-title">
                ⏳ Pedidos Pendentes
                <span class="rmbz-dep-section-count"><?php echo (int) count($pendentes); ?><?php if ($has_filters && (int) $stats->total_pendentes > count($pendentes)) echo ' de ' . (int) $stats->total_pendentes; ?></span>
            </h3>
            <?php if ( empty( $pendentes ) ) : ?>
                <div class="rmbz-dep-empty">
                    <div class="icon">✓</div>
                    <div class="msg">
                        <?php if ($has_filters): ?>
                            Nenhum depósito pendente com estes filtros.
                        <?php else: ?>
                            Nenhum depósito pendente. Tudo em dia!
                        <?php endif; ?>
                    </div>
                </div>
            <?php else : ?>
                <div class="rmbz-dep-table-wrap">
                    <table class="rmbz-dep-table">
                        <thead><tr>
                            <th>Data</th>
                            <th>Artista (Tel)</th>
                            <th>Valor (MT)</th>
                            <th>Pagador</th>
                            <th>Origem</th>
                            <th>Comprovativo</th>
                            <th style="text-align:right;">Ações</th>
                        </tr></thead>
                        <tbody>
                            <?php foreach ( $pendentes as $dep ) :
                                $link_apr = wp_nonce_url(admin_url('admin-post.php?action=rmbz_approve_deposit&dep_id='.$dep->id), 'rmbz_approve_deposit_nonce_'.$dep->id);
                                $link_rej = wp_nonce_url(admin_url('admin-post.php?action=rmbz_reject_deposit&dep_id='.$dep->id), 'rmbz_reject_deposit_nonce_'.$dep->id);

                                $origem      = $dep->source_platform ?? '';
                                $is_first    = ! empty( $dep->is_first_deposit );

                                // Countdown para 1º depósito
                                $countdown_html = '';
                                if ( $is_first ) {
                                    $expira_ts = strtotime( $dep->request_date . ' UTC' ) + 86400;
                                    $segs_rest = $expira_ts - time();
                                    if ( $segs_rest > 0 ) {
                                        $h = floor( $segs_rest / 3600 );
                                        $m = floor( ( $segs_rest % 3600 ) / 60 );
                                        $cor_class = $h < 6 ? 'urgent' : ( $h < 12 ? 'warn' : 'ok' );
                                        $countdown_html = '<div class="rmbz-dep-countdown ' . $cor_class . '">⏱ ' . $h . 'h ' . $m . 'm restantes</div>';
                                    } else {
                                        $countdown_html = '<div class="rmbz-dep-countdown expired">⚠ Expirado — será apagado</div>';
                                    }
                                }

                                $modal_data = wp_json_encode([
                                    'id'               => (int) $dep->id,
                                    'user_telemovel'   => $dep->user_telemovel,
                                    'amount'           => (float) $dep->amount,
                                    'status'           => $dep->status,
                                    'payment_method'   => $dep->payment_method,
                                    'transaction_id'   => $dep->transaction_id,
                                    'proof_image'      => $dep->proof_image,
                                    'sender_phone'     => $dep->sender_phone,
                                    'request_date'     => $dep->request_date,
                                    'processed_date'   => $dep->processed_date,
                                    'admin_notes'      => $dep->admin_notes,
                                    'source_platform'  => $origem,
                                    'is_first_deposit' => $is_first ? 1 : 0,
                                    'approve_url'      => $link_apr,
                                    'reject_url'       => $link_rej,
                                ]);
                            ?>
                                <tr class="rmbz-dep-row-clickable rmbz-dep-detail-btn" data-deposit='<?php echo esc_attr( $modal_data ); ?>'>
                                    <td><?php echo rmbz_safe_date_format($dep->request_date); ?></td>
                                    <td>
                                        <strong><?php echo esc_html( $dep->user_telemovel ); ?></strong>
                                        <?php if ( $is_first ): ?>
                                            <span class="rmbz-dep-badge first">🆕 Abertura</span>
                                            <?php echo $countdown_html; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><span class="rmbz-dep-amount"><?php echo number_format((float)$dep->amount, 2, ',', '.'); ?> MT</span></td>
                                    <td>
                                        <?php echo !empty($dep->sender_phone) ? esc_html($dep->sender_phone) : '—'; ?>
                                        <div class="rmbz-dep-method"><?php echo esc_html($dep->payment_method); ?></div>
                                    </td>
                                    <td>
                                        <?php
                                        if ( $origem === 'app' ) {
                                            echo '<span class="rmbz-dep-badge origin-app">📱 App</span>';
                                        } elseif ( $origem === 'site' ) {
                                            echo '<span class="rmbz-dep-badge origin-site">🌐 Site</span>';
                                        } else {
                                            echo '<span class="rmbz-dep-badge origin-old">— antigo</span>';
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <?php if ( !empty($dep->proof_image) ): ?>
                                            <a href="<?php echo esc_url($dep->proof_image); ?>" target="_blank" class="rmbz-dep-btn ghost small" onclick="event.stopPropagation();">📸 Ver Print</a>
                                        <?php else: ?>
                                            <code class="rmbz-dep-trxid" onclick="event.stopPropagation();"><?php echo esc_html( $dep->transaction_id ); ?></code>
                                        <?php endif; ?>
                                    </td>
                                    <td style="text-align:right;">
                                        <div class="rmbz-dep-actions" onclick="event.stopPropagation();">
                                            <a href="<?php echo esc_url($link_apr); ?>" class="rmbz-dep-btn success" onclick="return confirm('Adicionar saldo à carteira do utilizador?');">✓ Aprovar</a>
                                            <a href="<?php echo esc_url($link_rej); ?>" class="rmbz-dep-btn danger" onclick="return confirm('Rejeitar este depósito?');">✗ Rejeitar</a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- HISTÓRICO -->
        <div class="rmbz-dep-section">
            <h3 class="rmbz-dep-section-title">
                📜 Histórico
                <span class="rmbz-dep-section-count"><?php echo number_format($total_hist, 0, ',', '.'); ?></span>
            </h3>

            <!-- Sub-tabs status histórico -->
            <div class="rmbz-dep-subtabs">
                <a href="<?php echo esc_url($build_url(['hst'=>null,'p'=>null])); ?>" class="<?php echo $filter_hist_status === '' ? 'active' : ''; ?>">Todos</a>
                <a href="<?php echo esc_url($build_url(['hst'=>'aprovado','p'=>null])); ?>" class="<?php echo $filter_hist_status === 'aprovado' ? 'active' : ''; ?>">✓ Aprovados</a>
                <a href="<?php echo esc_url($build_url(['hst'=>'rejeitado','p'=>null])); ?>" class="<?php echo $filter_hist_status === 'rejeitado' ? 'active' : ''; ?>">✗ Rejeitados</a>
            </div>

            <?php if ( empty( $historico ) ) : ?>
                <div class="rmbz-dep-empty">
                    <div class="icon">📭</div>
                    <div class="msg">
                        <?php echo $has_filters ? 'Nenhum depósito no histórico com estes filtros.' : 'Sem histórico de depósitos ainda.'; ?>
                    </div>
                </div>
            <?php else : ?>
                <div class="rmbz-dep-table-wrap">
                    <table class="rmbz-dep-table">
                        <thead><tr>
                            <th>Processado</th>
                            <th>Artista</th>
                            <th>Valor</th>
                            <th>Origem</th>
                            <th>ID / Print</th>
                            <th>Status</th>
                            <th style="text-align:right;">Detalhe</th>
                        </tr></thead>
                        <tbody>
                            <?php foreach ( $historico as $dep ) :
                                $st_class = ($dep->status === 'aprovado') ? 'status-approved' : (($dep->status === 'rejeitado') ? 'status-rejected' : 'status-other');

                                $modal_data = wp_json_encode([
                                    'id'               => (int) $dep->id,
                                    'user_telemovel'   => $dep->user_telemovel,
                                    'amount'           => (float) $dep->amount,
                                    'status'           => $dep->status,
                                    'payment_method'   => $dep->payment_method,
                                    'transaction_id'   => $dep->transaction_id,
                                    'proof_image'      => $dep->proof_image,
                                    'sender_phone'     => $dep->sender_phone,
                                    'request_date'     => $dep->request_date,
                                    'processed_date'   => $dep->processed_date,
                                    'admin_notes'      => $dep->admin_notes,
                                    'source_platform'  => $dep->source_platform ?? '',
                                    'is_first_deposit' => ! empty( $dep->is_first_deposit ) ? 1 : 0,
                                    'delete_url'       => $dep->status === 'rejeitado'
                                        ? wp_nonce_url(
                                            admin_url( 'admin-post.php?action=rmbz_delete_rejected_deposit&dep_id=' . $dep->id ),
                                            'rmbz_delete_rejected_deposit_nonce_' . $dep->id
                                          )
                                        : null,
                                ]);
                            ?>
                                <tr>
                                    <td><?php echo rmbz_safe_date_format($dep->processed_date); ?></td>
                                    <td><?php echo esc_html( $dep->user_telemovel ); ?></td>
                                    <td><span class="rmbz-dep-amount"><?php echo number_format((float)$dep->amount, 2, ',', '.'); ?> MT</span></td>
                                    <td>
                                        <?php
                                        $orig_h = $dep->source_platform ?? '';
                                        if ($orig_h === 'app')        echo '<span class="rmbz-dep-badge origin-app">📱 App</span>';
                                        elseif ($orig_h === 'site')   echo '<span class="rmbz-dep-badge origin-site">🌐 Site</span>';
                                        else                          echo '<span class="rmbz-dep-badge origin-old">—</span>';
                                        ?>
                                    </td>
                                    <td><?php echo !empty($dep->proof_image) ? '📸 (Imagem)' : '<code class="rmbz-dep-trxid">'.esc_html($dep->transaction_id).'</code>'; ?></td>
                                    <td><span class="rmbz-dep-status <?php echo $st_class; ?>"><?php echo esc_html( ucfirst($dep->status) ); ?></span></td>
                                    <td style="text-align:right;">
                                        <button type="button" class="rmbz-dep-btn ghost small rmbz-dep-view-btn rmbz-dep-detail-btn"
                                                data-deposit='<?php echo esc_attr( $modal_data ); ?>'>
                                            Ver Detalhe →
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($total_pages_hist > 1): ?>
                    <div class="rmbz-dep-pagination">
                        <div class="info">
                            Mostrando <?php echo $offset_hist + 1; ?>–<?php echo min($offset_hist + count($historico), $total_hist); ?>
                            de <?php echo number_format($total_hist, 0, ',', '.'); ?>
                        </div>
                        <div class="links">
                            <?php
                            if ($page_hist > 1) {
                                echo '<a href="' . esc_url($build_url(['p' => $page_hist - 1])) . '">‹</a>';
                            }
                            $start_p = max(1, $page_hist - 2);
                            $end_p   = min($total_pages_hist, $page_hist + 2);
                            if ($start_p > 1) {
                                echo '<a href="' . esc_url($build_url(['p' => 1])) . '">1</a>';
                                if ($start_p > 2) echo '<span class="dots">…</span>';
                            }
                            for ($i = $start_p; $i <= $end_p; $i++) {
                                if ($i === $page_hist) {
                                    echo '<span class="current">' . $i . '</span>';
                                } else {
                                    echo '<a href="' . esc_url($build_url(['p' => $i])) . '">' . $i . '</a>';
                                }
                            }
                            if ($end_p < $total_pages_hist) {
                                if ($end_p < $total_pages_hist - 1) echo '<span class="dots">…</span>';
                                echo '<a href="' . esc_url($build_url(['p' => $total_pages_hist])) . '">' . $total_pages_hist . '</a>';
                            }
                            if ($page_hist < $total_pages_hist) {
                                echo '<a href="' . esc_url($build_url(['p' => $page_hist + 1])) . '">›</a>';
                            }
                            ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Modal de detalhe (escondida por defeito, populada via JS) -->
        <div id="rmbz-dep-modal" class="rmbz-dep-modal" aria-hidden="true">
            <div class="rmbz-dep-modal-backdrop" data-close-modal></div>
            <div class="rmbz-dep-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="rmbz-dep-modal-title">
                <div class="rmbz-dep-modal-header">
                    <h3 id="rmbz-dep-modal-title">Detalhe do Depósito</h3>
                    <button type="button" class="rmbz-dep-modal-close" data-close-modal aria-label="Fechar">&times;</button>
                </div>
                <div class="rmbz-dep-modal-body">
                    <!-- [1.6.118] Banner topo: badges abertura + countdown se aplicável -->
                    <div id="md-banner" style="margin-bottom:14px;"></div>
                    <div class="rmbz-dep-modal-grid">
                        <div class="rmbz-dep-modal-info">
                            <dl>
                                <dt>ID do pedido</dt><dd id="md-id">—</dd>
                                <dt>Status</dt><dd id="md-status">—</dd>
                                <dt>Origem</dt><dd id="md-origem">—</dd>
                                <dt>Artista (telemóvel)</dt><dd id="md-artist">—</dd>
                                <dt>Valor</dt><dd id="md-amount">—</dd>
                                <dt>Método</dt><dd id="md-method">—</dd>
                                <dt>Telemóvel pagador</dt><dd id="md-sender">—</dd>
                                <dt>ID da transação</dt><dd id="md-trxid">—</dd>
                                <dt>Pedido em</dt><dd id="md-req-date">—</dd>
                                <dt>Processado em</dt><dd id="md-proc-date">—</dd>
                            </dl>
                            <div class="rmbz-dep-notes-block">
                                <strong>Notas do admin</strong>
                                <p id="md-notes" class="rmbz-dep-notes">—</p>
                            </div>
                            <!-- [1.6.118] Botões aprovar/rejeitar dentro do modal
                                 (visíveis só quando status='pendente'). -->
                            <div id="md-actions" style="margin-top:16px; display:none; gap:10px;">
                                <a id="md-btn-approve" href="#" class="rmbz-btn btn-success" style="background:#10b981; color:#fff; padding:8px 16px; font-weight:600;" onclick="return confirm('Adicionar saldo à carteira do utilizador?');">✓ Aprovar Depósito</a>
                                <a id="md-btn-reject" href="#" class="rmbz-btn btn-danger" style="background:#dc2626; color:#fff; padding:8px 16px; font-weight:600;" onclick="return confirm('Rejeitar este depósito?');">✗ Rejeitar</a>
                            </div>
                            <!-- [1.6.118.3] Botão APAGAR — só visível para REJEITADOS -->
                            <div id="md-delete-block" style="margin-top:18px; padding-top:14px; border-top:1px solid #eee; display:none;">
                                <p style="font-size:11.5px; color:#888; margin:0 0 8px;">⚠ Apagar registo é IRREVERSÍVEL. O ficheiro do comprovativo também será removido (quando local).</p>
                                <a id="md-btn-delete" href="#" class="rmbz-btn" style="background:#7f1d1d; color:#fff; padding:6px 14px; font-size:12px; font-weight:600;" onclick="return rmbzDepConfirmDelete(this);">🗑 Apagar Registo Definitivamente</a>
                            </div>
                        </div>
                        <div class="rmbz-dep-modal-proof">
                            <strong>Comprovativo</strong>
                            <div id="md-proof-wrap" class="rmbz-dep-proof-wrap">
                                <p class="rmbz-dep-no-proof">Sem imagem anexada.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <style>
            /* [1.6.118.17] REFACTOR VISUAL — depósitos light theme moderno
             * Consistente com Gestão de Artistas / Perfil. Apenas as
             * classes `rmbz-dep-*` são novas; legacy permanece intocada
             * para o modal e outras integrações.
             */
            .rmbz-deposits-modern.rmbz-admin-wrap {
                max-width: none;
                margin: 16px 20px 32px 0;
                font-family: "Roboto", -apple-system, BlinkMacSystemFont, sans-serif;
                color: #1a1a1f;
                background: transparent;
                padding: 0;
            }

            /* Header */
            .rmbz-dep-head h1 { font-size: 26px; font-weight: 800; margin: 0 0 4px 0; color: #1d2327; letter-spacing: -0.01em; }
            .rmbz-dep-head p  { margin: 0; color: #5f6368; font-size: 13px; }

            /* Stats grid */
            .rmbz-dep-stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 20px 0 18px; }
            .rmbz-dep-stat-card { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 16px 18px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
            .rmbz-dep-stat-card .label { font-size: 11px; font-weight: 700; text-transform: uppercase; color: #5f6368; letter-spacing: 0.5px; margin-bottom: 6px; }
            .rmbz-dep-stat-card .value { font-size: 26px; font-weight: 800; color: #1d2327; line-height: 1.1; }
            .rmbz-dep-stat-card .sub   { font-size: 11px; color: #5f6368; margin-top: 3px; font-weight: 500; }
            .rmbz-dep-stat-card.warn .value    { color: #9a3412; }
            .rmbz-dep-stat-card.info .value    { color: #1e40af; }
            .rmbz-dep-stat-card.success .value { color: #047857; }
            .rmbz-dep-stat-card.danger .value  { color: #b91c1c; }

            /* Toolbar */
            .rmbz-dep-toolbar { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 14px 16px; margin-bottom: 16px; display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
            .rmbz-dep-search { display: flex; gap: 8px; flex: 1; min-width: 240px; }
            .rmbz-dep-search-input { flex: 1; padding: 8px 12px; border: 1px solid #d8dae0; border-radius: 6px; font-size: 13px; }
            .rmbz-dep-filter-group { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; }
            .rmbz-dep-filter-label { font-size: 11px; color: #5f6368; text-transform: uppercase; font-weight: 700; letter-spacing: 0.5px; margin-right: 4px; }
            .rmbz-dep-chip { display: inline-flex; align-items: center; padding: 5px 11px; border-radius: 16px; background: #f1f3f5; color: #3c434a; font-size: 12px; font-weight: 600; text-decoration: none; border: 1px solid transparent; transition: 0.15s; }
            .rmbz-dep-chip:hover { background: #e9ecef; color: #1d2327; }
            .rmbz-dep-chip.active { background: #1d2327; color: #f0b90b; border-color: #1d2327; }
            .rmbz-dep-chip.active:hover { background: #1d2327; color: #f0b90b; }

            /* Botões base */
            .rmbz-dep-btn { display: inline-flex; align-items: center; justify-content: center; padding: 8px 14px; background: #1d2327; color: #f0b90b; border: none; border-radius: 8px; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; cursor: pointer; text-decoration: none; transition: 0.15s; }
            .rmbz-dep-btn:hover { background: #2c2c34; color: #f0b90b; transform: translateY(-1px); }
            .rmbz-dep-btn.small { padding: 6px 10px; font-size: 11px; }
            .rmbz-dep-btn.ghost { background: #f1f3f5; color: #3c434a; }
            .rmbz-dep-btn.ghost:hover { background: #e9ecef; color: #1d2327; }
            .rmbz-dep-btn.success { background: #10b981; color: #fff; }
            .rmbz-dep-btn.success:hover { background: #047857; color: #fff; }
            .rmbz-dep-btn.danger { background: #ef4444; color: #fff; }
            .rmbz-dep-btn.danger:hover { background: #b91c1c; color: #fff; }

            /* Sections */
            .rmbz-dep-section { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 0; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); overflow: hidden; }
            .rmbz-dep-section-title { font-size: 14px; font-weight: 700; text-transform: uppercase; color: #1d2327; letter-spacing: 0.3px; margin: 0; padding: 16px 20px; background: #f7f7fb; border-bottom: 1px solid #e1e4e8; display: flex; align-items: center; gap: 10px; }
            .rmbz-dep-section-count { display: inline-block; padding: 2px 9px; background: #1d2327; color: #f0b90b; border-radius: 12px; font-size: 11px; font-weight: 700; }

            /* Sub-tabs */
            .rmbz-dep-subtabs { display: flex; gap: 2px; padding: 0 20px; background: #fafafa; border-bottom: 1px solid #e1e4e8; }
            .rmbz-dep-subtabs a { padding: 10px 16px; text-decoration: none; color: #5f6368; font-weight: 600; font-size: 12px; border-bottom: 3px solid transparent; margin-bottom: -1px; transition: 0.15s; }
            .rmbz-dep-subtabs a:hover { color: #1d2327; }
            .rmbz-dep-subtabs a.active { color: #1d2327; border-bottom-color: #f0b90b; }

            /* Tabela */
            .rmbz-dep-table-wrap { overflow-x: auto; }
            .rmbz-dep-table { width: 100%; border-collapse: collapse; }
            .rmbz-dep-table thead th { background: #fafafa; padding: 10px 16px; text-align: left; font-size: 11px; text-transform: uppercase; font-weight: 700; color: #5f6368; letter-spacing: 0.5px; border-bottom: 1px solid #e1e4e8; }
            .rmbz-dep-table tbody td { padding: 14px 16px; border-bottom: 1px solid #f0f0f1; font-size: 13px; color: #3c434a; vertical-align: middle; }
            .rmbz-dep-table tbody tr:last-child td { border-bottom: none; }
            .rmbz-dep-table tbody tr.rmbz-dep-row-clickable { cursor: pointer; }
            .rmbz-dep-table tbody tr:hover td { background: #fbfbfc; }

            /* Badges & amount */
            .rmbz-dep-badge { display: inline-block; padding: 3px 9px; border-radius: 12px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.3px; }
            .rmbz-dep-badge.first      { background: #fef3c7; color: #92400e; margin-left: 6px; }
            .rmbz-dep-badge.origin-app  { background: #dbeafe; color: #1e40af; }
            .rmbz-dep-badge.origin-site { background: #e0e7ff; color: #3730a3; }
            .rmbz-dep-badge.origin-old  { background: #f3f4f6; color: #6b7280; text-transform: none; font-weight: 500; }

            .rmbz-dep-amount { color: #1e40af; font-size: 14px; font-weight: 700; font-variant-numeric: tabular-nums; }
            .rmbz-dep-method { font-size: 11px; color: #5f6368; margin-top: 2px; font-weight: 500; }
            .rmbz-dep-trxid  { display: inline-block; background: #f1f3f5; padding: 3px 8px; border-radius: 6px; font-size: 11px; font-family: ui-monospace, "SF Mono", "Cascadia Code", monospace; color: #3c434a; cursor: text; user-select: all; }

            /* Countdown */
            .rmbz-dep-countdown { margin-top: 4px; font-size: 11px; font-weight: 600; }
            .rmbz-dep-countdown.ok      { color: #047857; }
            .rmbz-dep-countdown.warn    { color: #b45309; }
            .rmbz-dep-countdown.urgent  { color: #b91c1c; }
            .rmbz-dep-countdown.expired { color: #b91c1c; font-weight: 700; }

            /* Status pills histórico */
            .rmbz-dep-status { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; }
            .rmbz-dep-status.status-approved  { background: #d1fae5; color: #065f46; }
            .rmbz-dep-status.status-rejected  { background: #fee2e2; color: #991b1b; }
            .rmbz-dep-status.status-other     { background: #f1f3f5; color: #5f6368; }

            .rmbz-dep-actions { display: flex; gap: 8px; justify-content: flex-end; }

            /* Empty state */
            .rmbz-dep-empty { padding: 50px 20px; text-align: center; color: #5f6368; }
            .rmbz-dep-empty .icon { font-size: 42px; margin-bottom: 10px; opacity: 0.4; }
            .rmbz-dep-empty .msg  { font-size: 14px; }

            /* Paginação */
            .rmbz-dep-pagination { display: flex; justify-content: space-between; align-items: center; padding: 14px 20px; border-top: 1px solid #f0f0f1; background: #fbfbfc; }
            .rmbz-dep-pagination .info { color: #5f6368; font-size: 12px; }
            .rmbz-dep-pagination .links { display: flex; gap: 4px; }
            .rmbz-dep-pagination .links a, .rmbz-dep-pagination .links span { padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; text-decoration: none; }
            .rmbz-dep-pagination .links a { background: #fff; color: #3c434a; border: 1px solid #e1e4e8; }
            .rmbz-dep-pagination .links a:hover { background: #1d2327; color: #f0b90b; border-color: #1d2327; }
            .rmbz-dep-pagination .links span.current { background: #1d2327; color: #f0b90b; border: 1px solid #1d2327; }
            .rmbz-dep-pagination .links span.dots { background: transparent; color: #aaa; border: none; }

            /* ========== LAYOUT LEGACY (mantido para modal) ========== */
            /* Hero — cabeçalho com fundo escuro tinha problema de contraste
             * (título escuro sobre fundo escuro). Aqui forçamos cor clara. */
            .rmbz-deposits-hero {
                background: linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 60%, #1f1f1f 100%);
                color: #fff;
                padding: 22px 26px;
                border-radius: 14px;
                margin-bottom: 22px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.12);
                position: relative;
                overflow: hidden;
            }
            .rmbz-deposits-hero::before {
                /* Bloom dourado subtil canto superior direito — marca 1MZ */
                content: '';
                position: absolute;
                top: -40%; right: -10%;
                width: 50%; height: 180%;
                background: radial-gradient(circle, rgba(240,185,11,0.18) 0%, transparent 60%);
                pointer-events: none;
            }
            .rmbz-deposits-hero > div { position: relative; z-index: 1; }
            .rmbz-deposits-hero h1 {
                color: #fff !important;
                font-size: 26px;
                margin: 0 0 4px 0;
            }
            .rmbz-deposits-hero p {
                color: rgba(255,255,255,0.72) !important;
                margin: 0;
                font-size: 14px;
            }

            /* Pills de sumário (Pendentes / Histórico) no topo direito */
            .rmbz-deposits-summary {
                display: flex; gap: 12px;
            }
            .rmbz-stat-pill {
                background: rgba(255,255,255,0.08);
                border: 1px solid rgba(240,185,11,0.25);
                border-radius: 10px;
                padding: 10px 18px;
                display: flex; flex-direction: column; align-items: center;
                min-width: 90px;
            }
            .rmbz-stat-label {
                font-size: 10px; letter-spacing: 0.1em;
                text-transform: uppercase;
                color: rgba(255,255,255,0.6);
            }
            .rmbz-stat-value {
                font-size: 22px; font-weight: 800;
                color: #f0b90b; line-height: 1.1;
                margin-top: 2px;
            }

            /* Card de pendentes com borda dourada no topo (substitui o
             * style inline que estava no antigo). */
            .rmbz-deposits-modern .rmbz-deposits-pendentes {
                border-top: 4px solid #f0b90b;
            }

            /* Botão Ver Detalhe — classe dedicada, com cores explícitas
             * (não depende do .btn-outline herdado que estava a renderizar
             * fantasma por causa de uma var() não definida no admin). */
            .rmbz-dep-view-btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                padding: 7px 14px;
                border-radius: 8px;
                font-size: 12px;
                font-weight: 600;
                cursor: pointer;
                background: #1a1a1a;
                color: #f0b90b;
                border: 1px solid #f0b90b;
                transition: all 0.18s ease;
                white-space: nowrap;
            }
            .rmbz-dep-view-btn:hover {
                background: #f0b90b;
                color: #1a1a1a;
                transform: translateY(-1px);
                box-shadow: 0 3px 8px rgba(240,185,11,0.35);
            }

            /* ========== ESTILOS DA MODAL DE DETALHE ========== */
            .rmbz-dep-modal {
                position: fixed; inset: 0; z-index: 100000;
                display: none; align-items: center; justify-content: center;
                padding: 20px;
            }
            .rmbz-dep-modal.is-open { display: flex; }
            .rmbz-dep-modal-backdrop {
                position: absolute; inset: 0;
                background: rgba(10, 10, 10, 0.65);
                backdrop-filter: blur(2px);
            }
            .rmbz-dep-modal-dialog {
                position: relative;
                background: #fff;
                border-radius: 14px;
                box-shadow: 0 20px 60px rgba(0,0,0,0.4);
                max-width: 920px;
                width: 100%;
                max-height: 92vh;
                overflow: hidden;
                display: flex; flex-direction: column;
            }
            .rmbz-dep-modal-header {
                display: flex; justify-content: space-between; align-items: center;
                padding: 16px 22px;
                border-bottom: 1px solid #eee;
                background: linear-gradient(135deg, #1a1a1a, #2a2a2a);
                color: #fff;
            }
            .rmbz-dep-modal-header h3 { margin: 0; font-size: 18px; color: #fff; }
            .rmbz-dep-modal-close {
                background: transparent; border: 0; color: #fff;
                font-size: 28px; cursor: pointer; line-height: 1;
                padding: 0 8px; opacity: 0.8;
            }
            .rmbz-dep-modal-close:hover { opacity: 1; }
            .rmbz-dep-modal-body {
                padding: 20px 22px;
                overflow-y: auto;
            }
            .rmbz-dep-modal-grid {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 24px;
            }
            @media (max-width: 720px) {
                .rmbz-dep-modal-grid { grid-template-columns: 1fr; }
                .rmbz-deposits-hero {
                    flex-direction: column; gap: 14px; align-items: flex-start;
                }
                .rmbz-deposits-summary { width: 100%; }
                .rmbz-stat-pill { flex: 1; }
            }
            .rmbz-dep-modal-info dl {
                margin: 0;
                display: grid;
                grid-template-columns: 140px 1fr;
                gap: 6px 12px;
            }
            .rmbz-dep-modal-info dt {
                font-size: 12px; color: #666; font-weight: 600;
                text-transform: uppercase; letter-spacing: 0.04em;
            }
            .rmbz-dep-modal-info dd {
                margin: 0; font-size: 14px; color: #222;
                word-break: break-word;
            }
            .rmbz-dep-modal-info dd.amount { font-size: 18px; font-weight: 700; color: #2563eb; }
            .rmbz-dep-modal-info dd.status-aprovado { font-weight: 700; color: #10b981; }
            .rmbz-dep-modal-info dd.status-rejeitado { font-weight: 700; color: #6b7280; }
            .rmbz-dep-notes-block {
                margin-top: 20px;
                padding-top: 16px;
                border-top: 1px dashed #ddd;
            }
            .rmbz-dep-notes-block strong {
                display: block; margin-bottom: 6px;
                font-size: 12px; color: #666;
                text-transform: uppercase; letter-spacing: 0.04em;
            }
            .rmbz-dep-notes {
                margin: 0; padding: 10px 12px;
                background: #f7f7f7; border-radius: 8px;
                font-size: 13px; color: #333;
                white-space: pre-wrap;
            }
            .rmbz-dep-modal-proof strong {
                display: block; margin-bottom: 8px;
                font-size: 12px; color: #666;
                text-transform: uppercase; letter-spacing: 0.04em;
            }
            .rmbz-dep-proof-wrap {
                border: 1px solid #eee; border-radius: 10px;
                padding: 10px; background: #fafafa;
                min-height: 220px; display: flex;
                align-items: center; justify-content: center;
            }
            .rmbz-dep-proof-wrap img {
                max-width: 100%; max-height: 420px;
                border-radius: 6px; cursor: zoom-in;
                box-shadow: 0 4px 12px rgba(0,0,0,0.12);
            }
            .rmbz-dep-no-proof { color: #999; font-style: italic; margin: 0; }
        </style>

        <script>
            // [1.6.118.3] Função global para confirmar delete com input "APAGAR"
            window.rmbzDepConfirmDelete = function (anchorEl) {
                var typed = window.prompt(
                    'Apagar este registo é IRREVERSÍVEL. Vai apagar o pedido e o ficheiro do comprovativo.\n\nPara confirmar, escreve APAGAR em maiúsculas:'
                );
                if (typed === null) return false;
                if (typed.trim() !== 'APAGAR') {
                    alert('Confirmação incorrecta. Operação cancelada.');
                    return false;
                }
                return true;
            };

            (function () {
                var modal = document.getElementById('rmbz-dep-modal');
                if (!modal) return;

                function formatDate(s) {
                    if (!s || s === '0000-00-00 00:00:00') return '—';
                    // O servidor envia 'YYYY-MM-DD HH:MM:SS' (MySQL). Mostramos
                    // como veio, sem reformatar — mantém consistência com o
                    // resto do admin.
                    return s;
                }
                function formatAmount(n) {
                    if (typeof n !== 'number') n = parseFloat(n) || 0;
                    return n.toLocaleString('pt-PT', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2,
                    }) + ' MT';
                }
                function setText(id, val) {
                    var el = document.getElementById(id);
                    if (el) el.textContent = (val == null || val === '') ? '—' : String(val);
                }

                function openWith(data) {
                    setText('md-id', '#' + data.id);
                    setText('md-artist', data.user_telemovel);
                    setText('md-method', data.payment_method);
                    setText('md-sender', data.sender_phone);
                    setText('md-trxid', data.transaction_id);
                    setText('md-req-date', formatDate(data.request_date));
                    setText('md-proc-date', formatDate(data.processed_date));
                    setText('md-notes', data.admin_notes && data.admin_notes.trim() !== ''
                        ? data.admin_notes
                        : 'Sem notas registadas.');

                    // [1.6.118] Origem (app|site|—)
                    var origemEl = document.getElementById('md-origem');
                    if (origemEl) {
                        var origemTxt = '— antigo';
                        if (data.source_platform === 'app') origemTxt = '📱 App Android';
                        else if (data.source_platform === 'site') origemTxt = '🌐 Site';
                        origemEl.textContent = origemTxt;
                    }

                    // [1.6.118] Banner com badge "Abertura" e countdown
                    var banner = document.getElementById('md-banner');
                    if (banner) {
                        banner.innerHTML = '';
                        if (data.is_first_deposit) {
                            var expiraTs = new Date(data.request_date + 'Z').getTime() + 24 * 3600 * 1000;
                            var nowTs = Date.now();
                            var segsRest = Math.floor((expiraTs - nowTs) / 1000);
                            var html = '<div style="padding:10px 14px; background:#fef3c7; border-left:4px solid #f59e0b; border-radius:6px;">';
                            html += '<strong style="color:#92400e;">🆕 Primeiro depósito (abertura de conta)</strong><br>';
                            if (data.status === 'pendente') {
                                if (segsRest > 0) {
                                    var h = Math.floor(segsRest / 3600);
                                    var m = Math.floor((segsRest % 3600) / 60);
                                    var cor = h < 6 ? '#dc2626' : (h < 12 ? '#f59e0b' : '#059669');
                                    html += '<span style="color:' + cor + '; font-weight:600; font-size:13px;">⏱ Expira em ' + h + 'h ' + m + 'm — se não aprovado, conta será apagada automaticamente.</span>';
                                } else {
                                    html += '<span style="color:#dc2626; font-weight:700;">⚠ Período de 24h expirado — conta será apagada no próximo ciclo.</span>';
                                }
                            } else {
                                html += '<span style="color:#666; font-size:13px;">Este foi o primeiro depósito deste user (abertura de conta).</span>';
                            }
                            html += '</div>';
                            banner.innerHTML = html;
                        }
                    }

                    // [1.6.118] Botões aprovar/rejeitar — só visíveis se pendente
                    var actions = document.getElementById('md-actions');
                    var btnApr = document.getElementById('md-btn-approve');
                    var btnRej = document.getElementById('md-btn-reject');
                    if (actions && btnApr && btnRej) {
                        if (data.status === 'pendente' && data.approve_url && data.reject_url) {
                            btnApr.href = data.approve_url;
                            btnRej.href = data.reject_url;
                            actions.style.display = 'flex';
                        } else {
                            actions.style.display = 'none';
                        }
                    }

                    // [1.6.118.3] Botão APAGAR — só visível para REJEITADOS
                    var deleteBlock = document.getElementById('md-delete-block');
                    var btnDelete = document.getElementById('md-btn-delete');
                    if (deleteBlock && btnDelete) {
                        if (data.status === 'rejeitado' && data.delete_url) {
                            btnDelete.href = data.delete_url;
                            deleteBlock.style.display = 'block';
                        } else {
                            deleteBlock.style.display = 'none';
                        }
                    }

                    // Status com classe colorida
                    var statusEl = document.getElementById('md-status');
                    if (statusEl) {
                        statusEl.textContent = (data.status || '—')
                            .charAt(0).toUpperCase() + (data.status || '').slice(1);
                        statusEl.className = 'status-' + (data.status || '');
                    }

                    // Valor com cor
                    var amountEl = document.getElementById('md-amount');
                    if (amountEl) {
                        amountEl.textContent = formatAmount(data.amount);
                        amountEl.className = 'amount';
                    }

                    // Comprovativo
                    var proofWrap = document.getElementById('md-proof-wrap');
                    if (proofWrap) {
                        if (data.proof_image && data.proof_image.trim() !== '') {
                            proofWrap.innerHTML = '';
                            var img = document.createElement('img');
                            img.src = data.proof_image;
                            img.alt = 'Comprovativo do depósito';
                            img.addEventListener('click', function () {
                                window.open(data.proof_image, '_blank', 'noopener');
                            });
                            proofWrap.appendChild(img);
                        } else {
                            proofWrap.innerHTML = '<p class="rmbz-dep-no-proof">Sem imagem anexada.</p>';
                        }
                    }

                    modal.classList.add('is-open');
                    modal.setAttribute('aria-hidden', 'false');
                }

                function closeModal() {
                    modal.classList.remove('is-open');
                    modal.setAttribute('aria-hidden', 'true');
                }

                // Botões Ver Detalhe — delegamos ao document para apanhar
                // qualquer linha mesmo que sejam adicionadas dinamicamente.
                document.addEventListener('click', function (e) {
                    var btn = e.target.closest('.rmbz-dep-detail-btn');
                    if (btn) {
                        try {
                            var data = JSON.parse(btn.getAttribute('data-deposit'));
                            openWith(data);
                        } catch (err) {
                            console.error('1MZ: payload inválido no botão', err);
                        }
                        return;
                    }
                    if (e.target.closest('[data-close-modal]')) {
                        closeModal();
                    }
                });

                // ESC fecha
                document.addEventListener('keydown', function (e) {
                    if (e.key === 'Escape' && modal.classList.contains('is-open')) {
                        closeModal();
                    }
                });
            })();
        </script>
    </div>
    <?php
}

/**
 * --------------------------------------------------------------------------
 * 5. PÁGINA: PEDIDOS DE LEVANTAMENTO
 * --------------------------------------------------------------------------
 */
function rmbz_mostrar_pagina_pedidos_levantamento() {
    rmbz_admin_modern_styles();
    global $wpdb;
    $table_name = $wpdb->prefix . 'rmbz_withdrawal_requests';

    // [1.6.118.18] Filtros + paginação
    $filter_source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : '';        // wallet|royalties|''
    $filter_method = isset($_GET['method']) ? sanitize_text_field($_GET['method']) : '';        // mpesa|emola|''
    $filter_risk   = isset($_GET['risk'])   ? sanitize_text_field($_GET['risk'])   : '';        // ok|med|hi|crit|''
    $filter_hist_status = isset($_GET['hst']) ? sanitize_text_field($_GET['hst'])  : '';        // aprovado|rejeitado|''
    $search_tel    = isset($_GET['s'])      ? sanitize_text_field($_GET['s'])      : '';
    $page_hist     = max(1, isset($_GET['p']) ? absint($_GET['p']) : 1);
    $per_page_hist = 25;
    $offset_hist   = ($page_hist - 1) * $per_page_hist;

    // ─── Pendentes (todos, sem paginação — admin precisa ver tudo) ────
    $where_pend = "WHERE status = 'pendente'";
    $params_pend = array();
    if ($filter_source === 'wallet' || $filter_source === 'royalties') {
        $where_pend .= " AND source = %s";
        $params_pend[] = $filter_source;
    }
    if ($filter_method !== '') {
        $where_pend .= " AND payment_method LIKE %s";
        $params_pend[] = '%' . $wpdb->esc_like($filter_method) . '%';
    }
    if ($search_tel !== '') {
        $where_pend .= " AND user_telemovel LIKE %s";
        $params_pend[] = '%' . $wpdb->esc_like($search_tel) . '%';
    }
    $sql_pend = "SELECT * FROM {$table_name} $where_pend ORDER BY request_date ASC";
    $pendentes = empty($params_pend)
        ? $wpdb->get_results($sql_pend)
        : $wpdb->get_results($wpdb->prepare($sql_pend, $params_pend));

    // ─── Filtro risco aplicado em PHP (porque depende de função externa) ─
    $pendentes_filtered = $pendentes;
    if ($filter_risk !== '' && function_exists('rmbz_wg_build_forensic_report')) {
        $pendentes_filtered = array_filter($pendentes, function($req) use ($filter_risk) {
            $r = rmbz_wg_build_forensic_report($req);
            $s = (int) $r['risk_score'];
            if ($filter_risk === 'crit') return $s >= 80;
            if ($filter_risk === 'hi')   return $s >= 40 && $s < 80;
            if ($filter_risk === 'med')  return $s >= 15 && $s < 40;
            if ($filter_risk === 'ok')   return $s < 15;
            return true;
        });
    }

    // ─── Histórico (paginado + filtros) ────────────────────────────────
    $where_hist = "WHERE status != 'pendente'";
    $params_hist = array();
    if ($filter_hist_status === 'aprovado' || $filter_hist_status === 'rejeitado') {
        $where_hist .= " AND status = %s";
        $params_hist[] = $filter_hist_status;
    }
    if ($filter_source === 'wallet' || $filter_source === 'royalties') {
        $where_hist .= " AND source = %s";
        $params_hist[] = $filter_source;
    }
    if ($filter_method !== '') {
        $where_hist .= " AND payment_method LIKE %s";
        $params_hist[] = '%' . $wpdb->esc_like($filter_method) . '%';
    }
    if ($search_tel !== '') {
        $where_hist .= " AND user_telemovel LIKE %s";
        $params_hist[] = '%' . $wpdb->esc_like($search_tel) . '%';
    }
    $sql_count_hist = "SELECT COUNT(*) FROM {$table_name} $where_hist";
    $total_hist = empty($params_hist)
        ? (int) $wpdb->get_var($sql_count_hist)
        : (int) $wpdb->get_var($wpdb->prepare($sql_count_hist, $params_hist));
    $total_pages_hist = max(1, ceil($total_hist / $per_page_hist));

    $sql_hist = "SELECT * FROM {$table_name} $where_hist ORDER BY processed_date DESC LIMIT %d OFFSET %d";
    $params_hist_query = array_merge($params_hist, array($per_page_hist, $offset_hist));
    $historico = $wpdb->get_results($wpdb->prepare($sql_hist, $params_hist_query));

    // ─── Estatísticas globais (todos, não filtrado) ────────────────────
    $stats = $wpdb->get_row(
        "SELECT
            SUM(CASE WHEN status='pendente'  THEN 1 ELSE 0 END) AS pendentes_cnt,
            SUM(CASE WHEN status='pendente'  THEN amount ELSE 0 END) AS pendentes_valor,
            SUM(CASE WHEN status='aprovado'  THEN 1 ELSE 0 END) AS aprovados_cnt,
            SUM(CASE WHEN status='aprovado'  THEN amount ELSE 0 END) AS aprovados_valor,
            SUM(CASE WHEN status='rejeitado' THEN 1 ELSE 0 END) AS rejeitados_cnt,
            SUM(CASE WHEN status='pendente'  AND source='royalties' THEN 1 ELSE 0 END) AS pendentes_royalties,
            SUM(CASE WHEN status='pendente'  AND (source='wallet' OR source IS NULL) THEN 1 ELSE 0 END) AS pendentes_wallet
         FROM {$table_name}"
    );

    // Helper URL preservando query string
    $build_url = function( $overrides = array() ) use ( $filter_source, $filter_method, $filter_risk, $filter_hist_status, $search_tel, $page_hist ) {
        $args = array( 'page' => 'rmbz-pedidos-levantamento' );
        if ($filter_source !== '')      $args['source'] = $filter_source;
        if ($filter_method !== '')      $args['method'] = $filter_method;
        if ($filter_risk !== '')        $args['risk']   = $filter_risk;
        if ($filter_hist_status !== '') $args['hst']    = $filter_hist_status;
        if ($search_tel !== '')         $args['s']      = $search_tel;
        if ($page_hist > 1)             $args['p']      = $page_hist;
        foreach ($overrides as $k => $v) {
            if ($v === null) unset($args[$k]);
            else $args[$k] = $v;
        }
        return admin_url('admin.php?' . http_build_query($args));
    };

    $has_filters = ($filter_source || $filter_method || $filter_risk || $filter_hist_status || $search_tel !== '');
    ?>
    <div class="rmbz-admin-wrap rmbz-withdrawals-modern">

        <!-- HEADER -->
        <div class="rmbz-wd-head">
            <h1>💸 Pedidos de Levantamento</h1>
            <p>Gira os pagamentos aos artistas. <strong>Antes de aprovar, abra "🔍 Investigar" para ver a análise forense completa</strong> (Guarda-Costas).</p>
        </div>

        <!-- STATS GRID -->
        <div class="rmbz-wd-stats-grid">
            <div class="rmbz-wd-stat-card warn">
                <div class="label">Pendentes</div>
                <div class="value"><?php echo (int) $stats->pendentes_cnt; ?></div>
                <div class="sub"><?php echo number_format((float) $stats->pendentes_valor, 2, ',', '.'); ?> MT a pagar</div>
            </div>
            <div class="rmbz-wd-stat-card">
                <div class="label">Por fonte (pendentes)</div>
                <div class="value" style="font-size:14px; font-weight:600;">
                    💼 <?php echo (int) $stats->pendentes_wallet; ?>
                    &nbsp;·&nbsp;
                    🎵 <?php echo (int) $stats->pendentes_royalties; ?>
                </div>
                <div class="sub">Carteira · Royalties</div>
            </div>
            <div class="rmbz-wd-stat-card success">
                <div class="label">Aprovados histórico</div>
                <div class="value"><?php echo number_format((int) $stats->aprovados_cnt, 0, ',', '.'); ?></div>
                <div class="sub"><?php echo number_format((float) $stats->aprovados_valor, 2, ',', '.'); ?> MT pagos</div>
            </div>
            <div class="rmbz-wd-stat-card danger">
                <div class="label">Rejeitados histórico</div>
                <div class="value"><?php echo number_format((int) $stats->rejeitados_cnt, 0, ',', '.'); ?></div>
            </div>
        </div>

        <!-- TOOLBAR -->
        <div class="rmbz-wd-toolbar">
            <form method="get" class="rmbz-wd-search">
                <input type="hidden" name="page" value="rmbz-pedidos-levantamento">
                <?php foreach (['source'=>$filter_source, 'method'=>$filter_method, 'risk'=>$filter_risk, 'hst'=>$filter_hist_status] as $k => $v):
                    if ($v !== ''): ?>
                        <input type="hidden" name="<?php echo esc_attr($k); ?>" value="<?php echo esc_attr($v); ?>">
                    <?php endif;
                endforeach; ?>
                <input type="text" name="s" value="<?php echo esc_attr($search_tel); ?>" placeholder="🔍 Pesquisar por telemóvel…" class="rmbz-wd-search-input">
                <button type="submit" class="rmbz-wd-btn">Procurar</button>
                <?php if ($has_filters): ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=rmbz-pedidos-levantamento')); ?>" class="rmbz-wd-btn ghost">Limpar filtros</a>
                <?php endif; ?>
            </form>

            <div class="rmbz-wd-filter-group">
                <span class="rmbz-wd-filter-label">Fonte:</span>
                <a href="<?php echo esc_url($build_url(['source'=>null,'p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_source === '' ? 'active' : ''; ?>">Todas</a>
                <a href="<?php echo esc_url($build_url(['source'=>'wallet','p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_source === 'wallet' ? 'active' : ''; ?>">💼 Carteira</a>
                <a href="<?php echo esc_url($build_url(['source'=>'royalties','p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_source === 'royalties' ? 'active' : ''; ?>">🎵 Royalties</a>
            </div>

            <div class="rmbz-wd-filter-group">
                <span class="rmbz-wd-filter-label">Método:</span>
                <a href="<?php echo esc_url($build_url(['method'=>null,'p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_method === '' ? 'active' : ''; ?>">Todos</a>
                <a href="<?php echo esc_url($build_url(['method'=>'M-Pesa','p'=>null])); ?>" class="rmbz-wd-chip <?php echo stripos($filter_method, 'pesa') !== false ? 'active' : ''; ?>">M-Pesa</a>
                <a href="<?php echo esc_url($build_url(['method'=>'E-Mola','p'=>null])); ?>" class="rmbz-wd-chip <?php echo stripos($filter_method, 'mola') !== false ? 'active' : ''; ?>">E-Mola</a>
            </div>

            <div class="rmbz-wd-filter-group">
                <span class="rmbz-wd-filter-label">Risco:</span>
                <a href="<?php echo esc_url($build_url(['risk'=>null,'p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_risk === '' ? 'active' : ''; ?>">Todos</a>
                <a href="<?php echo esc_url($build_url(['risk'=>'ok','p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_risk === 'ok' ? 'active' : ''; ?>">🟢 OK</a>
                <a href="<?php echo esc_url($build_url(['risk'=>'med','p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_risk === 'med' ? 'active' : ''; ?>">🟡 Médio</a>
                <a href="<?php echo esc_url($build_url(['risk'=>'hi','p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_risk === 'hi' ? 'active' : ''; ?>">🟠 Alto</a>
                <a href="<?php echo esc_url($build_url(['risk'=>'crit','p'=>null])); ?>" class="rmbz-wd-chip <?php echo $filter_risk === 'crit' ? 'active' : ''; ?>">🔴 Crítico</a>
            </div>
        </div>

        <!-- PENDENTES -->
        <div class="rmbz-wd-section">
            <h3 class="rmbz-wd-section-title">
                ⏳ Pendentes (A Aguardar Pagamento)
                <span class="rmbz-wd-section-count"><?php echo (int) count($pendentes_filtered); ?><?php if ($has_filters && (int) $stats->pendentes_cnt > count($pendentes_filtered)) echo ' de ' . (int) $stats->pendentes_cnt; ?></span>
            </h3>
            <?php if ( empty( $pendentes_filtered ) ) : ?>
                <div class="rmbz-wd-empty">
                    <div class="icon">✓</div>
                    <div class="msg">
                        <?php echo $has_filters ? 'Nenhum levantamento pendente com estes filtros.' : 'Nenhum pedido pendente. Tudo pago!'; ?>
                    </div>
                </div>
            <?php else : ?>
                <div class="rmbz-wd-table-wrap">
                    <table class="rmbz-wd-table">
                        <thead><tr>
                            <th>Data</th>
                            <th>Artista</th>
                            <th>Valor</th>
                            <th>Fonte</th>
                            <th>Método e Conta</th>
                            <th>Risco</th>
                            <th style="text-align:right;">Ações</th>
                        </tr></thead>
                        <tbody>
                            <?php foreach ( $pendentes_filtered as $req ) :
                                // [FEAT 1.5.22] Calcular score de risco (Guarda-Costas)
                                $wg_score = 0;
                                $wg_checklist_done = false;
                                if ( function_exists('rmbz_wg_build_forensic_report') ) {
                                    $wg_report = rmbz_wg_build_forensic_report( $req );
                                    $wg_score = (int) $wg_report['risk_score'];
                                    $wg_checklist_done = rmbz_wg_checklist_complete( $req->id );
                                }
                                $wg_class = $wg_score >= 80 ? 'crit' : ($wg_score >= 40 ? 'hi' : ($wg_score >= 15 ? 'med' : 'ok'));
                                $wg_label = $wg_score >= 80 ? 'CRÍTICO' : ($wg_score >= 40 ? 'ALTO' : ($wg_score >= 15 ? 'MÉDIO' : 'OK'));

                                $link_apr   = wp_nonce_url(admin_url('admin-post.php?action=rmbz_approve_withdrawal&req_id=' . $req->id), 'rmbz_approve_withdrawal_nonce_' . $req->id);
                                $link_rej   = wp_nonce_url(admin_url('admin-post.php?action=rmbz_reject_withdrawal&req_id=' . $req->id), 'rmbz_reject_withdrawal_nonce_' . $req->id);
                                $link_guard = admin_url('admin.php?page=rmbz-withdrawal-guard&id=' . $req->id);

                                $req_source = isset($req->source) ? $req->source : 'wallet';
                            ?>
                                <tr>
                                    <td><?php echo rmbz_safe_date_format($req->request_date); ?></td>
                                    <td><strong><?php echo esc_html( $req->user_telemovel ); ?></strong></td>
                                    <td><span class="rmbz-wd-amount"><?php echo number_format((float)$req->amount, 2, ',', '.'); ?> MT</span></td>
                                    <td>
                                        <?php if ( $req_source === 'royalties' ): ?>
                                            <span class="rmbz-wd-badge royalties">🎵 Royalties</span>
                                        <?php else: ?>
                                            <span class="rmbz-wd-badge wallet">💼 Carteira</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="rmbz-wd-method-badge"><?php echo esc_html( $req->payment_method ); ?></span>
                                        <div class="rmbz-wd-account"><?php echo esc_html( $req->payment_details ); ?></div>
                                    </td>
                                    <td>
                                        <span class="rmbz-wd-risk <?php echo $wg_class; ?>">
                                            <?php echo $wg_score; ?> · <?php echo $wg_label; ?>
                                        </span>
                                        <?php if ( $wg_checklist_done ): ?>
                                            <div class="rmbz-wd-checklist done">☑️ Checklist OK</div>
                                        <?php else: ?>
                                            <div class="rmbz-wd-checklist pending">☐ Checklist pendente</div>
                                        <?php endif; ?>
                                    </td>
                                    <td style="text-align:right;">
                                        <div class="rmbz-wd-actions">
                                            <a href="<?php echo esc_url($link_guard); ?>" class="rmbz-wd-btn info small">🔍 Investigar</a>
                                            <a href="<?php echo esc_url($link_apr); ?>"
                                               class="rmbz-wd-btn small <?php echo $wg_checklist_done ? 'success' : 'disabled'; ?>"
                                               <?php if ( $wg_checklist_done ): ?>
                                                   onclick="return confirm('Já efetuou a transferência para o artista?');"
                                               <?php else: ?>
                                                   onclick="event.preventDefault(); alert('🔒 Aprovação bloqueada. Abra Investigar e complete a Checklist primeiro.');"
                                               <?php endif; ?>>
                                                Pagar &amp; Aprovar
                                            </a>
                                            <a href="<?php echo esc_url($link_rej); ?>" class="rmbz-wd-btn danger small" onclick="return confirm('Rejeitar e devolver saldo ao artista?');">Rejeitar</a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- HISTÓRICO -->
        <div class="rmbz-wd-section">
            <h3 class="rmbz-wd-section-title">
                📜 Histórico de Pagamentos
                <span class="rmbz-wd-section-count"><?php echo number_format($total_hist, 0, ',', '.'); ?></span>
            </h3>

            <div class="rmbz-wd-subtabs">
                <a href="<?php echo esc_url($build_url(['hst'=>null,'p'=>null])); ?>" class="<?php echo $filter_hist_status === '' ? 'active' : ''; ?>">Todos</a>
                <a href="<?php echo esc_url($build_url(['hst'=>'aprovado','p'=>null])); ?>" class="<?php echo $filter_hist_status === 'aprovado' ? 'active' : ''; ?>">✓ Aprovados</a>
                <a href="<?php echo esc_url($build_url(['hst'=>'rejeitado','p'=>null])); ?>" class="<?php echo $filter_hist_status === 'rejeitado' ? 'active' : ''; ?>">✗ Rejeitados</a>
            </div>

            <?php if ( empty( $historico ) ) : ?>
                <div class="rmbz-wd-empty">
                    <div class="icon">📭</div>
                    <div class="msg">
                        <?php echo $has_filters ? 'Nenhum levantamento no histórico com estes filtros.' : 'Sem histórico de levantamentos ainda.'; ?>
                    </div>
                </div>
            <?php else : ?>
                <div class="rmbz-wd-table-wrap">
                    <table class="rmbz-wd-table">
                        <thead><tr>
                            <th>Processado</th>
                            <th>Artista</th>
                            <th>Valor</th>
                            <th>Fonte</th>
                            <th>Método</th>
                            <th>Status</th>
                            <th style="text-align:right;">Detalhe</th>
                        </tr></thead>
                        <tbody>
                            <?php foreach ( $historico as $req ) :
                                $st_class = ($req->status === 'aprovado') ? 'status-approved' : (($req->status === 'rejeitado') ? 'status-rejected' : 'status-other');
                                $req_source = isset($req->source) ? $req->source : 'wallet';
                                $link_fatura = home_url( '/fatura/comprovativo-' . $req->id . '-' . rawurlencode($req->user_telemovel) );

                                $modal_data = wp_json_encode([
                                    'id'              => (int) $req->id,
                                    'user_telemovel'  => $req->user_telemovel,
                                    'amount'          => (float) $req->amount,
                                    'source'          => $req_source,
                                    'exchange_rate'   => isset($req->exchange_rate) ? (float) $req->exchange_rate : null,
                                    'status'          => $req->status,
                                    'payment_method'  => $req->payment_method,
                                    'payment_details' => $req->payment_details,
                                    'request_date'    => $req->request_date,
                                    'processed_date'  => $req->processed_date,
                                    'admin_notes'     => $req->admin_notes,
                                    'invoice_url'     => ($req->status === 'aprovado') ? $link_fatura : '',
                                ]);
                            ?>
                                <tr>
                                    <td><?php echo rmbz_safe_date_format($req->processed_date); ?></td>
                                    <td><?php echo esc_html( $req->user_telemovel ); ?></td>
                                    <td><span class="rmbz-wd-amount"><?php echo number_format((float)$req->amount, 2, ',', '.'); ?> MT</span></td>
                                    <td>
                                        <?php if ( $req_source === 'royalties' ): ?>
                                            <span class="rmbz-wd-badge royalties small">🎵 Royalties</span>
                                        <?php else: ?>
                                            <span class="rmbz-wd-badge wallet small">💼 Carteira</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo esc_html( $req->payment_method ); ?></td>
                                    <td><span class="rmbz-wd-status <?php echo $st_class; ?>"><?php echo esc_html( ucfirst($req->status) ); ?></span></td>
                                    <td style="text-align:right;">
                                        <button type="button" class="rmbz-wd-btn ghost small rmbz-wd-view-btn rmbz-wd-detail-btn"
                                                data-withdrawal='<?php echo esc_attr( $modal_data ); ?>'>
                                            Ver Detalhe →
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($total_pages_hist > 1): ?>
                    <div class="rmbz-wd-pagination">
                        <div class="info">
                            Mostrando <?php echo $offset_hist + 1; ?>–<?php echo min($offset_hist + count($historico), $total_hist); ?>
                            de <?php echo number_format($total_hist, 0, ',', '.'); ?>
                        </div>
                        <div class="links">
                            <?php
                            if ($page_hist > 1) {
                                echo '<a href="' . esc_url($build_url(['p' => $page_hist - 1])) . '">‹</a>';
                            }
                            $start_p = max(1, $page_hist - 2);
                            $end_p   = min($total_pages_hist, $page_hist + 2);
                            if ($start_p > 1) {
                                echo '<a href="' . esc_url($build_url(['p' => 1])) . '">1</a>';
                                if ($start_p > 2) echo '<span class="dots">…</span>';
                            }
                            for ($i = $start_p; $i <= $end_p; $i++) {
                                if ($i === $page_hist) {
                                    echo '<span class="current">' . $i . '</span>';
                                } else {
                                    echo '<a href="' . esc_url($build_url(['p' => $i])) . '">' . $i . '</a>';
                                }
                            }
                            if ($end_p < $total_pages_hist) {
                                if ($end_p < $total_pages_hist - 1) echo '<span class="dots">…</span>';
                                echo '<a href="' . esc_url($build_url(['p' => $total_pages_hist])) . '">' . $total_pages_hist . '</a>';
                            }
                            if ($page_hist < $total_pages_hist) {
                                echo '<a href="' . esc_url($build_url(['p' => $page_hist + 1])) . '">›</a>';
                            }
                            ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- Modal de detalhe -->
        <div id="rmbz-wd-modal" class="rmbz-wd-modal" aria-hidden="true">
            <div class="rmbz-wd-modal-backdrop" data-close-wd-modal></div>
            <div class="rmbz-wd-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="rmbz-wd-modal-title">
                <div class="rmbz-wd-modal-header">
                    <h3 id="rmbz-wd-modal-title">Detalhe do Levantamento</h3>
                    <button type="button" class="rmbz-wd-modal-close" data-close-wd-modal aria-label="Fechar">&times;</button>
                </div>
                <div class="rmbz-wd-modal-body">
                    <dl class="rmbz-wd-modal-info">
                        <dt>ID do pedido</dt><dd id="wd-id">—</dd>
                        <dt>Status</dt><dd id="wd-status">—</dd>
                        <dt>Artista (telemóvel)</dt><dd id="wd-artist">—</dd>
                        <dt>Valor</dt><dd id="wd-amount">—</dd>
                        <dt>Fonte</dt><dd id="wd-source">—</dd>
                        <dt>Taxa de câmbio</dt><dd id="wd-rate">—</dd>
                        <dt>Método</dt><dd id="wd-method">—</dd>
                        <dt>Conta de destino</dt><dd id="wd-details">—</dd>
                        <dt>Pedido em</dt><dd id="wd-req-date">—</dd>
                        <dt>Processado em</dt><dd id="wd-proc-date">—</dd>
                    </dl>
                    <div class="rmbz-wd-notes-block">
                        <strong>Notas do admin</strong>
                        <p id="wd-notes" class="rmbz-wd-notes">—</p>
                    </div>
                    <div id="wd-invoice-wrap" class="rmbz-wd-invoice-wrap" style="display:none;">
                        <a id="wd-invoice-link" href="#" target="_blank" rel="noopener" class="rmbz-wd-invoice-btn">
                            📄 Abrir Fatura / Comprovativo
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <style>
            /* [1.6.118.18] REFACTOR VISUAL — light theme moderno
             * Classes novas: rmbz-wd-* (consistente com Gestão/Perfil/Depósitos).
             * Legacy CSS preservado abaixo para modal e outros usos.
             */
            .rmbz-withdrawals-modern.rmbz-admin-wrap {
                max-width: none;
                margin: 16px 20px 32px 0;
                font-family: "Roboto", -apple-system, BlinkMacSystemFont, sans-serif;
                color: #1a1a1f;
                background: transparent;
                padding: 0;
            }

            /* Header */
            .rmbz-wd-head h1 { font-size: 26px; font-weight: 800; margin: 0 0 4px 0; color: #1d2327; letter-spacing: -0.01em; }
            .rmbz-wd-head p  { margin: 0; color: #5f6368; font-size: 13px; }

            /* Stats grid */
            .rmbz-wd-stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 20px 0 18px; }
            .rmbz-wd-stat-card { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 16px 18px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
            .rmbz-wd-stat-card .label { font-size: 11px; font-weight: 700; text-transform: uppercase; color: #5f6368; letter-spacing: 0.5px; margin-bottom: 6px; }
            .rmbz-wd-stat-card .value { font-size: 26px; font-weight: 800; color: #1d2327; line-height: 1.1; }
            .rmbz-wd-stat-card .sub   { font-size: 11px; color: #5f6368; margin-top: 3px; font-weight: 500; }
            .rmbz-wd-stat-card.warn .value    { color: #9a3412; }
            .rmbz-wd-stat-card.info .value    { color: #1e40af; }
            .rmbz-wd-stat-card.success .value { color: #047857; }
            .rmbz-wd-stat-card.danger .value  { color: #b91c1c; }

            /* Toolbar */
            .rmbz-wd-toolbar { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 14px 16px; margin-bottom: 16px; display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
            .rmbz-wd-search { display: flex; gap: 8px; flex: 1; min-width: 240px; }
            .rmbz-wd-search-input { flex: 1; padding: 8px 12px; border: 1px solid #d8dae0; border-radius: 6px; font-size: 13px; }
            .rmbz-wd-filter-group { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; }
            .rmbz-wd-filter-label { font-size: 11px; color: #5f6368; text-transform: uppercase; font-weight: 700; letter-spacing: 0.5px; margin-right: 4px; }
            .rmbz-wd-chip { display: inline-flex; align-items: center; padding: 5px 11px; border-radius: 16px; background: #f1f3f5; color: #3c434a; font-size: 12px; font-weight: 600; text-decoration: none; border: 1px solid transparent; transition: 0.15s; }
            .rmbz-wd-chip:hover { background: #e9ecef; color: #1d2327; }
            .rmbz-wd-chip.active { background: #1d2327; color: #f0b90b; border-color: #1d2327; }
            .rmbz-wd-chip.active:hover { background: #1d2327; color: #f0b90b; }

            /* Botões */
            .rmbz-wd-btn { display: inline-flex; align-items: center; justify-content: center; padding: 8px 14px; background: #1d2327; color: #f0b90b; border: none; border-radius: 8px; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; cursor: pointer; text-decoration: none; transition: 0.15s; }
            .rmbz-wd-btn:hover { background: #2c2c34; color: #f0b90b; transform: translateY(-1px); }
            .rmbz-wd-btn.small { padding: 6px 10px; font-size: 11px; }
            .rmbz-wd-btn.ghost { background: #f1f3f5; color: #3c434a; }
            .rmbz-wd-btn.ghost:hover { background: #e9ecef; color: #1d2327; }
            .rmbz-wd-btn.success { background: #10b981; color: #fff; }
            .rmbz-wd-btn.success:hover { background: #047857; color: #fff; }
            .rmbz-wd-btn.danger { background: #ef4444; color: #fff; }
            .rmbz-wd-btn.danger:hover { background: #b91c1c; color: #fff; }
            .rmbz-wd-btn.info { background: #3b82f6; color: #fff; }
            .rmbz-wd-btn.info:hover { background: #1e40af; color: #fff; }
            .rmbz-wd-btn.disabled { background: #d1d5db; color: #6b7280; cursor: not-allowed; opacity: 0.7; }
            .rmbz-wd-btn.disabled:hover { background: #d1d5db; color: #6b7280; transform: none; }

            /* Sections */
            .rmbz-wd-section { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 0; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); overflow: hidden; }
            .rmbz-wd-section-title { font-size: 14px; font-weight: 700; text-transform: uppercase; color: #1d2327; letter-spacing: 0.3px; margin: 0; padding: 16px 20px; background: #f7f7fb; border-bottom: 1px solid #e1e4e8; display: flex; align-items: center; gap: 10px; }
            .rmbz-wd-section-count { display: inline-block; padding: 2px 9px; background: #1d2327; color: #f0b90b; border-radius: 12px; font-size: 11px; font-weight: 700; }

            /* Sub-tabs */
            .rmbz-wd-subtabs { display: flex; gap: 2px; padding: 0 20px; background: #fafafa; border-bottom: 1px solid #e1e4e8; }
            .rmbz-wd-subtabs a { padding: 10px 16px; text-decoration: none; color: #5f6368; font-weight: 600; font-size: 12px; border-bottom: 3px solid transparent; margin-bottom: -1px; transition: 0.15s; }
            .rmbz-wd-subtabs a:hover { color: #1d2327; }
            .rmbz-wd-subtabs a.active { color: #1d2327; border-bottom-color: #f0b90b; }

            /* Tabela */
            .rmbz-wd-table-wrap { overflow-x: auto; }
            .rmbz-wd-table { width: 100%; border-collapse: collapse; }
            .rmbz-wd-table thead th { background: #fafafa; padding: 10px 16px; text-align: left; font-size: 11px; text-transform: uppercase; font-weight: 700; color: #5f6368; letter-spacing: 0.5px; border-bottom: 1px solid #e1e4e8; }
            .rmbz-wd-table tbody td { padding: 14px 16px; border-bottom: 1px solid #f0f0f1; font-size: 13px; color: #3c434a; vertical-align: middle; }
            .rmbz-wd-table tbody tr:last-child td { border-bottom: none; }
            .rmbz-wd-table tbody tr:hover td { background: #fbfbfc; }

            /* Badges */
            .rmbz-wd-badge { display: inline-block; padding: 3px 9px; border-radius: 12px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.3px; }
            .rmbz-wd-badge.small { padding: 2px 7px; font-size: 10px; }
            .rmbz-wd-badge.wallet    { background: #d1ecf1; color: #0c5460; }
            .rmbz-wd-badge.royalties { background: #fff3cd; color: #856404; }

            .rmbz-wd-amount { color: #1e40af; font-size: 14px; font-weight: 700; font-variant-numeric: tabular-nums; }
            .rmbz-wd-method-badge { display: inline-block; padding: 3px 9px; background: #1d2327; color: #f0b90b; border-radius: 6px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.3px; }
            .rmbz-wd-account { margin-top: 4px; font-size: 13px; font-weight: 600; color: #1d2327; font-variant-numeric: tabular-nums; }

            /* Risco pill */
            .rmbz-wd-risk { display: inline-block; padding: 3px 9px; border-radius: 12px; color: #fff; font-size: 11px; font-weight: 700; letter-spacing: 0.3px; }
            .rmbz-wd-risk.ok   { background: #10b981; }
            .rmbz-wd-risk.med  { background: #f59e0b; }
            .rmbz-wd-risk.hi   { background: #ef4444; }
            .rmbz-wd-risk.crit { background: #991b1b; box-shadow: 0 0 0 2px rgba(153, 27, 27, 0.2); }

            .rmbz-wd-checklist { margin-top: 4px; font-size: 11px; font-weight: 600; }
            .rmbz-wd-checklist.done    { color: #047857; }
            .rmbz-wd-checklist.pending { color: #5f6368; }

            /* Status pills histórico */
            .rmbz-wd-status { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; }
            .rmbz-wd-status.status-approved  { background: #d1fae5; color: #065f46; }
            .rmbz-wd-status.status-rejected  { background: #fee2e2; color: #991b1b; }
            .rmbz-wd-status.status-other     { background: #f1f3f5; color: #5f6368; }

            .rmbz-wd-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; }

            /* Empty state */
            .rmbz-wd-empty { padding: 50px 20px; text-align: center; color: #5f6368; }
            .rmbz-wd-empty .icon { font-size: 42px; margin-bottom: 10px; opacity: 0.4; }
            .rmbz-wd-empty .msg  { font-size: 14px; }

            /* Paginação */
            .rmbz-wd-pagination { display: flex; justify-content: space-between; align-items: center; padding: 14px 20px; border-top: 1px solid #f0f0f1; background: #fbfbfc; }
            .rmbz-wd-pagination .info { color: #5f6368; font-size: 12px; }
            .rmbz-wd-pagination .links { display: flex; gap: 4px; }
            .rmbz-wd-pagination .links a, .rmbz-wd-pagination .links span { padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; text-decoration: none; }
            .rmbz-wd-pagination .links a { background: #fff; color: #3c434a; border: 1px solid #e1e4e8; }
            .rmbz-wd-pagination .links a:hover { background: #1d2327; color: #f0b90b; border-color: #1d2327; }
            .rmbz-wd-pagination .links span.current { background: #1d2327; color: #f0b90b; border: 1px solid #1d2327; }
            .rmbz-wd-pagination .links span.dots { background: transparent; color: #aaa; border: none; }

            /* ========== LAYOUT LEGACY (mantido para modal) ========== */
            /* Hero — fundo escuro 1MZ + bloom dourado subtil */
            .rmbz-withdrawals-hero {
                background: linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 60%, #1f1f1f 100%);
                color: #fff;
                padding: 22px 26px;
                border-radius: 14px;
                margin-bottom: 22px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.12);
                position: relative;
                overflow: hidden;
            }
            .rmbz-withdrawals-hero::before {
                content: '';
                position: absolute;
                top: -40%; right: -10%;
                width: 50%; height: 180%;
                background: radial-gradient(circle, rgba(240,185,11,0.18) 0%, transparent 60%);
                pointer-events: none;
            }
            .rmbz-withdrawals-hero > div { position: relative; z-index: 1; }
            .rmbz-withdrawals-hero h1 {
                color: #fff !important;
                font-size: 26px;
                margin: 0 0 4px 0;
            }
            .rmbz-withdrawals-hero p {
                color: rgba(255,255,255,0.72) !important;
                margin: 0;
                font-size: 14px;
            }
            .rmbz-withdrawals-hero p strong { color: #f0b90b; }

            /* Pills de sumário no topo direito (Pendentes / Aprovados / Rejeitados) */
            .rmbz-withdrawals-summary {
                display: flex; gap: 12px;
            }
            .rmbz-withdrawals-summary .rmbz-stat-pill {
                background: rgba(255,255,255,0.08);
                border: 1px solid rgba(240,185,11,0.25);
                border-radius: 10px;
                padding: 10px 18px;
                display: flex; flex-direction: column; align-items: center;
                min-width: 90px;
            }
            .rmbz-withdrawals-summary .stat-pending { border-color: rgba(240,185,11,0.45); }
            .rmbz-withdrawals-summary .stat-approved { border-color: rgba(46,204,113,0.45); }
            .rmbz-withdrawals-summary .stat-rejected { border-color: rgba(192,57,43,0.45); }
            .rmbz-withdrawals-summary .rmbz-stat-label {
                font-size: 10px; letter-spacing: 0.1em;
                text-transform: uppercase;
                color: rgba(255,255,255,0.6);
            }
            .rmbz-withdrawals-summary .rmbz-stat-value {
                font-size: 22px; font-weight: 800;
                line-height: 1.1; margin-top: 2px;
                color: #f0b90b;
            }
            .rmbz-withdrawals-summary .stat-approved .rmbz-stat-value { color: #2ecc71; }
            .rmbz-withdrawals-summary .stat-rejected .rmbz-stat-value { color: #e74c3c; }

            /* Card de pendentes: borda verde no topo (era inline antes) */
            .rmbz-withdrawals-modern .rmbz-withdrawals-pendentes {
                border-top: 4px solid #2ecc71;
            }

            /* Botão Ver Detalhe — classe dedicada (não depende do .btn-outline
             * que renderizava fantasma por causa de var() não definida no admin). */
            .rmbz-wd-view-btn {
                display: inline-flex;
                align-items: center; justify-content: center;
                padding: 7px 14px;
                border-radius: 8px;
                font-size: 12px;
                font-weight: 600;
                cursor: pointer;
                background: #1a1a1a;
                color: #f0b90b;
                border: 1px solid #f0b90b;
                transition: all 0.18s ease;
                white-space: nowrap;
            }
            .rmbz-wd-view-btn:hover {
                background: #f0b90b;
                color: #1a1a1a;
                transform: translateY(-1px);
                box-shadow: 0 3px 8px rgba(240,185,11,0.35);
            }

            /* ========== MODAL ========== */
            .rmbz-wd-modal {
                position: fixed; inset: 0; z-index: 100000;
                display: none; align-items: center; justify-content: center;
                padding: 20px;
            }
            .rmbz-wd-modal.is-open { display: flex; }
            .rmbz-wd-modal-backdrop {
                position: absolute; inset: 0;
                background: rgba(10,10,10,0.65);
                backdrop-filter: blur(2px);
            }
            .rmbz-wd-modal-dialog {
                position: relative;
                background: #fff;
                border-radius: 14px;
                box-shadow: 0 20px 60px rgba(0,0,0,0.4);
                max-width: 640px;
                width: 100%;
                max-height: 92vh;
                overflow: hidden;
                display: flex; flex-direction: column;
            }
            .rmbz-wd-modal-header {
                display: flex; justify-content: space-between; align-items: center;
                padding: 16px 22px;
                border-bottom: 1px solid #eee;
                background: linear-gradient(135deg, #1a1a1a, #2a2a2a);
                color: #fff;
            }
            .rmbz-wd-modal-header h3 { margin: 0; font-size: 18px; color: #fff; }
            .rmbz-wd-modal-close {
                background: transparent; border: 0; color: #fff;
                font-size: 28px; cursor: pointer; line-height: 1;
                padding: 0 8px; opacity: 0.8;
            }
            .rmbz-wd-modal-close:hover { opacity: 1; }
            .rmbz-wd-modal-body { padding: 20px 22px; overflow-y: auto; }
            .rmbz-wd-modal-info {
                margin: 0;
                display: grid;
                grid-template-columns: 160px 1fr;
                gap: 6px 12px;
            }
            .rmbz-wd-modal-info dt {
                font-size: 12px; color: #666; font-weight: 600;
                text-transform: uppercase; letter-spacing: 0.04em;
            }
            .rmbz-wd-modal-info dd {
                margin: 0; font-size: 14px; color: #222;
                word-break: break-word;
            }
            .rmbz-wd-modal-info dd.amount {
                font-size: 18px; font-weight: 700; color: #2563eb;
            }
            .rmbz-wd-modal-info dd.status-aprovado {
                font-weight: 700; color: #10b981;
            }
            .rmbz-wd-modal-info dd.status-rejeitado {
                font-weight: 700; color: #6b7280;
            }
            .rmbz-wd-notes-block {
                margin-top: 20px;
                padding-top: 16px;
                border-top: 1px dashed #ddd;
            }
            .rmbz-wd-notes-block strong {
                display: block; margin-bottom: 6px;
                font-size: 12px; color: #666;
                text-transform: uppercase; letter-spacing: 0.04em;
            }
            .rmbz-wd-notes {
                margin: 0; padding: 10px 12px;
                background: #f7f7f7; border-radius: 8px;
                font-size: 13px; color: #333;
                white-space: pre-wrap;
            }
            .rmbz-wd-invoice-wrap {
                margin-top: 18px;
                padding-top: 16px;
                border-top: 1px dashed #ddd;
            }
            .rmbz-wd-invoice-btn {
                display: inline-flex;
                align-items: center; justify-content: center;
                padding: 11px 22px;
                background: #1a1a1a;
                color: #f0b90b;
                border: 1px solid #f0b90b;
                border-radius: 10px;
                font-size: 14px;
                font-weight: 600;
                text-decoration: none;
                transition: all 0.18s ease;
            }
            .rmbz-wd-invoice-btn:hover {
                background: #f0b90b;
                color: #1a1a1a;
                box-shadow: 0 3px 10px rgba(240,185,11,0.35);
            }
            @media (max-width: 720px) {
                .rmbz-withdrawals-hero {
                    flex-direction: column; gap: 14px; align-items: flex-start;
                }
                .rmbz-withdrawals-summary { width: 100%; }
                .rmbz-withdrawals-summary .rmbz-stat-pill { flex: 1; }
                .rmbz-wd-modal-info { grid-template-columns: 1fr; gap: 2px 0; }
                .rmbz-wd-modal-info dt { margin-top: 8px; }
            }
        </style>

        <script>
            (function () {
                var modal = document.getElementById('rmbz-wd-modal');
                if (!modal) return;

                function formatDate(s) {
                    if (!s || s === '0000-00-00 00:00:00') return '—';
                    return s;
                }
                function formatAmount(n) {
                    if (typeof n !== 'number') n = parseFloat(n) || 0;
                    return n.toLocaleString('pt-PT', {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2,
                    }) + ' MT';
                }
                function setText(id, val) {
                    var el = document.getElementById(id);
                    if (el) el.textContent = (val == null || val === '') ? '—' : String(val);
                }

                function openWith(data) {
                    setText('wd-id', '#' + data.id);
                    setText('wd-artist', data.user_telemovel);
                    setText('wd-method', data.payment_method);
                    setText('wd-details', data.payment_details);
                    setText('wd-req-date', formatDate(data.request_date));
                    setText('wd-proc-date', formatDate(data.processed_date));
                    setText('wd-notes', data.admin_notes && data.admin_notes.trim() !== ''
                        ? data.admin_notes
                        : 'Sem notas registadas.');

                    // Fonte: emoji + label
                    setText('wd-source', data.source === 'royalties' ? '🎵 Royalties' : '💼 Carteira');

                    // Taxa de câmbio — só se for royalties E houver valor
                    var rate = data.exchange_rate;
                    if (data.source === 'royalties' && rate && rate > 0) {
                        setText('wd-rate', '1 USD = ' + rate.toFixed(4) + ' MT');
                    } else {
                        setText('wd-rate', 'Não aplicável');
                    }

                    // Status colorido
                    var statusEl = document.getElementById('wd-status');
                    if (statusEl) {
                        statusEl.textContent = (data.status || '—')
                            .charAt(0).toUpperCase() + (data.status || '').slice(1);
                        statusEl.className = 'status-' + (data.status || '');
                    }

                    // Valor com cor
                    var amountEl = document.getElementById('wd-amount');
                    if (amountEl) {
                        amountEl.textContent = formatAmount(data.amount);
                        amountEl.className = 'amount';
                    }

                    // Botão fatura (só para aprovados)
                    var invWrap = document.getElementById('wd-invoice-wrap');
                    var invLink = document.getElementById('wd-invoice-link');
                    if (invWrap && invLink) {
                        if (data.invoice_url && data.invoice_url.trim() !== '') {
                            invLink.href = data.invoice_url;
                            invWrap.style.display = 'block';
                        } else {
                            invWrap.style.display = 'none';
                        }
                    }

                    modal.classList.add('is-open');
                    modal.setAttribute('aria-hidden', 'false');
                }

                function closeModal() {
                    modal.classList.remove('is-open');
                    modal.setAttribute('aria-hidden', 'true');
                }

                document.addEventListener('click', function (e) {
                    var btn = e.target.closest('.rmbz-wd-detail-btn');
                    if (btn) {
                        try {
                            var data = JSON.parse(btn.getAttribute('data-withdrawal'));
                            openWith(data);
                        } catch (err) {
                            console.error('1MZ: payload inválido no botão', err);
                        }
                        return;
                    }
                    if (e.target.closest('[data-close-wd-modal]')) {
                        closeModal();
                    }
                });
                document.addEventListener('keydown', function (e) {
                    if (e.key === 'Escape' && modal.classList.contains('is-open')) {
                        closeModal();
                    }
                });
            })();
        </script>
    </div>
    <?php
}

/**
 * ==========================================================================
 * AÇÕES DA LIXEIRA (RESTAURAR E APAGAR PERMANENTEMENTE)
 * ==========================================================================
 */
function rmbz_handle_trash_actions() {
    if ( ! current_user_can('manage_options') ) wp_die('Sem permissão.');
    if ( ! isset($_POST['_wpnonce']) || ! wp_verify_nonce($_POST['_wpnonce'], 'rmbz_trash_action_nonce') ) wp_die('Falha de segurança.');

    global $wpdb;
    $telemovel = sanitize_text_field($_POST['user_telemovel']);
    $action_type = sanitize_text_field($_POST['trash_action']);
    $table_wallets = $wpdb->prefix . 'rmbz_wallets';

    if ($action_type === 'restore') {
        $wallet = $wpdb->get_row($wpdb->prepare("SELECT extra_data FROM {$table_wallets} WHERE user_telemovel = %s", $telemovel));
        $extra = !empty($wallet->extra_data) ? json_decode($wallet->extra_data, true) : [];
        if (isset($extra['deleted_at'])) unset($extra['deleted_at']);
        
        $wpdb->update($table_wallets, ['extra_data' => wp_json_encode($extra), 'is_banned' => 0], ['user_telemovel' => $telemovel]);
        $msg = "Conta de $telemovel foi restaurada com sucesso!";
        
    } elseif ($action_type === 'permanent_delete') {
        
        // 1. DESTRUIR FICHEIROS FÍSICOS (Evita que o servidor fique cheio de lixo)
        
        // 1.1 Apagar Músicas e Capas das Submissões
        $submissions = $wpdb->get_results($wpdb->prepare("SELECT music_file_url, extra_data FROM {$wpdb->prefix}rmbz_artist_submissions WHERE artist_telemovel = %s", $telemovel));
        foreach ($submissions as $sub) {
            if (function_exists('rmbz_destruir_ficheiro_fisico')) {
                rmbz_destruir_ficheiro_fisico($sub->music_file_url);
                $extra = !empty($sub->extra_data) ? json_decode($sub->extra_data, true) : [];
                if (!empty($extra['cover_image'])) rmbz_destruir_ficheiro_fisico($extra['cover_image']);
                if (!empty($extra['thumbnail_url'])) rmbz_destruir_ficheiro_fisico($extra['thumbnail_url']);
                if (!empty($extra['album_tracks']) && is_array($extra['album_tracks'])) {
                    foreach ($extra['album_tracks'] as $track) {
                        if (!empty($track['url'])) rmbz_destruir_ficheiro_fisico($track['url']);
                    }
                }
            }
        }

        // 1.2 Apagar Áudios dos Projetos de Videoclipe
        $projetos = $wpdb->get_results($wpdb->prepare("SELECT demo_mp3_url FROM {$wpdb->prefix}rmbz_artist_projects WHERE artist_telemovel = %s", $telemovel));
        foreach ($projetos as $proj) {
            if (function_exists('rmbz_destruir_ficheiro_fisico')) {
                rmbz_destruir_ficheiro_fisico($proj->demo_mp3_url);
            }
        }

        // [1.6.364] 1.3 Apagar IMAGENS órfãs (ficheiro + anexo WP): comprovativos
        // de depósito, anexos do chat e imagens dentro dos projetos. Antes ficavam
        // no servidor e na biblioteca de média mesmo após apagar a conta.
        if ( function_exists('rmbz_delete_media_by_url') ) {
            // Comprovativos de depósito
            $proofs = $wpdb->get_col($wpdb->prepare("SELECT proof_image FROM {$wpdb->prefix}rmbz_deposit_requests WHERE user_telemovel = %s AND proof_image <> ''", $telemovel));
            if ($proofs) rmbz_delete_media_urls($proofs);

            // Anexos do chat dos projetos do artista
            $t_chat = $wpdb->prefix . 'rmbz_project_chat_messages';
            if ($wpdb->get_var("SHOW TABLES LIKE '$t_chat'") === $t_chat) {
                $atts = $wpdb->get_col($wpdb->prepare(
                    "SELECT c.attachment_url FROM $t_chat c
                       JOIN {$wpdb->prefix}rmbz_artist_projects p ON p.id = c.project_id
                      WHERE p.artist_telemovel = %s AND c.attachment_url IS NOT NULL AND c.attachment_url <> ''",
                    $telemovel
                ));
                if ($atts) rmbz_delete_media_urls($atts);
            }

            // Imagens dentro de scenario_details / extra_data dos projetos (KYC, referências, conceito…)
            $projs = $wpdb->get_results($wpdb->prepare("SELECT scenario_details, extra_data FROM {$wpdb->prefix}rmbz_artist_projects WHERE artist_telemovel = %s", $telemovel));
            $proj_urls = [];
            foreach ($projs as $pr) {
                $proj_urls = array_merge(
                    $proj_urls,
                    rmbz_collect_uploads_urls_from_json($pr->scenario_details),
                    rmbz_collect_uploads_urls_from_json($pr->extra_data)
                );
            }
            if ($proj_urls) rmbz_delete_media_urls($proj_urls);
        }

        // 2. ELIMINAR TODOS OS REGISTOS NAS TABELAS (Cascata)
        $wpdb->delete($wpdb->prefix . 'rmbz_wallet_transactions', ['user_telemovel' => $telemovel], ['%s']);
        $wpdb->delete($wpdb->prefix . 'rmbz_deposit_requests', ['user_telemovel' => $telemovel], ['%s']);
        $wpdb->delete($wpdb->prefix . 'rmbz_withdrawal_requests', ['user_telemovel' => $telemovel], ['%s']);
        $wpdb->delete($wpdb->prefix . 'rmbz_subscriptions', ['user_telemovel' => $telemovel], ['%s']);
        $wpdb->delete($wpdb->prefix . 'rmbz_artist_submissions', ['artist_telemovel' => $telemovel], ['%s']);
        $wpdb->delete($wpdb->prefix . 'rmbz_artist_projects', ['artist_telemovel' => $telemovel], ['%s']);
        
        // Módulo de Distribuição (Ignora erros caso as tabelas de distro ainda não existam)
        $wpdb->suppress_errors = true; 
        $wpdb->delete($wpdb->prefix . 'rmbz_distro_releases', ['artist_telemovel' => $telemovel], ['%s']);
        $wpdb->delete($wpdb->prefix . 'rmbz_distro_stats', ['artist_telemovel' => $telemovel], ['%s']);
        $wpdb->suppress_errors = false;

        // 3. APAGAR A CONTA PRINCIPAL DA CARTEIRA
        $wpdb->delete($table_wallets, ['user_telemovel' => $telemovel], ['%s']);

        $msg = "Conta do artista, transações, projetos e ficheiros foram permanentemente eliminados do sistema!";
    }
    
    wp_redirect( admin_url("admin.php?page=rmbz-utilizadores&status=trash&msg=" . urlencode($msg)) );
    exit;
}
add_action('admin_post_rmbz_handle_trash_actions', 'rmbz_handle_trash_actions');

/**
 * ==========================================================================
 * 6. LISTAGEM PRINCIPAL DE ARTISTAS E LIXEIRA (CLEAN DESIGN)
 * ==========================================================================
 */
function rmbz_mostrar_pagina_utilizadores() {
    if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Não tem permissão.' );

    global $wpdb;
    $table_wallets = $wpdb->prefix . 'rmbz_wallets';
    $table_subs = $wpdb->prefix . 'rmbz_subscriptions';

    // AUTO-LIMPEZA PASSIVA (Elimina quem está na lixeira há mais de 30 dias com HARD DELETE)
    $trash_users = $wpdb->get_results("SELECT user_telemovel, extra_data FROM {$table_wallets} WHERE extra_data LIKE '%\"deleted_at\"%'");
    foreach($trash_users as $tu) {
        $ext = json_decode($tu->extra_data, true);
        if(isset($ext['deleted_at'])) {
            $dias_na_lixeira = floor((time() - strtotime($ext['deleted_at'])) / 86400);
            if ($dias_na_lixeira >= 30) {
                
                $telemovel_limpeza = $tu->user_telemovel;
                
                // 1. DESTRUIR FICHEIROS FÍSICOS DO SERVIDOR AUTOMATICAMENTE
                $submissions = $wpdb->get_results($wpdb->prepare("SELECT music_file_url, extra_data FROM {$wpdb->prefix}rmbz_artist_submissions WHERE artist_telemovel = %s", $telemovel_limpeza));
                foreach ($submissions as $sub) {
                    if (function_exists('rmbz_destruir_ficheiro_fisico')) {
                        rmbz_destruir_ficheiro_fisico($sub->music_file_url);
                        $extra_sub = !empty($sub->extra_data) ? json_decode($sub->extra_data, true) : [];
                        if (!empty($extra_sub['cover_image'])) rmbz_destruir_ficheiro_fisico($extra_sub['cover_image']);
                        if (!empty($extra_sub['thumbnail_url'])) rmbz_destruir_ficheiro_fisico($extra_sub['thumbnail_url']);
                        if (!empty($extra_sub['album_tracks']) && is_array($extra_sub['album_tracks'])) {
                            foreach ($extra_sub['album_tracks'] as $track) {
                                if (!empty($track['url'])) rmbz_destruir_ficheiro_fisico($track['url']);
                            }
                        }
                    }
                }

                $projetos = $wpdb->get_results($wpdb->prepare("SELECT demo_mp3_url FROM {$wpdb->prefix}rmbz_artist_projects WHERE artist_telemovel = %s", $telemovel_limpeza));
                foreach ($projetos as $proj) {
                    if (function_exists('rmbz_destruir_ficheiro_fisico')) {
                        rmbz_destruir_ficheiro_fisico($proj->demo_mp3_url);
                    }
                }

                // 2. ELIMINAR TABELAS EM CASCATA AUTOMATICAMENTE
                $wpdb->delete($wpdb->prefix . 'rmbz_wallet_transactions', ['user_telemovel' => $telemovel_limpeza], ['%s']);
                $wpdb->delete($wpdb->prefix . 'rmbz_deposit_requests', ['user_telemovel' => $telemovel_limpeza], ['%s']);
                $wpdb->delete($wpdb->prefix . 'rmbz_withdrawal_requests', ['user_telemovel' => $telemovel_limpeza], ['%s']);
                $wpdb->delete($wpdb->prefix . 'rmbz_subscriptions', ['user_telemovel' => $telemovel_limpeza], ['%s']);
                $wpdb->delete($wpdb->prefix . 'rmbz_artist_submissions', ['artist_telemovel' => $telemovel_limpeza], ['%s']);
                $wpdb->delete($wpdb->prefix . 'rmbz_artist_projects', ['artist_telemovel' => $telemovel_limpeza], ['%s']);
                
                // Módulo de Distribuição
                $wpdb->suppress_errors = true; 
                $wpdb->delete($wpdb->prefix . 'rmbz_distro_releases', ['artist_telemovel' => $telemovel_limpeza], ['%s']);
                $wpdb->delete($wpdb->prefix . 'rmbz_distro_stats', ['artist_telemovel' => $telemovel_limpeza], ['%s']);
                $wpdb->suppress_errors = false;

                // 3. APAGAR A CONTA FINALMENTE
                $wpdb->delete($table_wallets, ['user_telemovel' => $telemovel_limpeza], ['%s']);
            }
        }
    }

    // Configuração de Abas (Ativos vs Lixeira)
    $is_trash = isset($_GET['status']) && $_GET['status'] === 'trash';
    $search_query = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';

    // [1.6.118.13] Filtros adicionais + paginação
    $filter_vip      = isset($_GET['vip'])     ? sanitize_text_field($_GET['vip'])     : '';   // 'yes'|'no'|''
    $filter_status   = isset($_GET['st'])      ? sanitize_text_field($_GET['st'])      : '';   // 'active'|'banned'|'expired'|''
    $filter_origin   = isset($_GET['origin'])  ? sanitize_text_field($_GET['origin'])  : '';   // 'app'|'site'|''
    $current_page    = max( 1, isset($_GET['p']) ? absint($_GET['p']) : 1 );
    $per_page        = 25;
    $offset          = ( $current_page - 1 ) * $per_page;

    $where = "WHERE 1=1";
    $where_params = array();

    if ( ! empty($search_query) ) {
        $where .= " AND (w.user_nome LIKE %s OR w.user_telemovel LIKE %s OR w.user_email LIKE %s)";
        $like = '%' . $wpdb->esc_like($search_query) . '%';
        $where_params[] = $like;
        $where_params[] = $like;
        $where_params[] = $like;
    }

    if ($is_trash) {
        $where .= " AND w.extra_data LIKE '%\"deleted_at\"%'";
    } else {
        $where .= " AND (w.extra_data NOT LIKE '%\"deleted_at\"%' OR w.extra_data IS NULL)";
    }

    // Filtros activos (só fora da lixeira)
    if ( ! $is_trash ) {
        if ( $filter_status === 'banned' )  $where .= " AND w.is_banned = 1";
        if ( $filter_status === 'active' )  $where .= " AND w.is_banned = 0";
        if ( $filter_status === 'expired' ) $where .= " AND w.extra_data LIKE '%\"account_status\":\"expired\"%'";
        if ( $filter_vip === 'yes' )        $where .= " AND s.status = 'active' AND s.end_date > NOW()";
        if ( $filter_vip === 'no' )         $where .= " AND (s.status IS NULL OR s.status != 'active' OR s.end_date <= NOW())";
        // Origem app/site: detectada via deposit_requests (primeiro depósito = origem da conta)
        if ( $filter_origin === 'app' || $filter_origin === 'site' ) {
            $t_deps = $wpdb->prefix . 'rmbz_deposit_requests';
            $where .= $wpdb->prepare(
                " AND EXISTS ( SELECT 1 FROM $t_deps d
                               WHERE d.user_telemovel = w.user_telemovel
                                 AND d.is_first_deposit = 1
                                 AND d.source_platform = %s )",
                $filter_origin
            );
        }
    }

    // ─── Contar total para paginação ───────────────────────────────
    $count_sql = "SELECT COUNT(DISTINCT w.user_telemovel)
                  FROM {$table_wallets} w
                  LEFT JOIN {$table_subs} s ON w.user_telemovel = s.user_telemovel AND s.status = 'active' AND s.end_date > NOW()
                  $where";
    $total_rows = empty($where_params)
        ? (int) $wpdb->get_var( $count_sql )
        : (int) $wpdb->get_var( $wpdb->prepare( $count_sql, $where_params ) );
    $total_pages = max( 1, (int) ceil( $total_rows / $per_page ) );

    // ─── Estatísticas globais (sempre para a lista completa, não filtrada) ─
    $stats = $wpdb->get_row(
        "SELECT
            COUNT(*) AS total,
            SUM( CASE WHEN extra_data LIKE '%\"deleted_at\"%' THEN 1 ELSE 0 END ) AS trash,
            SUM( CASE WHEN is_banned = 1 AND extra_data NOT LIKE '%\"deleted_at\"%' THEN 1 ELSE 0 END ) AS banned,
            SUM( CASE WHEN extra_data LIKE '%\"account_status\":\"expired\"%' AND extra_data NOT LIKE '%\"deleted_at\"%' THEN 1 ELSE 0 END ) AS expired,
            SUM( balance ) AS total_balance
         FROM {$table_wallets}"
    );
    $stat_vip = (int) $wpdb->get_var(
        "SELECT COUNT(DISTINCT s.user_telemovel)
         FROM {$table_subs} s
         INNER JOIN {$table_wallets} w ON w.user_telemovel = s.user_telemovel
         WHERE s.status = 'active' AND s.end_date > NOW()
           AND (w.extra_data NOT LIKE '%\"deleted_at\"%' OR w.extra_data IS NULL)"
    );

    // ─── Query principal com paginação ─────────────────────────────
    $query_sql = "SELECT w.*, s.status as sub_status, s.end_date, s.id as sub_id
                  FROM {$table_wallets} w
                  LEFT JOIN {$table_subs} s ON w.user_telemovel = s.user_telemovel AND s.status = 'active' AND s.end_date > NOW()
                  $where
                  ORDER BY w.last_updated DESC
                  LIMIT %d OFFSET %d";
    $all_params = array_merge( $where_params, array( $per_page, $offset ) );
    $utilizadores = $wpdb->get_results( $wpdb->prepare( $query_sql, $all_params ) );

    // ─── Helper para preservar query string ao mudar página/filtro ─
    $build_url = function( $overrides = array() ) use ( $is_trash, $search_query, $filter_vip, $filter_status, $filter_origin, $current_page ) {
        $args = array(
            'page' => 'rmbz-utilizadores',
        );
        if ( $is_trash )                  $args['status'] = 'trash';
        if ( $search_query !== '' )       $args['s']      = $search_query;
        if ( $filter_vip !== '' )         $args['vip']    = $filter_vip;
        if ( $filter_status !== '' )      $args['st']     = $filter_status;
        if ( $filter_origin !== '' )      $args['origin'] = $filter_origin;
        if ( $current_page > 1 )          $args['p']      = $current_page;
        foreach ( $overrides as $k => $v ) {
            if ( $v === null ) unset( $args[ $k ] );
            else               $args[ $k ] = $v;
        }
        return admin_url( 'admin.php?' . http_build_query( $args ) );
    };

    // ─── Carregar estilos modernos do plugin ───────────────────────
    rmbz_admin_modern_styles();
    ?>

    <style>
        /* [1.6.118.13] Estilos específicos da página Gestão de Artistas */
        .rmbz-users-page { max-width: none; margin: 16px 20px 32px 0; font-family: "Roboto", -apple-system, BlinkMacSystemFont, sans-serif; }
        .rmbz-users-head h1 { font-size: 26px; font-weight: 800; margin: 0 0 4px 0; color: #1d2327; }
        .rmbz-users-head p  { margin: 0; color: #5f6368; font-size: 13px; }

        /* Grelha de estatísticas */
        .rmbz-users-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 20px 0 24px; }
        .rmbz-stat-card { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
        .rmbz-stat-card .label { font-size: 11px; font-weight: 600; text-transform: uppercase; color: #5f6368; letter-spacing: 0.5px; margin-bottom: 6px; }
        .rmbz-stat-card .value { font-size: 24px; font-weight: 700; color: #1d2327; line-height: 1.1; }
        .rmbz-stat-card .value .unit { font-size: 12px; font-weight: 500; color: #5f6368; margin-left: 4px; }
        .rmbz-stat-card.gold .value { color: #d4a000; }
        .rmbz-stat-card.danger .value { color: #b91c1c; }
        .rmbz-stat-card.warn .value { color: #9a3412; }
        .rmbz-stat-card.info .value { color: #1e40af; }

        /* Barra de pesquisa + filtros */
        .rmbz-users-toolbar { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 14px 16px; margin-bottom: 16px; display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }
        .rmbz-users-toolbar form { display: flex; gap: 8px; flex: 1; min-width: 220px; }
        .rmbz-users-toolbar input[type="text"] { flex: 1; padding: 8px 12px; border: 1px solid #d8dae0; border-radius: 6px; font-size: 13px; }
        .rmbz-users-toolbar .filter-group { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
        .rmbz-users-toolbar .filter-label { font-size: 11px; color: #5f6368; text-transform: uppercase; font-weight: 600; letter-spacing: 0.5px; }
        .rmbz-users-toolbar .filter-chip { display: inline-flex; align-items: center; gap: 4px; padding: 5px 10px; border-radius: 16px; background: #f1f3f5; color: #3c434a; font-size: 12px; font-weight: 500; text-decoration: none; border: 1px solid transparent; transition: 0.15s; }
        .rmbz-users-toolbar .filter-chip:hover { background: #e9ecef; color: #1d2327; }
        .rmbz-users-toolbar .filter-chip.active { background: #1d2327; color: #f0b90b; border-color: #1d2327; }
        .rmbz-users-toolbar .filter-chip.active:hover { background: #1d2327; color: #f0b90b; }

        /* Tabela artistas */
        .rmbz-users-table-wrap { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
        .rmbz-users-table { width: 100%; border-collapse: collapse; }
        .rmbz-users-table thead th { background: #f7f7fb; padding: 12px 16px; text-align: left; font-size: 11px; text-transform: uppercase; font-weight: 700; color: #5f6368; letter-spacing: 0.5px; border-bottom: 1px solid #e1e4e8; }
        .rmbz-users-table tbody td { padding: 14px 16px; border-bottom: 1px solid #f0f0f1; font-size: 13px; color: #3c434a; vertical-align: middle; }
        .rmbz-users-table tbody tr:hover td { background: #fbfbfc; }
        .rmbz-users-table tbody tr:last-child td { border-bottom: none; }

        /* Avatar/nome cell */
        .ru-artist { display: flex; align-items: center; gap: 12px; }
        .ru-avatar { width: 38px; height: 38px; border-radius: 50%; background: linear-gradient(135deg, #1a1a1f 0%, #2c2c34 100%); color: #f0b90b; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px; flex-shrink: 0; }
        .ru-artist-info { line-height: 1.3; }
        .ru-artist-info .name { font-weight: 700; color: #1d2327; font-size: 14px; }
        .ru-artist-info .tel  { color: #5f6368; font-size: 12px; font-variant-numeric: tabular-nums; }

        /* Estado dots */
        .ru-online { display: inline-block; margin-left: 6px; padding: 2px 8px; border-radius: 10px; font-size: 10px; font-weight: 700; vertical-align: middle; }
        .ru-online.is-online  { background: #d1fae5; color: #065f46; }
        .ru-online.is-offline { background: #f1f3f5; color: #5f6368; }

        /* Badges */
        .ru-badge { display: inline-block; padding: 3px 9px; border-radius: 12px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.3px; }
        .ru-badge.active   { background: #d1fae5; color: #065f46; }
        .ru-badge.banned   { background: #fee2e2; color: #991b1b; }
        .ru-badge.expired  { background: #fef3c7; color: #92400e; }
        .ru-badge.vip      { background: linear-gradient(135deg, #fff3cd 0%, #ffe5a0 100%); color: #856404; border: 1px solid #f0b90b; }
        .ru-badge.no-vip   { background: #f1f3f5; color: #5f6368; }
        .ru-badge.origin-app  { background: #e0f2fe; color: #075985; }
        .ru-badge.origin-site { background: #f1f3f5; color: #3c434a; }
        .ru-badge.dim         { background: transparent; color: #5f6368; padding: 0; font-size: 12px; text-transform: none; letter-spacing: 0; font-weight: 500; }

        /* Localização */
        .ru-loc .provincia { display: block; font-weight: 600; color: #1d2327; }
        .ru-loc .cidade    { display: block; color: #5f6368; font-size: 12px; }
        .ru-loc.empty      { color: #aaa; font-style: italic; font-size: 12px; }

        /* Saldo */
        .ru-balance { font-weight: 700; font-size: 14px; font-variant-numeric: tabular-nums; }
        .ru-balance .unit { font-size: 11px; color: #5f6368; font-weight: 500; }

        /* Botão acção */
        .ru-action { display: inline-flex; align-items: center; gap: 4px; padding: 7px 14px; background: #1d2327; color: #f0b90b; border-radius: 8px; text-decoration: none; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; transition: 0.15s; border: none; cursor: pointer; }
        .ru-action:hover { background: #2c2c34; color: #f0b90b; transform: translateY(-1px); }
        .ru-action.danger { background: #ef4444; color: #fff; }
        .ru-action.danger:hover { background: #b91c1c; color: #fff; }
        .ru-action.success { background: #10b981; color: #fff; }
        .ru-action.success:hover { background: #047857; color: #fff; }

        /* Empty state */
        .ru-empty { padding: 60px 20px; text-align: center; color: #5f6368; }
        .ru-empty .icon { font-size: 48px; margin-bottom: 12px; opacity: 0.4; }
        .ru-empty .msg  { font-size: 14px; }

        /* Paginação */
        .ru-pagination { display: flex; justify-content: space-between; align-items: center; padding: 16px; border-top: 1px solid #f0f0f1; background: #fbfbfc; }
        .ru-pagination .info { color: #5f6368; font-size: 12px; }
        .ru-pagination .links { display: flex; gap: 4px; }
        .ru-pagination .links a, .ru-pagination .links span { padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 600; text-decoration: none; }
        .ru-pagination .links a { background: #fff; color: #3c434a; border: 1px solid #e1e4e8; }
        .ru-pagination .links a:hover { background: #1d2327; color: #f0b90b; border-color: #1d2327; }
        .ru-pagination .links span.current { background: #1d2327; color: #f0b90b; border: 1px solid #1d2327; }
        .ru-pagination .links span.dots { background: transparent; color: #aaa; border: none; }

        /* Aviso */
        .ru-notice { padding: 12px 16px; background: #d1fae5; border-left: 4px solid #10b981; color: #065f46; border-radius: 6px; margin-bottom: 16px; font-size: 13px; font-weight: 600; }
        .ru-notice.is-trash { background: #fee2e2; border-left-color: #ef4444; color: #991b1b; }

        /* Lixeira specific */
        .ru-trash-days { color: #ef4444; font-weight: 700; font-size: 13px; }
        .ru-trash-days.urgent { background: #fee2e2; padding: 3px 9px; border-radius: 12px; }
        .ru-trash-actions { display: flex; gap: 6px; }
        .ru-trash-actions form { display: inline-block; }

        /* Tabs */
        .ru-tabs { display: flex; gap: 4px; margin-bottom: 20px; border-bottom: 2px solid #e1e4e8; }
        .ru-tabs a { padding: 10px 20px; text-decoration: none; color: #5f6368; font-weight: 600; font-size: 13px; border-bottom: 3px solid transparent; margin-bottom: -2px; transition: 0.15s; }
        .ru-tabs a:hover { color: #1d2327; }
        .ru-tabs a.active { color: #1d2327; border-bottom-color: #f0b90b; }
        .ru-tabs a .count { display: inline-block; margin-left: 6px; padding: 1px 8px; background: #f1f3f5; color: #5f6368; border-radius: 10px; font-size: 11px; font-weight: 700; }
        .ru-tabs a.active .count { background: #1d2327; color: #f0b90b; }
    </style>

    <div class="rmbz-users-page">
        <div class="rmbz-users-head">
            <h1>Gestão de Artistas (Carteiras)</h1>
            <p>Lista completa de artistas registados na plataforma, com saldos, subscrições e estado da conta.</p>
        </div>

        <?php if (isset($_GET['msg'])): ?>
            <div class="ru-notice"><?php echo esc_html($_GET['msg']); ?></div>
        <?php endif; ?>

        <!-- Estatísticas globais (não filtradas) -->
        <div class="rmbz-users-stats">
            <div class="rmbz-stat-card">
                <div class="label">Total artistas</div>
                <div class="value"><?php echo number_format( (int) $stats->total, 0, ',', '.' ); ?></div>
            </div>
            <div class="rmbz-stat-card gold">
                <div class="label">VIP activos</div>
                <div class="value"><?php echo number_format( $stat_vip, 0, ',', '.' ); ?></div>
            </div>
            <div class="rmbz-stat-card info">
                <div class="label">Saldo total em wallets</div>
                <div class="value"><?php echo number_format( (float) $stats->total_balance, 2, ',', '.' ); ?><span class="unit">MT</span></div>
            </div>
            <div class="rmbz-stat-card warn">
                <div class="label">Contas expiradas</div>
                <div class="value"><?php echo number_format( (int) $stats->expired, 0, ',', '.' ); ?></div>
            </div>
            <div class="rmbz-stat-card danger">
                <div class="label">Banidos</div>
                <div class="value"><?php echo number_format( (int) $stats->banned, 0, ',', '.' ); ?></div>
            </div>
            <div class="rmbz-stat-card">
                <div class="label">Na lixeira</div>
                <div class="value"><?php echo number_format( (int) $stats->trash, 0, ',', '.' ); ?></div>
            </div>
        </div>

        <!-- Tabs Activos/Lixeira -->
        <div class="ru-tabs">
            <a href="<?php echo esc_url( $build_url( array( 'status' => null, 'p' => null ) ) ); ?>" class="<?php echo !$is_trash ? 'active' : ''; ?>">
                Artistas Ativos
                <span class="count"><?php echo (int) $stats->total - (int) $stats->trash; ?></span>
            </a>
            <a href="<?php echo esc_url( $build_url( array( 'status' => 'trash', 'p' => null ) ) ); ?>" class="<?php echo $is_trash ? 'active' : ''; ?>">
                Lixeira
                <span class="count"><?php echo (int) $stats->trash; ?></span>
            </a>
        </div>

        <!-- Toolbar: pesquisa + filtros -->
        <div class="rmbz-users-toolbar">
            <form method="get">
                <input type="hidden" name="page" value="rmbz-utilizadores">
                <?php if ( $is_trash ): ?><input type="hidden" name="status" value="trash"><?php endif; ?>
                <input type="text" name="s" value="<?php echo esc_attr( $search_query ); ?>" placeholder="🔍 Pesquisar por nome, telemóvel ou email…">
                <button type="submit" class="ru-action">Pesquisar</button>
                <?php if ( $search_query !== '' ): ?>
                    <a href="<?php echo esc_url( $build_url( array( 's' => null, 'p' => null ) ) ); ?>" class="ru-action" style="background:#f1f3f5; color:#5f6368;">Limpar</a>
                <?php endif; ?>
            </form>

            <?php if ( ! $is_trash ): ?>
                <div class="filter-group">
                    <span class="filter-label">Estado:</span>
                    <a href="<?php echo esc_url( $build_url( array( 'st' => null, 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_status === '' ? 'active' : ''; ?>">Todos</a>
                    <a href="<?php echo esc_url( $build_url( array( 'st' => 'active', 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_status === 'active' ? 'active' : ''; ?>">✓ Ativos</a>
                    <a href="<?php echo esc_url( $build_url( array( 'st' => 'banned', 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_status === 'banned' ? 'active' : ''; ?>">⛔ Banidos</a>
                    <a href="<?php echo esc_url( $build_url( array( 'st' => 'expired', 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_status === 'expired' ? 'active' : ''; ?>">⚠ Expirados</a>
                </div>

                <div class="filter-group">
                    <span class="filter-label">VIP:</span>
                    <a href="<?php echo esc_url( $build_url( array( 'vip' => null, 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_vip === '' ? 'active' : ''; ?>">Todos</a>
                    <a href="<?php echo esc_url( $build_url( array( 'vip' => 'yes', 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_vip === 'yes' ? 'active' : ''; ?>">💎 Com VIP</a>
                    <a href="<?php echo esc_url( $build_url( array( 'vip' => 'no', 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_vip === 'no' ? 'active' : ''; ?>">○ Sem VIP</a>
                </div>

                <div class="filter-group">
                    <span class="filter-label">Origem:</span>
                    <a href="<?php echo esc_url( $build_url( array( 'origin' => null, 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_origin === '' ? 'active' : ''; ?>">Todas</a>
                    <a href="<?php echo esc_url( $build_url( array( 'origin' => 'app', 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_origin === 'app' ? 'active' : ''; ?>">📱 App</a>
                    <a href="<?php echo esc_url( $build_url( array( 'origin' => 'site', 'p' => null ) ) ); ?>" class="filter-chip <?php echo $filter_origin === 'site' ? 'active' : ''; ?>">🌐 Site</a>
                </div>
            <?php endif; ?>
        </div>

        <!-- Tabela -->
        <div class="rmbz-users-table-wrap">
            <?php if ( empty($utilizadores) ) : ?>
                <div class="ru-empty">
                    <div class="icon">👤</div>
                    <div class="msg">
                        <?php if ( $search_query !== '' || $filter_vip !== '' || $filter_status !== '' || $filter_origin !== '' ): ?>
                            Nenhum artista encontrado com estes filtros.
                            <br><br>
                            <a href="<?php echo esc_url( admin_url( 'admin.php?page=rmbz-utilizadores' . ( $is_trash ? '&status=trash' : '' ) ) ); ?>" class="ru-action">Limpar filtros</a>
                        <?php else: ?>
                            Nenhum artista <?php echo $is_trash ? 'na lixeira' : 'registado ainda'; ?>.
                        <?php endif; ?>
                    </div>
                </div>
            <?php else : ?>
                <table class="rmbz-users-table">
                    <thead>
                        <tr>
                            <th>Artista</th>
                            <th>Localização</th>
                            <th>Saldo</th>
                            <?php if ( $is_trash ): ?>
                                <th>Dias na Lixeira</th>
                            <?php else: ?>
                                <th>Estado</th>
                                <th>Subscrição</th>
                            <?php endif; ?>
                            <th style="text-align:right;">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $utilizadores as $user ) :
                            $extra = !empty($user->extra_data) ? json_decode($user->extra_data, true) : array();
                            if ( ! is_array($extra) ) $extra = array();

                            // Online/Offline (5 min)
                            $last_seen   = isset($extra['last_seen']) ? intval($extra['last_seen']) : 0;
                            $is_online   = ( $last_seen > 0 && ( time() - $last_seen ) < 300 );

                            // Provincia/cidade — usar coluna directa primeiro, fallback extra_data
                            $provincia   = ! empty( $user->user_provincia )
                                ? $user->user_provincia
                                : ( $extra['provincia'] ?? '' );
                            $cidade      = $extra['cidade'] ?? '';

                            // Account status (expired soft-delete)
                            $account_status = $extra['account_status'] ?? 'active';
                            $is_expired     = ( $account_status === 'expired' );

                            // VIP active
                            $is_vip = ( ! empty( $user->sub_status ) && $user->sub_status === 'active' && strtotime( $user->end_date ) > time() );

                            // Avatar — iniciais
                            $iniciais = '';
                            if ( ! empty( $user->user_nome ) ) {
                                $parts = preg_split( '/\s+/', trim( $user->user_nome ) );
                                $iniciais = mb_strtoupper( mb_substr( $parts[0] ?? '', 0, 1 ) );
                                if ( count( $parts ) > 1 ) {
                                    $iniciais .= mb_strtoupper( mb_substr( $parts[ count($parts) - 1 ], 0, 1 ) );
                                }
                            }
                            if ( $iniciais === '' ) $iniciais = '?';
                        ?>
                        <tr>
                            <td>
                                <div class="ru-artist">
                                    <div class="ru-avatar"><?php echo esc_html( $iniciais ); ?></div>
                                    <div class="ru-artist-info">
                                        <div class="name"><?php echo esc_html( $user->user_nome ?: '(sem nome)' ); ?></div>
                                        <div class="tel">
                                            <?php echo esc_html( $user->user_telemovel ); ?>
                                            <?php if ( ! $is_trash ): ?>
                                                <span class="ru-online <?php echo $is_online ? 'is-online' : 'is-offline'; ?>">
                                                    <?php echo $is_online ? '● Online' : '○ Offline'; ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </td>

                            <td>
                                <?php if ( $provincia !== '' || $cidade !== '' ): ?>
                                    <div class="ru-loc">
                                        <span class="provincia"><?php echo esc_html( $provincia ?: '—' ); ?></span>
                                        <?php if ( $cidade !== '' ): ?>
                                            <span class="cidade"><?php echo esc_html( $cidade ); ?></span>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="ru-loc empty">não informada</div>
                                <?php endif; ?>
                            </td>

                            <td>
                                <span class="ru-balance">
                                    <?php echo number_format( (float) $user->balance, 2, ',', '.' ); ?>
                                    <span class="unit">MT</span>
                                </span>
                            </td>

                            <?php if ( $is_trash ):
                                $deleted_at      = $extra['deleted_at'] ?? null;
                                $dias_passados   = $deleted_at ? floor( ( time() - strtotime( $deleted_at ) ) / 86400 ) : 0;
                                $dias_restantes  = max( 0, 30 - $dias_passados );
                                $urgent_class    = $dias_restantes <= 7 ? 'urgent' : '';
                            ?>
                                <td>
                                    <span class="ru-trash-days <?php echo $urgent_class; ?>">
                                        Restam <?php echo $dias_restantes; ?> dia<?php echo $dias_restantes === 1 ? '' : 's'; ?>
                                    </span>
                                </td>
                                <td style="text-align:right;">
                                    <div class="ru-trash-actions">
                                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                                            <input type="hidden" name="action" value="rmbz_handle_trash_actions">
                                            <input type="hidden" name="trash_action" value="restore">
                                            <input type="hidden" name="user_telemovel" value="<?php echo esc_attr( $user->user_telemovel ); ?>">
                                            <?php wp_nonce_field( 'rmbz_trash_action_nonce' ); ?>
                                            <button type="submit" class="ru-action success">♻️ Restaurar</button>
                                        </form>
                                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" onsubmit="return confirm('ATENÇÃO! Vai apagar a conta, o extrato e o saldo PARA SEMPRE. Continuar?');">
                                            <input type="hidden" name="action" value="rmbz_handle_trash_actions">
                                            <input type="hidden" name="trash_action" value="permanent_delete">
                                            <input type="hidden" name="user_telemovel" value="<?php echo esc_attr( $user->user_telemovel ); ?>">
                                            <?php wp_nonce_field( 'rmbz_trash_action_nonce' ); ?>
                                            <button type="submit" class="ru-action danger">🗑 Apagar</button>
                                        </form>
                                    </div>
                                </td>
                            <?php else: ?>
                                <td>
                                    <?php if ( $user->is_banned ): ?>
                                        <span class="ru-badge banned">⛔ Banido</span>
                                    <?php elseif ( $is_expired ): ?>
                                        <span class="ru-badge expired">⚠ Expirada</span>
                                    <?php else: ?>
                                        <span class="ru-badge active">✓ Activa</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ( $is_vip ): ?>
                                        <span class="ru-badge vip">💎 VIP</span>
                                        <?php
                                            $days_left = max( 0, ceil( ( strtotime( $user->end_date ) - time() ) / 86400 ) );
                                        ?>
                                        <div style="font-size:11px; color:#5f6368; margin-top:3px;">
                                            <?php echo (int) $days_left; ?> dia<?php echo $days_left === 1 ? '' : 's'; ?> restantes
                                        </div>
                                    <?php else: ?>
                                        <span class="ru-badge no-vip">Sem VIP</span>
                                    <?php endif; ?>
                                </td>
                                <td style="text-align:right;">
                                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=rmbz-historico-utilizador&user_id=' . urlencode( $user->user_telemovel ) ) ); ?>" class="ru-action">
                                        Abrir Perfil →
                                    </a>
                                </td>
                            <?php endif; ?>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <!-- Paginação -->
                <?php if ( $total_pages > 1 ): ?>
                    <div class="ru-pagination">
                        <div class="info">
                            Mostrando <?php echo $offset + 1; ?>–<?php echo min( $offset + count( $utilizadores ), $total_rows ); ?>
                            de <?php echo number_format( $total_rows, 0, ',', '.' ); ?> artistas
                        </div>
                        <div class="links">
                            <?php
                            // Anterior
                            if ( $current_page > 1 ) {
                                echo '<a href="' . esc_url( $build_url( array( 'p' => $current_page - 1 ) ) ) . '">‹ Anterior</a>';
                            }
                            // Páginas (mostrar até 5 ao redor da actual)
                            $start = max( 1, $current_page - 2 );
                            $end   = min( $total_pages, $current_page + 2 );
                            if ( $start > 1 ) {
                                echo '<a href="' . esc_url( $build_url( array( 'p' => 1 ) ) ) . '">1</a>';
                                if ( $start > 2 ) echo '<span class="dots">…</span>';
                            }
                            for ( $i = $start; $i <= $end; $i++ ) {
                                if ( $i === $current_page ) {
                                    echo '<span class="current">' . $i . '</span>';
                                } else {
                                    echo '<a href="' . esc_url( $build_url( array( 'p' => $i ) ) ) . '">' . $i . '</a>';
                                }
                            }
                            if ( $end < $total_pages ) {
                                if ( $end < $total_pages - 1 ) echo '<span class="dots">…</span>';
                                echo '<a href="' . esc_url( $build_url( array( 'p' => $total_pages ) ) ) . '">' . $total_pages . '</a>';
                            }
                            // Próxima
                            if ( $current_page < $total_pages ) {
                                echo '<a href="' . esc_url( $build_url( array( 'p' => $current_page + 1 ) ) ) . '">Seguinte ›</a>';
                            }
                            ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    <?php
}

/**
 * --------------------------------------------------------------------------
 * 7. PÁGINAS AUXILIARES DE SISTEMA
 * --------------------------------------------------------------------------
 */
function rmbz_mostrar_pagina_ajuste_saldo() {
    rmbz_admin_modern_styles();
    if ( ! isset($_GET['user_phone']) ) wp_die('Artista em falta.');
    $phone = sanitize_text_field(rawurldecode($_GET['user_phone']));
    global $wpdb;
    $w = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel=%s", $phone));
    if(!$w) wp_die('Carteira não encontrada.');
    $nonce = str_replace('+', '', (string) ($phone ?? ''));
    ?>
    <div class="rmbz-admin-wrap">
        <div class="rmbz-header">
            <div>
                <h1>Ajustar Saldo da Carteira</h1>
                <p>Adicione ou remova fundos manualmente da conta do artista.</p>
            </div>
            <a href="<?php echo admin_url('admin.php?page=rmbz-utilizadores'); ?>" class="rmbz-btn btn-outline">&larr; Voltar à lista</a>
        </div>
        
        <div class="rmbz-card" style="max-width: 600px; border-top: 4px solid #3498db;">
            <p style="font-size:16px;"><strong>Artista:</strong> <?php echo esc_html($w->user_nome); ?> (<?php echo esc_html($phone); ?>)</p>
            <p style="font-size:16px; margin-bottom:20px;"><strong>Saldo Atual:</strong> <span style="color:var(--rmbz-info-strong, #2563eb); font-weight:bold; font-size:24px;"><?php echo number_format((float)$w->balance, 2, ',', '.'); ?> MT</span></p>
            
            <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                <input type="hidden" name="action" value="rmbz_processar_ajuste_saldo">
                <input type="hidden" name="user_telemovel" value="<?php echo esc_attr($phone); ?>">
                <?php wp_nonce_field('rmbz_executar_ajuste_saldo_nonce_'.$nonce, '_rmbz_ajuste_nonce'); ?>
                
                <label style="font-weight:bold; display:block; margin-bottom:5px;">Valor a Ajustar (MT):</label>
                <input type="number" name="amount" required step="0.01" style="width:100%; padding:10px; border-radius:6px; margin-bottom:5px; border:1px solid #ccc;" placeholder="Ex: 100.00 (Positivo) ou -50.00 (Negativo)">
                
                <label style="font-weight:bold; display:block; margin-bottom:5px;">Motivo do Ajuste:</label>
                <input type="text" name="reason" required style="width:100%; padding:10px; border-radius:6px; margin-bottom:20px; border:1px solid #ccc;" placeholder="Ex: Bónus promocional, correção de erro...">

                <button type="submit" class="rmbz-btn btn-gold" style="width:100%; padding:15px; font-size:16px;" onclick="return confirm('Confirmar alteração de saldo?');">Confirmar Ajuste 💰</button>
            </form>
        </div>
    </div>
    <?php
}

function rmbz_mostrar_pagina_redefinir_pin() {
    rmbz_admin_modern_styles();
    if(!isset($_GET['user_phone'])) wp_die('User em falta.');
    $phone = sanitize_text_field(rawurldecode($_GET['user_phone']));
    $nonce = str_replace('+', '', (string) ($phone ?? ''));
    ?>
    <div class="rmbz-admin-wrap">
        <div class="rmbz-header">
            <div>
                <h1>Redefinir PIN do Artista</h1>
                <p>Altere a senha de acesso (PIN de 4 dígitos) para este utilizador.</p>
            </div>
            <a href="<?php echo admin_url('admin.php?page=rmbz-utilizadores'); ?>" class="rmbz-btn btn-outline">&larr; Voltar à lista</a>
        </div>

        <div class="rmbz-card" style="max-width: 500px; border-top: 4px solid #e74c3c;">
            <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                <input type="hidden" name="action" value="rmbz_processar_redefinir_pin">
                <input type="hidden" name="user_telemovel" value="<?php echo esc_attr($phone); ?>">
                <?php wp_nonce_field('rmbz_executar_redefinir_pin_nonce_'.$nonce, '_rmbz_pin_nonce'); ?>
                
                <label style="font-weight:bold; display:block; margin-bottom:5px;">Novo PIN (4 dígitos numéricos):</label>
                <input type="password" name="new_pin_1" maxlength="4" pattern="\d{4}" required style="width:100%; padding:10px; border-radius:6px; margin-bottom:15px; border:1px solid #ccc;">
                
                <label style="font-weight:bold; display:block; margin-bottom:5px;">Confirmar PIN:</label>
                <input type="password" name="new_pin_2" maxlength="4" pattern="\d{4}" required style="width:100%; padding:10px; border-radius:6px; margin-bottom:20px; border:1px solid #ccc;">
                
                <button type="submit" class="rmbz-btn btn-danger" style="width:100%; padding:15px; font-size:16px;">Alterar PIN de Acesso</button>
            </form>
        </div>
    </div>
    <?php
}

function rmbz_mostrar_pagina_editar_bloqueio() {
    rmbz_admin_modern_styles();
    if(!isset($_GET['trans_id'])) wp_die('ID em falta.');
    $tid = absint($_GET['trans_id']);
    global $wpdb;
    $t = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}rmbz_wallet_transactions WHERE transaction_id=%d", $tid));
    ?>
    <div class="rmbz-admin-wrap">
        <div class="rmbz-header">
            <div>
                <h1>Editar Bloqueio de Fundos</h1>
                <p>Libertar ou bloquear fundos manualmente.</p>
            </div>
            <a href="<?php echo admin_url('admin.php?page=rmbz-historico-utilizador&user_phone='.rawurlencode($t->user_telemovel)); ?>" class="rmbz-btn btn-outline">&larr; Voltar ao Histórico</a>
        </div>
        
        <div class="rmbz-card" style="max-width: 500px;">
            <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                <input type="hidden" name="action" value="rmbz_processar_edicao_bloqueio">
                <input type="hidden" name="trans_id" value="<?php echo $tid; ?>">
                <input type="hidden" name="user_phone" value="<?php echo esc_attr($t->user_telemovel ?? ''); ?>">
                <?php wp_nonce_field('rmbz_edit_lock_'.$tid, '_rmbz_edit_lock_nonce'); ?>
                
                <p>Estado atual: <strong><?php echo ($t->is_unlocked) ? '<span style="color:var(--rmbz-success, #10b981);">Desbloqueado</span>' : '<span style="color:var(--rmbz-danger, #ef4444);">Bloqueado</span>'; ?></strong></p>
                <p>Valor bloqueado: <strong><?php echo number_format((float)$t->amount, 2, ',', '.'); ?> MT</strong></p>
                
                <div style="background:#f9f9f9; padding:15px; border-radius:8px; margin:20px 0;">
                    <label style="cursor:pointer; display:block; margin-bottom:10px;"><input type="radio" name="lock_status" value="1" <?php checked($t->is_unlocked, 1); ?>> <strong>Desbloquear fundos agora</strong></label>
                    <label style="cursor:pointer; display:block;"><input type="radio" name="lock_status" value="0" <?php checked($t->is_unlocked, 0); ?>> Manter Bloqueado</label>
                </div>
                
                <label style="font-weight:bold; display:block; margin-bottom:5px;">Data planeada para Desbloqueio Automático:</label>
                <input type="datetime-local" name="unlock_date" value="<?php echo esc_attr($t->unlock_date ?? ''); ?>" style="width:100%; padding:10px; border-radius:6px; margin-bottom:20px; border:1px solid #ccc;">
                
                <button type="submit" class="rmbz-btn btn-gold" style="width:100%; padding:15px;">💾 Guardar Alterações</button>
            </form>
        </div>
    </div>
    <?php
}

/**
 * --------------------------------------------------------------------------
 * PÁGINA: GESTÃO DE CUPÕES
 * --------------------------------------------------------------------------
 */
function rmbz_mostrar_pagina_cupoes() {
    rmbz_admin_modern_styles();
    if ( function_exists('rmbz_admin_wd_styles') ) { rmbz_admin_wd_styles(); }
    global $wpdb;
    $table_coupons = $wpdb->prefix . 'rmbz_coupons';

    $cupoes = $wpdb->get_results("SELECT * FROM {$table_coupons} ORDER BY created_at DESC");

    $cup_total = count($cupoes);
    $cup_ativos = 0;
    $cup_usos = 0;
    $cup_expirados = 0;
    foreach ($cupoes as $c) {
        $exp = (!empty($c->expiry_date) && strtotime($c->expiry_date . ' UTC') < time());
        $exh = ($c->usage_limit > 0 && $c->used_count >= $c->usage_limit);
        if ($c->status === 'ativo' && !$exp && !$exh) $cup_ativos++;
        if ($exp) $cup_expirados++;
        $cup_usos += (int) $c->used_count;
    }
    ?>
    <div class="rmbz-admin-wrap rmbz-withdrawals-modern rmbz-coupons-page">
        <style>
            .rmbz-coupons-page select,
            .rmbz-coupons-page input:not([type=checkbox]):not([type=radio]),
            .rmbz-coupons-page textarea { color-scheme: light; }
            .rmbz-coupons-page select option,
            .rmbz-coupons-page optgroup { background: #fff; color: #1d2327; }
            .rmbz-coupons-page input[type=text],
            .rmbz-coupons-page input[type=number],
            .rmbz-coupons-page input[type=datetime-local],
            .rmbz-coupons-page input[type=date],
            .rmbz-coupons-page input[type=email],
            .rmbz-coupons-page input[type=url],
            .rmbz-coupons-page select,
            .rmbz-coupons-page textarea {
                background-color: #fff !important;
                color: #1d2327 !important;
                -webkit-text-fill-color: #1d2327 !important;
            }
            .rmbz-coupons-page input[type=text]:-webkit-autofill,
            .rmbz-coupons-page input[type=number]:-webkit-autofill {
                -webkit-box-shadow: 0 0 0 1000px #fff inset !important;
                -webkit-text-fill-color: #1d2327 !important;
            }
            .rmbz-coupons-page input[type=checkbox],
            .rmbz-coupons-page input[type=radio] {
                -webkit-appearance: auto;
                appearance: auto;
                accent-color: #f0b90b;
                width: 16px; height: 16px; cursor: pointer;
            }
        </style>

        <div class="rmbz-wd-head">
            <h1>🎟️ Gestão de Cupões Promocionais</h1>
            <p>Crie códigos de desconto e defina regras estritas sobre o que eles permitem fazer.</p>
        </div>

        <div class="rmbz-wd-stats-grid">
            <div class="rmbz-wd-stat-card success">
                <div class="label">Cupões Ativos</div>
                <div class="value"><?php echo (int) $cup_ativos; ?></div>
                <div class="sub">prontos a usar</div>
            </div>
            <div class="rmbz-wd-stat-card">
                <div class="label">Total Criados</div>
                <div class="value"><?php echo (int) $cup_total; ?></div>
                <div class="sub">todos os cupões</div>
            </div>
            <div class="rmbz-wd-stat-card info">
                <div class="label">Usos Totais</div>
                <div class="value"><?php echo (int) $cup_usos; ?></div>
                <div class="sub">resgates feitos</div>
            </div>
            <div class="rmbz-wd-stat-card warn">
                <div class="label">Expirados</div>
                <div class="value"><?php echo (int) $cup_expirados; ?></div>
                <div class="sub">fora de validade</div>
            </div>
        </div>

        <div style="display:flex; gap:20px; flex-wrap:wrap; align-items:flex-start;">
            
            <div class="rmbz-wd-section" style="flex:1; min-width:300px; padding:20px;">
                <h3 style="margin-top:0; font-size:15px; font-weight:800; color:#1d2327;">Criar Novo Cupão</h3>
                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                    <input type="hidden" name="action" value="rmbz_admin_add_coupon">
                    <?php wp_nonce_field('rmbz_add_coupon_nonce'); ?>

                    <div class="rmbz-field">
                        <label class="rmbz-label">Código do Cupão</label>
                        <input type="text" name="coupon_code" required class="rmbz-input" style="text-transform:uppercase;" placeholder="Ex: 1MZVIP2026">
                    </div>

                    <div class="rmbz-field">
                        <label class="rmbz-label">Tipo de Recompensa</label>
                        <select name="reward_type" id="coupon_reward_type" required class="rmbz-select" onchange="toggleCouponOptions()">
                            <option value="saldo">💰 Adicionar Saldo (Meticais)</option>
                            <option value="vip_days">💎 Oferecer Dias de Subscrição VIP</option>
                        </select>
                    </div>

                    <div class="rmbz-field">
                        <label class="rmbz-label">Valor (MT ou Dias)</label>
                        <input type="number" name="reward_value" required min="1" step="0.01" class="rmbz-input" placeholder="Ex: 100">
                    </div>

                    <div id="saldo_options" class="rmbz-option-box rmbz-option-box--green" style="display:block;">
                        <label class="rmbz-label" style="color:var(--rmbz-success-strong, #059669);">O saldo é retirável? (Levantamento M-Pesa/E-Mola)</label>
                        <select name="is_withdrawable" class="rmbz-select">
                            <option value="0">Não (Serve apenas para gastar dentro da plataforma)</option>
                            <option value="1">Sim (O artista pode levantar este dinheiro)</option>
                        </select>
                    </div>

                    <div id="vip_options" class="rmbz-option-box rmbz-option-box--gold" style="display:none;">
                        <label class="rmbz-label" style="color:var(--rmbz-brand-strong, #d4a000);">Permissões desta Subscrição VIP:</label>
                        <label style="display:block; margin-bottom:8px; cursor:pointer;"><input type="checkbox" name="vip_perm_distribute" value="1" checked> Distribuir músicas nas Plataformas Digitais</label>
                        <label style="display:block; margin-bottom:8px; cursor:pointer;"><input type="checkbox" name="vip_perm_site" value="1" checked> Enviar áudio/álbuns para o Site</label>
                        <label style="display:block; margin-bottom:8px; cursor:pointer;"><input type="checkbox" name="vip_perm_social" value="1" checked> Promover vídeos nas Redes Sociais</label>
                        <label style="display:block; margin-bottom:8px; cursor:pointer;"><input type="checkbox" name="vip_perm_video" value="1"> Concorrer à gravação de Videoclipe (Patrocínio)</label>
                        <label style="display:block; margin-bottom:5px; cursor:pointer;"><input type="checkbox" name="vip_perm_ai" value="1"> 🤖 Assistente de IA (insights, dicas, legendas, plano de lançamento…)</label>
                        <p style="font-size:11px; color:var(--rmbz-text-faint, #888); margin-top:10px; line-height:1.4;">Desmarque as opções que este cupão <strong>NÃO</strong> deve permitir. O artista será bloqueado nessas áreas específicas.</p>
                    </div>

                    <div style="display:flex; gap:14px;">
                        <div class="rmbz-field" style="flex:1;">
                            <label class="rmbz-label">Limite de Usos</label>
                            <input type="number" name="usage_limit" required min="1" value="100" class="rmbz-input">
                        </div>
                        <div class="rmbz-field" style="flex:1;">
                            <label class="rmbz-label">Validade (Opcional)</label>
                            <input type="datetime-local" name="expiry_date" class="rmbz-input">
                            <p class="rmbz-hint">Hora de Moçambique (Maputo).</p>
                        </div>
                    </div>

                    <button type="submit" class="rmbz-wd-btn" style="width:100%; padding:13px; font-size:13px; margin-top:6px;">➕ Gerar Cupão</button>
                </form>

                <script>
                function toggleCouponOptions() {
                    var type = document.getElementById('coupon_reward_type').value;
                    if (type === 'saldo') {
                        document.getElementById('saldo_options').style.display = 'block';
                        document.getElementById('vip_options').style.display = 'none';
                    } else {
                        document.getElementById('saldo_options').style.display = 'none';
                        document.getElementById('vip_options').style.display = 'block';
                    }
                }
                document.addEventListener('DOMContentLoaded', toggleCouponOptions);
                </script>
            </div>

            <div class="rmbz-wd-section" style="flex:2; min-width:500px;">
                <h3 class="rmbz-wd-section-title">Cupões Ativos e Expirados <span class="rmbz-wd-section-count"><?php echo (int) $cup_total; ?></span></h3>
                <div style="padding:16px 20px;">
                <?php if ( empty($cupoes) ) : ?>
                    <p style="color:var(--rmbz-text-faint, #888);">Nenhum cupão criado ainda.</p>
                <?php else : ?>
                    <div class="rmbz-wd-table-wrap">
                    <table class="rmbz-table">
                        <thead><tr><th>Código</th><th>Recompensa</th><th>Regras / Limites</th><th>Usos</th><th>Estado</th><th>Ação</th></tr></thead>
                        <tbody>
                            <?php foreach ( $cupoes as $c ) : 
                                $is_expired = (!empty($c->expiry_date) && strtotime($c->expiry_date . ' UTC') < time());
                                $is_exhausted = ($c->usage_limit > 0 && $c->used_count >= $c->usage_limit);
                                
                                if ($c->status !== 'ativo') { $badge = '<span class="rmbz-badge bg-dark">Inativo</span>'; } 
                                elseif ($is_expired) { $badge = '<span class="rmbz-badge" style="background:#ffebee; color:var(--rmbz-danger-strong, #b91c1c);">Expirado</span>'; } 
                                elseif ($is_exhausted) { $badge = '<span class="rmbz-badge" style="background:#fff3cd; color:var(--rmbz-warning-strong, #856404);">Esgotado</span>'; } 
                                else { $badge = '<span class="rmbz-badge bg-success">Ativo</span>'; }

                                $recompensa = ($c->reward_type === 'saldo') ? '+'.number_format($c->reward_value, 2, ',', '.').' MT' : '+'.intval($c->reward_value).' Dias VIP';
                                
                                // Processar as regras visuais
                                $regras_html = '';
                                $extra = !empty($c->extra_data) ? json_decode($c->extra_data, true) : [];
                                
                                if ($c->reward_type === 'saldo') {
                                    $is_withdrawable = isset($extra['is_withdrawable']) && $extra['is_withdrawable'] == 1;
                                    $regras_html = $is_withdrawable ? '<span style="color:var(--rmbz-success, #10b981); font-size:11px;">✔️ Retirável</span>' : '<span style="color:var(--rmbz-danger, #ef4444); font-size:11px;">❌ Não Retirável (Uso Interno)</span>';
                                } else {
                                    $perms = $extra['vip_permissions'] ?? [];
                                    $regras_html .= '<div style="font-size:10px; line-height:1.4;">';
                                    $regras_html .= (!empty($perms['distribute'])) ? '✔️ Distribuir<br>' : '<span style="color:#e74c3c">❌ Distribuir</span><br>';
                                    $regras_html .= (!empty($perms['site'])) ? '✔️ Site<br>' : '<span style="color:#e74c3c">❌ Site</span><br>';
                                    $regras_html .= (!empty($perms['social'])) ? '✔️ Redes Sociais<br>' : '<span style="color:#e74c3c">❌ Redes Sociais</span><br>';
                                    $regras_html .= (!empty($perms['video'])) ? '✔️ Videoclipe<br>' : '<span style="color:#e74c3c">❌ Videoclipe</span><br>';
                                    $regras_html .= (!empty($perms['ai'])) ? '🤖 Assistente de IA' : '<span style="color:#999">— sem IA</span>';
                                    $regras_html .= '</div>';
                                }

                                $link_del = wp_nonce_url(admin_url('admin-post.php?action=rmbz_admin_delete_coupon&id='.$c->id), 'rmbz_del_coupon_'.$c->id);
                            ?>
                                <tr style="<?php if($is_expired || $is_exhausted) echo 'opacity:0.6;'; ?>">
                                    <td><strong style="color:var(--rmbz-info-strong, #2563eb); font-size:14px;"><?php echo esc_html($c->coupon_code); ?></strong><br><small><?php
                                        if ( !empty($c->expiry_date) ) {
                                            $exp_utc = strtotime($c->expiry_date . ' UTC');
                                            $off = function_exists('rmbz_coupons_site_offset_secs') ? rmbz_coupons_site_offset_secs() : 0;
                                            echo esc_html( gmdate('d/m/y H:i', $exp_utc + $off) );
                                        } else {
                                            echo 'Sem limite de tempo';
                                        }
                                    ?></small></td>
                                    <td><strong><?php echo $recompensa; ?></strong></td>
                                    <td><?php echo $regras_html; ?></td>
                                    <td><strong><?php echo intval($c->used_count); ?></strong> / <?php echo intval($c->usage_limit); ?></td>
                                    <td><?php echo $badge; ?></td>
                                    <td>
                                        <a href="<?php echo esc_url($link_del); ?>" class="rmbz-wd-btn danger small" onclick="return confirm('Apagar este cupão permanentemente?');">Apagar 🗑️</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    </div>
                <?php endif; ?>
                </div>
            </div>

        </div>
    </div>
    <?php
}

/**
 * ==========================================================================
 * GESTÃO DE PACOTES / PLANOS VIP
 * ==========================================================================
 */
function rmbz_mostrar_pagina_pacotes() {
    if ( ! function_exists('rmbz_admin_modern_styles') ) return;
    rmbz_admin_modern_styles();

    global $wpdb;
    $pacotes      = get_option('rmbz_vip_packages', []);
    $table_subs   = $wpdb->prefix . 'rmbz_subscriptions';

    // [1.6.118.23] LIMITAÇÃO CONHECIDA: a tabela rmbz_subscriptions
    // NÃO regista qual pacote (plan_id) foi comprado. Schema actual:
    //   id, user_telemovel, start_date, end_date, last_payment_amount, status
    //
    // Como NÃO há forma fiável de saber qual pacote cada subscrição usou,
    // mostramos **stats globais** das subscrições em vez de por pacote.
    // Para stats por pacote precisamos de:
    //   1) ALTER TABLE para adicionar coluna `plan_id`
    //   2) Migração para inferir plan_id antigo via `last_payment_amount`
    //   3) Atualizar `buy_vip_package` para gravar plan_id ao criar sub
    // (mudança grande — adiada).
    $stats_globais = $wpdb->get_row(
        "SELECT
            COUNT(*) AS subs_total,
            SUM(CASE WHEN status='active' AND end_date > NOW() THEN 1 ELSE 0 END) AS subs_ativas,
            COALESCE(SUM(last_payment_amount),0) AS receita
         FROM {$table_subs}"
    );
    $stats_por_pacote = []; // mantido para compat — vazio porque não há plan_id

    // Detectar se está em modo edição
    $editing_id = isset($_GET['edit']) ? sanitize_text_field($_GET['edit']) : '';
    $editing_pkg = null;
    if ( $editing_id !== '' ) {
        foreach ( $pacotes as $p ) {
            if ( $p['id'] === $editing_id ) { $editing_pkg = $p; break; }
        }
    }
    ?>
    <style>
        /* [1.6.118.20] Pacotes VIP — light theme */
        .rmbz-pkg-wrap { max-width: none; margin: 16px 20px 32px 0; font-family: "Roboto", -apple-system, BlinkMacSystemFont, sans-serif; color: #1a1a1f; }

        .rmbz-pkg-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 12px; }
        .rmbz-pkg-head h1 { font-size: 26px; font-weight: 800; margin: 0 0 4px 0; color: #1d2327; }
        .rmbz-pkg-head p { margin: 0; color: #5f6368; font-size: 13px; }

        /* Notice */
        .rmbz-pkg-notice { padding: 12px 16px; border-radius: 8px; margin-bottom: 16px; font-weight: 600; font-size: 13px; display: flex; align-items: center; gap: 10px; }
        .rmbz-pkg-notice.success { background: #d1fae5; border-left: 4px solid #10b981; color: #065f46; }
        .rmbz-pkg-notice.error   { background: #fee2e2; border-left: 4px solid #ef4444; color: #991b1b; }

        /* Stats globais */
        .rmbz-pkg-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin-bottom: 22px; }
        .rmbz-pkg-stat-card { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 16px 18px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
        .rmbz-pkg-stat-card .label { font-size: 11px; font-weight: 700; text-transform: uppercase; color: #5f6368; letter-spacing: 0.5px; margin-bottom: 6px; }
        .rmbz-pkg-stat-card .value { font-size: 24px; font-weight: 800; color: #1d2327; line-height: 1.1; }
        .rmbz-pkg-stat-card .value .unit { font-size: 12px; font-weight: 500; color: #5f6368; margin-left: 4px; }
        .rmbz-pkg-stat-card.gold .value { color: #d4a000; }
        .rmbz-pkg-stat-card.green .value { color: #047857; }
        .rmbz-pkg-stat-card.blue .value { color: #1e40af; }

        /* Layout principal */
        .rmbz-pkg-layout { display: grid; grid-template-columns: 380px 1fr; gap: 20px; align-items: flex-start; }
        @media (max-width: 1100px) { .rmbz-pkg-layout { grid-template-columns: 1fr; } }

        /* Form card */
        .rmbz-pkg-form-card { background: #fff; border: 1px solid #e1e4e8; border-radius: 14px; padding: 22px 22px 18px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); position: sticky; top: 50px; }
        .rmbz-pkg-form-card.editing { border-left: 4px solid #f0b90b; }
        .rmbz-pkg-form-card h3 { font-size: 14px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; margin: 0 0 16px; color: #1d2327; padding-bottom: 10px; border-bottom: 1px solid #f0f0f1; }
        .rmbz-pkg-form-card label.field-label { font-weight: 700; font-size: 11px; text-transform: uppercase; color: #5f6368; letter-spacing: 0.5px; display: block; margin-bottom: 5px; }
        .rmbz-pkg-form-card input[type="text"], .rmbz-pkg-form-card input[type="number"], .rmbz-pkg-form-card select { width: 100%; padding: 9px 11px; border: 1px solid #d8dae0; border-radius: 6px; font-size: 14px; margin-bottom: 12px; transition: 0.15s; }
        .rmbz-pkg-form-card input:focus, .rmbz-pkg-form-card select:focus { outline: none; border-color: #f0b90b; box-shadow: 0 0 0 3px rgba(240,185,11,0.15); }
        .rmbz-pkg-form-card .field-row { display: flex; gap: 10px; }
        .rmbz-pkg-form-card .field-row > div { flex: 1; }

        .rmbz-pkg-perms-box { background: #f7f7fb; border-radius: 10px; padding: 14px 16px; margin-bottom: 14px; }
        .rmbz-pkg-perms-box .box-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: #047857; margin-bottom: 10px; display: block; }
        .rmbz-pkg-perms-box label.check { display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 5px 0; font-size: 13px; color: #3c434a; }
        .rmbz-pkg-perms-box label.check:hover { color: #1d2327; }
        .rmbz-pkg-perms-box input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; }
        .rmbz-pkg-perms-box .hint { font-size: 11px; color: #5f6368; margin-top: 8px; font-style: italic; }

        .rmbz-pkg-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; width: 100%; padding: 11px 16px; background: #1d2327; color: #f0b90b; border: none; border-radius: 8px; font-weight: 700; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px; cursor: pointer; text-decoration: none; transition: 0.15s; }
        .rmbz-pkg-btn:hover { background: #2c2c34; color: #f0b90b; transform: translateY(-1px); }
        .rmbz-pkg-btn.cancel { background: #f1f3f5; color: #3c434a; margin-top: 8px; }
        .rmbz-pkg-btn.cancel:hover { background: #e9ecef; color: #1d2327; transform: none; }

        /* Lista pacotes */
        .rmbz-pkg-list-card { background: #fff; border: 1px solid #e1e4e8; border-radius: 14px; padding: 0; box-shadow: 0 1px 3px rgba(0,0,0,0.04); overflow: hidden; }
        .rmbz-pkg-list-card h3 { font-size: 14px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; margin: 0; padding: 16px 22px; background: #f7f7fb; border-bottom: 1px solid #e1e4e8; color: #1d2327; }
        .rmbz-pkg-list-card .empty { padding: 60px 20px; text-align: center; color: #5f6368; }
        .rmbz-pkg-list-card .empty .icon { font-size: 48px; margin-bottom: 12px; opacity: 0.4; }
        .rmbz-pkg-list-card .empty .msg { font-size: 14px; }

        .rmbz-pkg-card { padding: 18px 22px; border-bottom: 1px solid #f0f0f1; display: grid; grid-template-columns: 1fr auto; gap: 14px; align-items: center; transition: 0.15s; }
        .rmbz-pkg-card:last-child { border-bottom: none; }
        .rmbz-pkg-card:hover { background: #fbfbfc; }
        .rmbz-pkg-card.featured { background: linear-gradient(90deg, #fffbeb 0%, #fff 60%); border-left: 4px solid #f0b90b; padding-left: 18px; }
        .rmbz-pkg-card.editing-row { background: #fef9e7; border-left: 4px solid #d4a000; }

        .rmbz-pkg-info h4 { font-size: 16px; font-weight: 700; color: #1d2327; margin: 0 0 4px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .rmbz-pkg-info .meta { display: flex; gap: 14px; flex-wrap: wrap; align-items: center; font-size: 13px; color: #3c434a; }
        .rmbz-pkg-info .meta .price { font-weight: 700; font-size: 16px; color: #1e40af; font-variant-numeric: tabular-nums; }
        .rmbz-pkg-info .meta .dias { color: #5f6368; }
        .rmbz-pkg-info .badges { display: inline-flex; gap: 4px; flex-wrap: wrap; }

        .rmbz-pkg-badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; }
        .rmbz-pkg-badge.featured  { background: linear-gradient(135deg, #fff3cd, #ffe5a0); color: #856404; border: 1px solid #f0b90b; }
        .rmbz-pkg-badge.app-only  { background: #dbeafe; color: #1e40af; }
        .rmbz-pkg-badge.site-only { background: #e0e7ff; color: #3730a3; }

        .rmbz-pkg-stats-line { margin-top: 8px; font-size: 12px; color: #5f6368; display: flex; gap: 14px; flex-wrap: wrap; }
        .rmbz-pkg-stats-line strong { color: #1d2327; font-variant-numeric: tabular-nums; }
        .rmbz-pkg-stats-line .receita { color: #047857; }
        .rmbz-pkg-stats-line .ativas  { color: #1e40af; }

        .rmbz-pkg-perms-row { margin-top: 8px; display: flex; gap: 8px; flex-wrap: wrap; }
        .rmbz-pkg-perm-pill { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 10px; font-size: 11px; font-weight: 600; }
        .rmbz-pkg-perm-pill.ok   { background: #d1fae5; color: #065f46; }
        .rmbz-pkg-perm-pill.no   { background: #f1f3f5; color: #9ca3af; text-decoration: line-through; }

        .rmbz-pkg-actions { display: flex; gap: 4px; align-items: center; flex-shrink: 0; }
        .rmbz-pkg-icon-btn { display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 6px; background: #fff; border: 1px solid #e1e4e8; color: #3c434a; text-decoration: none; cursor: pointer; transition: 0.15s; font-size: 14px; }
        .rmbz-pkg-icon-btn:hover { background: #1d2327; color: #f0b90b; border-color: #1d2327; }
        .rmbz-pkg-icon-btn.disabled { opacity: 0.3; cursor: not-allowed; }
        .rmbz-pkg-icon-btn.disabled:hover { background: #fff; color: #3c434a; border-color: #e1e4e8; }
        .rmbz-pkg-icon-btn.danger:hover { background: #ef4444; color: #fff; border-color: #ef4444; }
        .rmbz-pkg-icon-btn.gold:hover { background: #f0b90b; color: #1d2327; border-color: #f0b90b; }
        .rmbz-pkg-icon-btn.featured-on { background: #f0b90b; color: #1d2327; border-color: #f0b90b; }

        /* Editing form note */
        .rmbz-pkg-edit-note { padding: 10px 12px; background: #fef9e7; border-radius: 8px; margin-bottom: 14px; font-size: 12px; color: #856404; }
        .rmbz-pkg-edit-note strong { color: #1d2327; }

        /* ===== [1.5.292] Add-on de IA ===== */
        .rmbz-pkg-perm-pill.ai {
            background: linear-gradient(135deg, #fff3cd, #ffe9b0);
            color: #8a6d0b;
            border: 1px solid rgba(184,134,11,0.45);
            font-weight: 700;
            text-decoration: none;
        }
        .rmbz-pkg-perms-box.ai {
            background: linear-gradient(135deg, rgba(240,185,11,0.10), rgba(240,185,11,0.03));
            border: 1px solid rgba(240,185,11,0.35);
        }
        .rmbz-pkg-perms-box.ai .box-title { color: #8a6d0b; }

        /* ===== [1.5.292] Polimento Material 3 ===== */
        .rmbz-pkg-stat-card,
        .rmbz-pkg-form-card,
        .rmbz-pkg-list-card {
            border-radius: 20px;
            border-color: #e6e8ec;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05), 0 1px 3px rgba(0,0,0,0.06);
        }
        .rmbz-pkg-list-card h3 { border-radius: 0; }
        .rmbz-pkg-form-card input[type="text"],
        .rmbz-pkg-form-card input[type="number"],
        .rmbz-pkg-form-card select {
            border-radius: 12px;
            padding: 11px 13px;
            border-color: #dfe2e7;
            background: #fbfbfd;
        }
        .rmbz-pkg-perms-box { border-radius: 16px; }
        .rmbz-pkg-perm-pill { border-radius: 999px; padding: 4px 11px; }
        .rmbz-pkg-badge { border-radius: 999px; }
        .rmbz-pkg-btn { border-radius: 14px; padding: 13px 16px; }
        .rmbz-pkg-icon-btn { border-radius: 12px; width: 36px; height: 36px; }
        .rmbz-pkg-card { transition: background 0.18s ease; }
        .rmbz-pkg-card:hover { background: rgba(99,86,229,0.04); }
        .rmbz-pkg-stat-card.ai .value { color: #8a6d0b; }
    </style>

    <div class="rmbz-pkg-wrap">
        <div class="rmbz-pkg-head">
            <div>
                <h1>📦 Gestão de Pacotes VIP</h1>
                <p>Crie planos com preços, durações, permissões e canais de venda (App, Site, ou ambos).</p>
            </div>
        </div>

        <?php
        // Notice de status
        $status = $_GET['status'] ?? '';
        $msg    = $_GET['msg'] ?? '';
        if ( $status === 'success' ): ?>
            <div class="rmbz-pkg-notice success">✅ Pacote criado com sucesso!</div>
        <?php elseif ( $status === 'updated' ): ?>
            <div class="rmbz-pkg-notice success">✅ Pacote actualizado com sucesso!</div>
        <?php elseif ( $status === 'deleted' ): ?>
            <div class="rmbz-pkg-notice success">✅ Pacote apagado.</div>
        <?php elseif ( $status === 'error' && $msg !== '' ): ?>
            <div class="rmbz-pkg-notice error">❌ <?php echo esc_html( $msg ); ?></div>
        <?php endif; ?>

        <!-- STATS GLOBAIS -->
        <?php
        $total_pkgs    = count( $pacotes );
        // [1.6.118.23] Stats vêm de $stats_globais (não há plan_id na BD)
        $total_subs    = (int)   ($stats_globais->subs_total   ?? 0);
        $total_ativas  = (int)   ($stats_globais->subs_ativas  ?? 0);
        $total_receita = (float) ($stats_globais->receita      ?? 0);
        // [1.5.292] Quantos pacotes oferecem o add-on de IA.
        $pkgs_com_ia = 0;
        foreach ( $pacotes as $pk ) { if ( ! empty( $pk['ai_offered'] ) ) $pkgs_com_ia++; }
        ?>
        <div class="rmbz-pkg-stats">
            <div class="rmbz-pkg-stat-card">
                <div class="label">Pacotes Criados</div>
                <div class="value"><?php echo $total_pkgs; ?></div>
            </div>
            <div class="rmbz-pkg-stat-card ai">
                <div class="label">🤖 Pacotes com IA</div>
                <div class="value"><?php echo $pkgs_com_ia; ?><span class="unit">de <?php echo $total_pkgs; ?></span></div>
            </div>
            <div class="rmbz-pkg-stat-card gold">
                <div class="label">Subscrições Totais</div>
                <div class="value"><?php echo number_format($total_subs, 0, ',', '.'); ?></div>
            </div>
            <div class="rmbz-pkg-stat-card blue">
                <div class="label">VIPs Activos Agora</div>
                <div class="value"><?php echo number_format($total_ativas, 0, ',', '.'); ?></div>
            </div>
            <div class="rmbz-pkg-stat-card green">
                <div class="label">Receita Total VIP</div>
                <div class="value"><?php echo number_format($total_receita, 2, ',', '.'); ?><span class="unit">MT</span></div>
            </div>
        </div>

        <?php /* [1.6.118.23] Aviso explícito ao admin sobre limitação */ ?>
        <?php if ( $total_subs > 0 && $total_pkgs > 0 ): ?>
        <div style="background: #fef3c7; border-left: 4px solid #f0b90b; padding: 10px 14px; border-radius: 6px; margin-bottom: 16px; font-size: 12px; color: #92400e;">
            <strong>ℹ️ Nota técnica:</strong>
            As subscrições históricas não regista qual pacote foi comprado (a BD não tem coluna <code>plan_id</code>).
            Por isso aparecem aqui apenas <strong>stats globais</strong> e não por pacote individual.
            Para ter stats por pacote no futuro, precisamos de migração da BD.
        </div>
        <?php endif; ?>

        <div class="rmbz-pkg-layout">

            <!-- FORM CRIAR / EDITAR -->
            <div class="rmbz-pkg-form-card <?php echo $editing_pkg ? 'editing' : ''; ?>">
                <h3>
                    <?php if ( $editing_pkg ): ?>
                        ✏️ Editar Pacote
                    <?php else: ?>
                        ➕ Criar Novo Pacote
                    <?php endif; ?>
                </h3>

                <?php if ( $editing_pkg ): ?>
                    <div class="rmbz-pkg-edit-note">
                        A editar pacote <strong><?php echo esc_html( $editing_pkg['nome'] ); ?></strong>.
                        Alterações afectam pacote para novas subscrições — quem já comprou continua com o plano original.
                    </div>
                <?php endif; ?>

                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                    <input type="hidden" name="action" value="rmbz_admin_save_package">
                    <?php if ( $editing_pkg ): ?>
                        <input type="hidden" name="pkg_id" value="<?php echo esc_attr( $editing_pkg['id'] ); ?>">
                    <?php endif; ?>
                    <?php wp_nonce_field('rmbz_save_package_nonce'); ?>

                    <label class="field-label">Nome do Plano</label>
                    <input type="text" name="pkg_nome" required maxlength="60" placeholder="Ex: Plano Básico, Plano Gold..." value="<?php echo $editing_pkg ? esc_attr( $editing_pkg['nome'] ) : ''; ?>">

                    <div class="field-row">
                        <div>
                            <label class="field-label">Preço (MT)</label>
                            <input type="number" name="pkg_preco" required min="1" step="0.01" placeholder="500" value="<?php echo $editing_pkg ? esc_attr( $editing_pkg['preco'] ) : ''; ?>">
                        </div>
                        <div>
                            <label class="field-label">Duração (dias)</label>
                            <input type="number" name="pkg_dias" required min="1" max="3650" placeholder="30" value="<?php echo $editing_pkg ? esc_attr( $editing_pkg['dias'] ) : ''; ?>">
                        </div>
                    </div>

                    <label class="field-label">Canal de Venda</label>
                    <select name="pkg_channel">
                        <?php $current_channel = $editing_pkg['channel'] ?? 'both'; ?>
                        <option value="both"      <?php selected( $current_channel, 'both' ); ?>>🌐 Ambos (App + Site)</option>
                        <option value="app_only"  <?php selected( $current_channel, 'app_only' ); ?>>📱 Apenas App</option>
                        <option value="site_only" <?php selected( $current_channel, 'site_only' ); ?>>🖥️ Apenas Site</option>
                    </select>

                    <label class="check" style="margin-bottom:14px;">
                        <input type="checkbox" name="pkg_featured" value="1" <?php checked( ! empty( $editing_pkg['featured'] ) ); ?> style="width:16px; height:16px;">
                        <span style="font-size:13px;">⭐ Destacar (aparece primeiro na lista)</span>
                    </label>

                    <div class="rmbz-pkg-perms-box">
                        <span class="box-title">✓ Permissões do plano</span>
                        <?php
                        $perms_check = $editing_pkg['perms'] ?? [ 'site' => 1, 'social' => 1, 'distribute' => 1, 'video' => 0 ];
                        ?>
                        <label class="check"><input type="checkbox" name="perm_site"       value="1" <?php checked( ! empty($perms_check['site']) ); ?>> Enviar Músicas para Site</label>
                        <label class="check"><input type="checkbox" name="perm_social"     value="1" <?php checked( ! empty($perms_check['social']) ); ?>> Promover nas Redes Sociais</label>
                        <label class="check"><input type="checkbox" name="perm_distribute" value="1" <?php checked( ! empty($perms_check['distribute']) ); ?>> Distribuir nas Lojas Digitais (Spotify, etc)</label>
                        <label class="check"><input type="checkbox" name="perm_video"      value="1" <?php checked( ! empty($perms_check['video']) ); ?>> Candidatar a Videoclipe</label>
                        <p class="hint">Desmarque o que este plano NÃO inclui.</p>
                    </div>

                    <?php
                    // [1.5.291] Add-on do Assistente de IA — opcional no checkout.
                    $ai_offered_chk = ! empty( $editing_pkg['ai_offered'] );
                    $ai_price_val   = isset( $editing_pkg['ai_price'] ) ? (float) $editing_pkg['ai_price'] : 0;
                    ?>
                    <div class="rmbz-pkg-perms-box ai" style="margin-top:12px;">
                        <span class="box-title">🤖 Assistente de IA (add-on)</span>
                        <label class="check">
                            <input type="checkbox" name="pkg_ai_offered" value="1" <?php checked( $ai_offered_chk ); ?>>
                            Oferecer o Assistente de IA neste plano
                        </label>
                        <label style="display:block; margin-top:8px; font-size:13px;">
                            Preço do add-on (MT):
                            <input type="number" step="0.01" min="0" name="pkg_ai_price"
                                   value="<?php echo esc_attr( $ai_price_val ); ?>"
                                   style="width:120px; margin-left:6px;">
                        </label>
                        <p class="hint">No checkout, o artista vê uma opção "🤖 Assistente de IA (+preço)" que pode marcar/desmarcar. Deixe o preço a 0 para oferecer grátis (mas opcional).</p>
                    </div>

                    <?php
                    // [1.5.372] Durações (1/2/3/4/12 meses) e desconto opcional por duração.
                    $disc_cfg = ( isset( $editing_pkg['duration_discounts'] ) && is_array( $editing_pkg['duration_discounts'] ) )
                        ? $editing_pkg['duration_discounts'] : [];
                    $disc_of = function( $m ) use ( $disc_cfg ) {
                        return isset( $disc_cfg[ $m ] ) ? (float) $disc_cfg[ $m ] : ( isset( $disc_cfg[ (string) $m ] ) ? (float) $disc_cfg[ (string) $m ] : 0 );
                    };
                    ?>
                    <div class="rmbz-pkg-perms-box" style="margin-top:12px;">
                        <span class="box-title">📅 Durações &amp; Descontos</span>
                        <p class="hint" style="margin-top:4px;">
                            O preço/período acima são a <strong>unidade base</strong>. As durações maiores <strong>multiplicam</strong> esse período e mostram os <strong>dias reais</strong>.
                            Ex.: 800 MT por 15 dias → 800 (15 dias), 1600 (30 dias), 2400 (45 dias), 3200 (60 dias), 9600 (180 dias).
                            Pode dar um <strong>desconto (%)</strong> por duração (2×/3×/4×/12×) para incentivar planos mais longos. Deixe a 0 para sem desconto.
                        </p>
                        <div class="field-row" style="gap:10px; flex-wrap:wrap;">
                            <div>
                                <label class="field-label">2× período — desconto %</label>
                                <input type="number" name="pkg_disc_2" min="0" max="90" step="1" placeholder="0" value="<?php echo esc_attr( $disc_of( 2 ) ?: '' ); ?>" style="width:120px;">
                            </div>
                            <div>
                                <label class="field-label">3× período — desconto %</label>
                                <input type="number" name="pkg_disc_3" min="0" max="90" step="1" placeholder="0" value="<?php echo esc_attr( $disc_of( 3 ) ?: '' ); ?>" style="width:120px;">
                            </div>
                            <div>
                                <label class="field-label">4× período — desconto %</label>
                                <input type="number" name="pkg_disc_4" min="0" max="90" step="1" placeholder="0" value="<?php echo esc_attr( $disc_of( 4 ) ?: '' ); ?>" style="width:120px;">
                            </div>
                            <div>
                                <label class="field-label">12× período — desconto %</label>
                                <input type="number" name="pkg_disc_12" min="0" max="90" step="1" placeholder="0" value="<?php echo esc_attr( $disc_of( 12 ) ?: '' ); ?>" style="width:120px;">
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="rmbz-pkg-btn">
                        <?php echo $editing_pkg ? '💾 Guardar Alterações' : '💾 Criar Pacote'; ?>
                    </button>
                    <?php if ( $editing_pkg ): ?>
                        <a href="<?php echo admin_url('admin.php?page=rmbz-pacotes'); ?>" class="rmbz-pkg-btn cancel">Cancelar Edição</a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- LISTA DE PACOTES -->
            <div class="rmbz-pkg-list-card">
                <h3>📋 Pacotes Existentes (<?php echo $total_pkgs; ?>)</h3>

                <?php if ( empty( $pacotes ) ) : ?>
                    <div class="empty">
                        <div class="icon">📦</div>
                        <div class="msg">
                            Nenhum pacote criado.<br>
                            <span style="font-size:12px; color:#9a3412;">Os artistas não conseguirão subscrever VIP enquanto não houver pacotes.</span>
                        </div>
                    </div>
                <?php else : ?>

                    <?php foreach ( $pacotes as $index => $pack ) :
                        $p_perms = $pack['perms'] ?? [];
                        $is_featured = ! empty( $pack['featured'] );
                        $channel = $pack['channel'] ?? 'both';
                        $is_editing_row = ( $editing_pkg && $editing_pkg['id'] === $pack['id'] );

                        $st = $stats_por_pacote[ $pack['id'] ] ?? null;
                        $subs_total   = $st ? (int) $st->subs_total : 0;
                        $subs_ativas  = $st ? (int) $st->subs_ativas : 0;
                        $receita_pkg  = $st ? (float) $st->receita : 0;

                        $link_edit     = admin_url('admin.php?page=rmbz-pacotes&edit=' . $pack['id']);
                        $link_del      = wp_nonce_url(admin_url('admin-post.php?action=rmbz_admin_delete_package&id=' . $pack['id']), 'rmbz_del_pack_' . $pack['id']);
                        $link_up       = wp_nonce_url(admin_url('admin-post.php?action=rmbz_admin_move_package&id=' . $pack['id'] . '&direction=up'), 'rmbz_move_pack_' . $pack['id']);
                        $link_down     = wp_nonce_url(admin_url('admin-post.php?action=rmbz_admin_move_package&id=' . $pack['id'] . '&direction=down'), 'rmbz_move_pack_' . $pack['id']);
                        $link_featured = wp_nonce_url(admin_url('admin-post.php?action=rmbz_admin_toggle_featured_package&id=' . $pack['id']), 'rmbz_toggle_featured_' . $pack['id']);

                        // [1.6.118.23] Confirm genérico — sem plan_id não conseguimos
                        // saber quantas subs têm este pacote especificamente
                        $confirm_del = 'Apagar este pacote? Quem já comprou continua com o plano original.';
                    ?>
                        <div class="rmbz-pkg-card <?php echo $is_featured ? 'featured' : ''; ?> <?php echo $is_editing_row ? 'editing-row' : ''; ?>">

                            <div class="rmbz-pkg-info">
                                <h4>
                                    <?php echo esc_html( $pack['nome'] ); ?>
                                    <div class="badges">
                                        <?php if ( $is_featured ): ?>
                                            <span class="rmbz-pkg-badge featured">⭐ Destacado</span>
                                        <?php endif; ?>
                                        <?php if ( $channel === 'app_only' ): ?>
                                            <span class="rmbz-pkg-badge app-only">📱 Só App</span>
                                        <?php elseif ( $channel === 'site_only' ): ?>
                                            <span class="rmbz-pkg-badge site-only">🖥️ Só Site</span>
                                        <?php endif; ?>
                                    </div>
                                </h4>

                                <div class="meta">
                                    <span class="price"><?php echo number_format( (float) $pack['preco'], 2, ',', '.' ); ?> MT</span>
                                    <span class="dias">📅 <?php echo (int) $pack['dias']; ?> dias</span>
                                </div>

                                <?php /* [1.6.118.23] Stats por pacote removidos por
                                       falta de plan_id na BD. Quando migrarmos, voltam aqui. */ ?>
                                <?php /* <div class="rmbz-pkg-stats-line">
                                    <span><strong>?</strong> subs totais</span>
                                </div> */ ?>

                                <div class="rmbz-pkg-perms-row">
                                    <span class="rmbz-pkg-perm-pill <?php echo ! empty($p_perms['site']) ? 'ok' : 'no'; ?>">📡 Site</span>
                                    <span class="rmbz-pkg-perm-pill <?php echo ! empty($p_perms['social']) ? 'ok' : 'no'; ?>">📱 Redes</span>
                                    <span class="rmbz-pkg-perm-pill <?php echo ! empty($p_perms['distribute']) ? 'ok' : 'no'; ?>">🌍 Lojas</span>
                                    <span class="rmbz-pkg-perm-pill <?php echo ! empty($p_perms['video']) ? 'ok' : 'no'; ?>">🎬 Videoclipe</span>
                                    <?php
                                    // [1.5.292] Add-on do Assistente de IA.
                                    $row_ai_offered = ! empty( $pack['ai_offered'] );
                                    $row_ai_price   = isset( $pack['ai_price'] ) ? (float) $pack['ai_price'] : 0.0;
                                    if ( $row_ai_offered ):
                                    ?>
                                        <span class="rmbz-pkg-perm-pill ai">🤖 IA +<?php echo number_format( $row_ai_price, 2, ',', '.' ); ?> MT</span>
                                    <?php else: ?>
                                        <span class="rmbz-pkg-perm-pill no">🤖 IA</span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <div class="rmbz-pkg-actions">
                                <a href="<?php echo esc_url( $link_featured ); ?>" class="rmbz-pkg-icon-btn gold <?php echo $is_featured ? 'featured-on' : ''; ?>" title="<?php echo $is_featured ? 'Remover destaque' : 'Destacar'; ?>">⭐</a>

                                <?php if ( $index > 0 ): ?>
                                    <a href="<?php echo esc_url( $link_up ); ?>" class="rmbz-pkg-icon-btn" title="Subir posição">⬆</a>
                                <?php else: ?>
                                    <span class="rmbz-pkg-icon-btn disabled">⬆</span>
                                <?php endif; ?>

                                <?php if ( $index < count( $pacotes ) - 1 ): ?>
                                    <a href="<?php echo esc_url( $link_down ); ?>" class="rmbz-pkg-icon-btn" title="Descer posição">⬇</a>
                                <?php else: ?>
                                    <span class="rmbz-pkg-icon-btn disabled">⬇</span>
                                <?php endif; ?>

                                <a href="<?php echo esc_url( $link_edit ); ?>" class="rmbz-pkg-icon-btn" title="Editar">✏️</a>
                                <a href="<?php echo esc_url( $link_del ); ?>" class="rmbz-pkg-icon-btn danger" title="Apagar" onclick="return confirm('<?php echo esc_js( $confirm_del ); ?>');">🗑️</a>
                            </div>
                        </div>
                    <?php endforeach; ?>

                <?php endif; ?>
            </div>

        </div>
    </div>
    <?php
}
?>
