<?php
// includes/admin/admin-analytics.php

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Acesso direto bloqueado
}

/**
 * [1.6.118.19] Renderiza Visão Geral da Plataforma — Dashboard completo
 *
 * Mapeia TODAS as áreas relevantes do plugin + app:
 *   - 🚨 Alertas Urgentes (acção necessária HOJE)
 *   - 💰 Finanças (depósitos, levantamentos, saldo, receita)
 *   - 👥 Artistas (totais, online, origem, estado)
 *   - 📱 App & Devices (versões em uso, sessões, push tokens)
 *   - 🎵 Conteúdo (envios, projetos, distribuição)
 *   - 🛡 Operações Pendentes
 *   - 🏆 Top artistas + Top depositantes
 *   - ⚙ Sistema (DB version, anúncios, configuração)
 *
 * Light theme moderno consistente com Gestão de Artistas/Perfil/Depósitos.
 */
function rmbz_render_admin_analytics_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( 'Não tem permissão para aceder a esta página.' );
    }

    global $wpdb;

    // ========================================================================
    // TABELAS
    // ========================================================================
    $t_wallets      = $wpdb->prefix . 'rmbz_wallets';
    $t_subs         = $wpdb->prefix . 'rmbz_subscriptions';
    $t_deps         = $wpdb->prefix . 'rmbz_deposit_requests';
    $t_withd        = $wpdb->prefix . 'rmbz_withdrawal_requests';
    $t_subm         = $wpdb->prefix . 'rmbz_artist_submissions';
    $t_proj         = $wpdb->prefix . 'rmbz_artist_projects';
    $t_devs         = $wpdb->prefix . 'rmbz_app_devices';
    $t_tokens       = $wpdb->prefix . 'rmbz_api_refresh_tokens';
    $t_push         = $wpdb->prefix . 'rmbz_app_push_tokens';
    $t_announce     = $wpdb->prefix . 'rmbz_app_announcements';
    $t_releases     = $wpdb->prefix . 'rmbz_distro_releases';
    $t_milestones   = $wpdb->prefix . 'rmbz_artist_milestones';

    // Helper para verificar existência de tabela (algumas podem não estar criadas)
    $table_exists = function( $table ) use ( $wpdb ) {
        return $wpdb->get_var( "SHOW TABLES LIKE '$table'" ) === $table;
    };

    // ========================================================================
    // 💰 FINANÇAS
    // ========================================================================
    $fin = $wpdb->get_row(
        "SELECT
            (SELECT COALESCE(SUM(amount),0) FROM {$t_deps} WHERE status='aprovado')   AS dep_total,
            (SELECT COALESCE(SUM(amount),0) FROM {$t_deps} WHERE status='aprovado' AND DATE(processed_date)=CURDATE()) AS dep_hoje,
            (SELECT COALESCE(SUM(amount),0) FROM {$t_deps} WHERE status='aprovado' AND processed_date >= NOW()-INTERVAL 7 DAY) AS dep_semana,
            (SELECT COALESCE(SUM(amount),0) FROM {$t_deps} WHERE status='pendente')   AS dep_pendente_valor,
            (SELECT COUNT(*)                  FROM {$t_deps} WHERE status='pendente') AS dep_pendente_cnt,

            (SELECT COALESCE(SUM(amount),0) FROM {$t_withd} WHERE status='aprovado')   AS withd_total,
            (SELECT COALESCE(SUM(amount),0) FROM {$t_withd} WHERE status='aprovado' AND DATE(processed_date)=CURDATE()) AS withd_hoje,
            (SELECT COALESCE(SUM(amount),0) FROM {$t_withd} WHERE status='pendente')   AS withd_pendente_valor,
            (SELECT COUNT(*)                  FROM {$t_withd} WHERE status='pendente') AS withd_pendente_cnt,

            (SELECT COALESCE(SUM(balance),0) FROM {$t_wallets} WHERE (extra_data NOT LIKE '%\"deleted_at\"%' OR extra_data IS NULL)) AS saldo_caixa,
            (SELECT COALESCE(SUM(amount_paid),0) FROM {$t_proj}) AS receita_projetos"
    );

    // Receita líquida = depósitos aprovados - levantamentos pagos
    $receita_liquida = (float) $fin->dep_total - (float) $fin->withd_total;

    // [1.6.118.23] Subscrições recentes — antes era "Pacote mais popular"
    // mas a tabela rmbz_subscriptions NÃO tem coluna plan_id. Em vez disso
    // mostramos volume + receita das subscrições recentes.
    $top_vip_pkg = $wpdb->get_row(
        "SELECT COUNT(*) AS cnt, COALESCE(SUM(last_payment_amount),0) AS receita
         FROM {$t_subs}
         WHERE start_date >= NOW()-INTERVAL 30 DAY"
    );

    // ========================================================================
    // 👥 ARTISTAS
    // ========================================================================
    $artists = $wpdb->get_row(
        "SELECT
            COUNT(*) AS total,
            SUM(CASE WHEN extra_data LIKE '%\"deleted_at\"%' THEN 1 ELSE 0 END) AS lixeira,
            SUM(CASE WHEN extra_data NOT LIKE '%\"deleted_at\"%' OR extra_data IS NULL THEN 1 ELSE 0 END) AS ativos,
            SUM(CASE WHEN is_banned=1 AND (extra_data NOT LIKE '%\"deleted_at\"%' OR extra_data IS NULL) THEN 1 ELSE 0 END) AS banidos,
            SUM(CASE WHEN extra_data LIKE '%\"account_status\":\"expired\"%' AND extra_data NOT LIKE '%\"deleted_at\"%' THEN 1 ELSE 0 END) AS expirados
         FROM {$t_wallets}"
    );

    $total_vips = (int) $wpdb->get_var(
        "SELECT COUNT(DISTINCT s.user_telemovel)
         FROM {$t_subs} s
         INNER JOIN {$t_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)"
    );

    // Novos artistas (últimos 7 e 30 dias) — usando primeiro depósito como proxy
    $novos_7d = (int) $wpdb->get_var(
        "SELECT COUNT(DISTINCT user_telemovel)
         FROM {$t_deps}
         WHERE is_first_deposit=1 AND status='aprovado'
           AND processed_date >= NOW()-INTERVAL 7 DAY"
    );
    $novos_30d = (int) $wpdb->get_var(
        "SELECT COUNT(DISTINCT user_telemovel)
         FROM {$t_deps}
         WHERE is_first_deposit=1 AND status='aprovado'
           AND processed_date >= NOW()-INTERVAL 30 DAY"
    );

    // Online agora (extra_data['last_seen'] < 5min)
    $cutoff_online = time() - 300;
    $online_now = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT COUNT(*) FROM {$t_wallets}
         WHERE extra_data LIKE %s
           AND (extra_data NOT LIKE '%%\"deleted_at\"%%' OR extra_data IS NULL)",
        '%"last_seen":' . $cutoff_online . '%'  // imperfeito mas approximação
    ) );
    // Melhor: contar wallets com last_seen recente — vamos fazer scan limitado
    // (porque last_seen está em JSON, regex no MySQL é fraco — fazemos em PHP)
    $sample_wallets = $wpdb->get_results(
        "SELECT extra_data FROM {$t_wallets}
         WHERE extra_data LIKE '%last_seen%'
           AND (extra_data NOT LIKE '%\"deleted_at\"%' OR extra_data IS NULL)"
    );
    $online_now = 0;
    foreach ( $sample_wallets as $sw ) {
        $ext = json_decode( $sw->extra_data, true );
        if ( is_array( $ext ) && ! empty( $ext['last_seen'] ) && intval( $ext['last_seen'] ) > $cutoff_online ) {
            $online_now++;
        }
    }

    // Origem App vs Site (via primeiro depósito)
    $origem = $wpdb->get_row(
        "SELECT
            SUM(CASE WHEN source_platform='app' THEN 1 ELSE 0 END)  AS via_app,
            SUM(CASE WHEN source_platform='site' THEN 1 ELSE 0 END) AS via_site,
            SUM(CASE WHEN source_platform IS NULL OR source_platform='' THEN 1 ELSE 0 END) AS antigos
         FROM {$t_deps} WHERE is_first_deposit=1"
    );

    // ========================================================================
    // 📱 APP & DEVICES
    // ========================================================================
    $devices_total = 0;
    $devices_versoes = [];
    if ( $table_exists( $t_devs ) ) {
        $devices_total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$t_devs}" );
        $devices_versoes = $wpdb->get_results(
            "SELECT last_app_version, COUNT(*) AS cnt
             FROM {$t_devs}
             WHERE last_app_version IS NOT NULL AND last_app_version != ''
             GROUP BY last_app_version
             ORDER BY cnt DESC LIMIT 10"
        );
    }

    $sessions_active = 0;
    if ( $table_exists( $t_tokens ) ) {
        $sessions_active = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$t_tokens}
             WHERE (revoked_at IS NULL OR revoked_at='') AND expires_at > NOW()"
        );
    }

    $push_tokens = 0;
    if ( $table_exists( $t_push ) ) {
        $push_tokens = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$t_push}" );
    }

    // ========================================================================
    // 🎵 CONTEÚDO
    // ========================================================================
    $envios_site      = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$t_subm} WHERE scenario_type = 'Publicação Site'");
    $envios_sociais   = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$t_subm} WHERE scenario_type = 'Redes Sociais'");
    $envios_pendentes = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$t_subm} WHERE review_status = 'pendente'");
    $envios_publicados = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$t_subm} WHERE review_status = 'publicado' OR review_status = 'aprovado'");

    $projetos_total      = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$t_proj}");
    $projetos_concluidos = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$t_proj} WHERE production_status = 'done'");
    $projetos_abertos    = $projetos_total - $projetos_concluidos;

    // Distribuição digital
    $distro = (object) [ 'total' => 0, 'pendentes' => 0, 'live' => 0 ];
    if ( $table_exists( $t_releases ) ) {
        $distro->total     = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$t_releases}" );
        $distro->pendentes = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$t_releases} WHERE status IN ('pendente','em_revisao','enviado')" );
        $distro->live      = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$t_releases} WHERE status = 'publicado' OR status = 'live'" );
    }

    // ========================================================================
    // 🚨 ALERTAS URGENTES
    // ========================================================================
    $alertas = [];

    // 1º depósitos a expirar em <6h
    $first_dep_expira = $wpdb->get_results(
        "SELECT id, user_telemovel, amount, request_date
         FROM {$t_deps}
         WHERE status='pendente' AND is_first_deposit=1
           AND request_date < (UTC_TIMESTAMP() - INTERVAL 18 HOUR)
         ORDER BY request_date ASC LIMIT 5"
    );
    if ( count( $first_dep_expira ) > 0 ) {
        $alertas[] = [
            'icon' => '⏰',
            'level' => 'urgent',
            'title' => count( $first_dep_expira ) . ' depósito(s) de abertura a expirar em <6h',
            'desc'  => 'Após 24h sem aprovação são apagados automaticamente.',
            'cta_label' => 'Ver Depósitos →',
            'cta_url'   => admin_url( 'admin.php?page=rmbz-depositos&type=first' ),
        ];
    }

    // Levantamentos de risco crítico
    $withd_pendentes_obj = $wpdb->get_results(
        "SELECT * FROM {$t_withd} WHERE status='pendente'"
    );
    $crit_count = 0;
    if ( function_exists( 'rmbz_wg_build_forensic_report' ) ) {
        foreach ( $withd_pendentes_obj as $w ) {
            $rep = rmbz_wg_build_forensic_report( $w );
            if ( (int) $rep['risk_score'] >= 80 ) $crit_count++;
        }
    }
    if ( $crit_count > 0 ) {
        $alertas[] = [
            'icon'  => '🚨',
            'level' => 'urgent',
            'title' => $crit_count . ' levantamento(s) de risco CRÍTICO',
            'desc'  => 'Guarda-Costas detectou padrões suspeitos. Revise antes de aprovar.',
            'cta_label' => 'Investigar →',
            'cta_url'   => admin_url( 'admin.php?page=rmbz-pedidos-levantamento&risk=crit' ),
        ];
    }

    // Envios pendentes há muito tempo (>3 dias)
    $envios_stale = (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM {$t_subm}
         WHERE review_status = 'pendente'
           AND submission_date < (NOW() - INTERVAL 3 DAY)"
    );
    if ( $envios_stale > 0 ) {
        $alertas[] = [
            'icon'  => '📋',
            'level' => 'warn',
            'title' => $envios_stale . ' envio(s) pendentes há mais de 3 dias',
            'desc'  => 'Artistas podem estar a aguardar resposta há vários dias.',
            'cta_label' => 'Ver Fila →',
            'cta_url'   => admin_url( 'admin.php?page=rmbz-envios-site' ),
        ];
    }

    // VIPs a expirar nas próximas 48h
    $vips_expirar = (int) $wpdb->get_var(
        "SELECT COUNT(DISTINCT user_telemovel) FROM {$t_subs}
         WHERE status='active' AND end_date > NOW() AND end_date <= (NOW() + INTERVAL 48 HOUR)"
    );
    if ( $vips_expirar > 0 ) {
        $alertas[] = [
            'icon'  => '⌛',
            'level' => 'info',
            'title' => $vips_expirar . ' VIP(s) a expirar nas próximas 48h',
            'desc'  => 'Oportunidade para enviar lembrete de renovação.',
            'cta_label' => null, 'cta_url' => null,
        ];
    }

    // ========================================================================
    // 🏆 TOP ARTISTAS (mais envios) + 💎 TOP DEPOSITANTES
    // ========================================================================
    $top_artists = $wpdb->get_results(
        "SELECT s.artist_telemovel, w.user_nome, COUNT(s.id) as total_envios
         FROM {$t_subm} s
         LEFT JOIN {$t_wallets} w ON s.artist_telemovel = w.user_telemovel
         GROUP BY s.artist_telemovel
         ORDER BY total_envios DESC
         LIMIT 5"
    );

    $top_depositantes = $wpdb->get_results(
        "SELECT d.user_telemovel, w.user_nome,
                SUM(d.amount) AS total_dep,
                COUNT(d.id) AS dep_cnt
         FROM {$t_deps} d
         LEFT JOIN {$t_wallets} w ON d.user_telemovel = w.user_telemovel
         WHERE d.status='aprovado'
         GROUP BY d.user_telemovel
         ORDER BY total_dep DESC
         LIMIT 5"
    );

    // ========================================================================
    // ⚙ SISTEMA
    // ========================================================================
    $db_version       = get_option( 'rmbz_db_version', 'desconhecido' );
    $min_app_version  = get_option( 'rmbz_min_app_version_code', 0 );
    $latest_app_version = get_option( 'rmbz_latest_app_version_code', 0 );
    $vip_packages     = (array) get_option( 'rmbz_vip_packages', [] );
    $exchange_rate    = (float) get_option( 'rmbz_exchange_rate', 0 );
    $referral_blacklist_cnt = count( (array) get_option( 'rmbz_referral_blacklist', [] ) );

    $announcements_active = 0;
    if ( $table_exists( $t_announce ) ) {
        $announcements_active = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$t_announce}
             WHERE active = 1
               AND (starts_at IS NULL OR starts_at <= NOW())
               AND (ends_at IS NULL OR ends_at > NOW())"
        );
    }

    ?>
    <style>
        /* [1.6.118.19] Visão Geral — light theme moderno */
        .rmbz-overview-wrap { max-width: none; margin: 16px 20px 32px 0; font-family: "Roboto", -apple-system, BlinkMacSystemFont, sans-serif; color: #1a1a1f; line-height: 1.5; }
        .rmbz-overview-wrap * { box-sizing: border-box; }

        /* Header */
        .rmbz-ov-head { background: #fff; border: 1px solid #e1e4e8; border-radius: 14px; padding: 22px 24px; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); display: flex; gap: 18px; align-items: center; }
        .rmbz-ov-head-icon { font-size: 42px; line-height: 1; }
        .rmbz-ov-head h1 { font-size: 26px; font-weight: 800; margin: 0 0 4px 0; color: #1d2327; letter-spacing: -0.01em; }
        .rmbz-ov-head p { margin: 0; color: #5f6368; font-size: 13px; }
        .rmbz-ov-refresh { margin-left: auto; padding: 8px 14px; background: #1d2327; color: #f0b90b; text-decoration: none; border-radius: 8px; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; transition: 0.15s; }
        .rmbz-ov-refresh:hover { background: #2c2c34; color: #f0b90b; transform: translateY(-1px); }

        /* Alertas */
        .rmbz-ov-alerts { display: flex; flex-direction: column; gap: 10px; margin-bottom: 22px; }
        .rmbz-ov-alert { display: flex; align-items: center; gap: 14px; padding: 14px 18px; border-radius: 10px; border-left: 4px solid; }
        .rmbz-ov-alert.urgent { background: #fef2f2; border-left-color: #ef4444; color: #991b1b; }
        .rmbz-ov-alert.warn   { background: #fffbeb; border-left-color: #f59e0b; color: #92400e; }
        .rmbz-ov-alert.info   { background: #eff6ff; border-left-color: #3b82f6; color: #1e40af; }
        .rmbz-ov-alert .icon { font-size: 22px; flex-shrink: 0; }
        .rmbz-ov-alert .body { flex: 1; }
        .rmbz-ov-alert .title { font-weight: 700; font-size: 14px; }
        .rmbz-ov-alert .desc  { font-size: 12px; opacity: 0.85; margin-top: 2px; }
        .rmbz-ov-alert .cta { padding: 6px 14px; background: #fff; color: inherit; text-decoration: none; border-radius: 6px; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; border: 1px solid currentColor; transition: 0.15s; flex-shrink: 0; }
        .rmbz-ov-alert .cta:hover { background: currentColor; color: #fff; }
        .rmbz-ov-alert .cta:hover { color: inherit; } /* fix hover */

        /* Section title */
        .rmbz-ov-section-title { font-size: 11px; font-weight: 700; text-transform: uppercase; color: #5f6368; letter-spacing: 1px; margin: 28px 0 12px 0; padding-bottom: 8px; border-bottom: 1px solid #e1e4e8; display: flex; align-items: center; gap: 8px; }
        .rmbz-ov-section-title .icon { font-size: 16px; }

        /* Stats grid genérico */
        .rmbz-ov-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px; margin-bottom: 6px; }
        .rmbz-ov-card { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 18px 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); transition: 0.15s; }
        .rmbz-ov-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
        .rmbz-ov-card .label { font-size: 11px; font-weight: 700; text-transform: uppercase; color: #5f6368; letter-spacing: 0.5px; margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
        .rmbz-ov-card .value { font-size: 26px; font-weight: 800; color: #1d2327; line-height: 1.1; font-variant-numeric: tabular-nums; }
        .rmbz-ov-card .value .unit { font-size: 13px; font-weight: 500; color: #5f6368; margin-left: 4px; }
        .rmbz-ov-card .sub { font-size: 11px; color: #5f6368; margin-top: 6px; font-weight: 500; }
        .rmbz-ov-card.green   .value { color: #047857; }
        .rmbz-ov-card.red     .value { color: #b91c1c; }
        .rmbz-ov-card.gold    .value { color: #d4a000; }
        .rmbz-ov-card.blue    .value { color: #1e40af; }
        .rmbz-ov-card.purple  .value { color: #6d28d9; }
        .rmbz-ov-card.orange  .value { color: #9a3412; }
        .rmbz-ov-card .delta { display: inline-block; font-size: 11px; font-weight: 700; padding: 2px 6px; border-radius: 8px; margin-left: 6px; background: #d1fae5; color: #065f46; }

        /* Tabela horizontal/breakdown */
        .rmbz-ov-breakdown { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 18px 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.04); margin-bottom: 6px; }
        .rmbz-ov-breakdown h4 { font-size: 12px; font-weight: 700; text-transform: uppercase; color: #5f6368; letter-spacing: 0.5px; margin: 0 0 12px 0; }
        .rmbz-ov-bd-row { display: grid; grid-template-columns: 100px 1fr 60px; gap: 12px; align-items: center; padding: 6px 0; font-size: 13px; }
        .rmbz-ov-bd-label { color: #3c434a; font-weight: 600; }
        .rmbz-ov-bd-bar { background: #f1f3f5; height: 8px; border-radius: 4px; overflow: hidden; }
        .rmbz-ov-bd-bar-fill { height: 100%; border-radius: 4px; transition: width 0.3s; }
        .rmbz-ov-bd-bar-fill.app    { background: linear-gradient(90deg, #3b82f6, #1e40af); }
        .rmbz-ov-bd-bar-fill.site   { background: linear-gradient(90deg, #6366f1, #3730a3); }
        .rmbz-ov-bd-bar-fill.old    { background: #9ca3af; }
        .rmbz-ov-bd-bar-fill.gold   { background: linear-gradient(90deg, #f0b90b, #d4a000); }
        .rmbz-ov-bd-value { text-align: right; font-weight: 700; color: #1d2327; font-size: 12px; font-variant-numeric: tabular-nums; }

        /* Top lists */
        .rmbz-ov-tops { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        @media (max-width: 1100px) { .rmbz-ov-tops { grid-template-columns: 1fr; } }
        .rmbz-ov-top { background: #fff; border: 1px solid #e1e4e8; border-radius: 12px; padding: 0; box-shadow: 0 1px 3px rgba(0,0,0,0.04); overflow: hidden; }
        .rmbz-ov-top-head { padding: 14px 18px; background: #f7f7fb; border-bottom: 1px solid #e1e4e8; font-size: 12px; font-weight: 700; text-transform: uppercase; color: #1d2327; letter-spacing: 0.3px; }
        .rmbz-ov-top-list { padding: 0; margin: 0; list-style: none; }
        .rmbz-ov-top-list li { padding: 10px 18px; border-bottom: 1px solid #f0f0f1; display: flex; align-items: center; gap: 12px; font-size: 13px; }
        .rmbz-ov-top-list li:last-child { border-bottom: none; }
        .rmbz-ov-top-list .rank { width: 24px; height: 24px; background: #1d2327; color: #f0b90b; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 700; flex-shrink: 0; }
        .rmbz-ov-top-list .name { font-weight: 700; color: #1d2327; flex: 1; }
        .rmbz-ov-top-list .tel { color: #5f6368; font-size: 11px; font-variant-numeric: tabular-nums; }
        .rmbz-ov-top-list .val { font-weight: 700; color: #047857; font-variant-numeric: tabular-nums; }
        .rmbz-ov-top-list .val-orange { color: #9a3412; }
        .rmbz-ov-top-list .action { padding: 4px 10px; background: #1d2327; color: #f0b90b; text-decoration: none; border-radius: 6px; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; transition: 0.15s; }
        .rmbz-ov-top-list .action:hover { background: #2c2c34; color: #f0b90b; }
        .rmbz-ov-empty { padding: 30px 20px; text-align: center; color: #5f6368; font-style: italic; }

        /* Sistema info */
        .rmbz-ov-system { background: #1d2327; color: #e8e8e8; border-radius: 12px; padding: 18px 22px; }
        .rmbz-ov-system h4 { color: #f0b90b; font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; margin: 0 0 14px; }
        .rmbz-ov-sys-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; }
        .rmbz-ov-sys-item .label { font-size: 10px; text-transform: uppercase; color: #9ca3af; letter-spacing: 0.5px; margin-bottom: 3px; }
        .rmbz-ov-sys-item .value { font-size: 14px; font-weight: 700; color: #fff; font-variant-numeric: tabular-nums; }
        .rmbz-ov-sys-item .value .ok { color: #10b981; }
    </style>

    <div class="rmbz-overview-wrap">

        <!-- HEADER -->
        <div class="rmbz-ov-head">
            <div class="rmbz-ov-head-icon">📊</div>
            <div>
                <h1>Visão Geral da Plataforma</h1>
                <p>Resumo em tempo real de finanças, artistas, app e operações na 1MZ.</p>
            </div>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=rmbz-dashboard' ) ); ?>" class="rmbz-ov-refresh">🔄 Actualizar</a>
        </div>

        <!-- 🚨 ALERTAS URGENTES -->
        <?php if ( ! empty( $alertas ) ) : ?>
            <div class="rmbz-ov-alerts">
                <?php foreach ( $alertas as $a ) : ?>
                    <div class="rmbz-ov-alert <?php echo esc_attr( $a['level'] ); ?>">
                        <div class="icon"><?php echo esc_html( $a['icon'] ); ?></div>
                        <div class="body">
                            <div class="title"><?php echo esc_html( $a['title'] ); ?></div>
                            <div class="desc"><?php echo esc_html( $a['desc'] ); ?></div>
                        </div>
                        <?php if ( ! empty( $a['cta_url'] ) ) : ?>
                            <a href="<?php echo esc_url( $a['cta_url'] ); ?>" class="cta"><?php echo esc_html( $a['cta_label'] ); ?></a>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- 💰 FINANÇAS -->
        <div class="rmbz-ov-section-title"><span class="icon">💰</span> Finanças</div>
        <div class="rmbz-ov-grid">
            <div class="rmbz-ov-card green">
                <div class="label">📥 Depósitos Aprovados (total)</div>
                <div class="value"><?php echo number_format( (float) $fin->dep_total, 2, ',', '.' ); ?><span class="unit">MT</span></div>
                <div class="sub">Hoje: <strong><?php echo number_format( (float) $fin->dep_hoje, 2, ',', '.' ); ?> MT</strong> · 7d: <?php echo number_format( (float) $fin->dep_semana, 2, ',', '.' ); ?> MT</div>
            </div>
            <div class="rmbz-ov-card red">
                <div class="label">📤 Levantamentos Pagos (total)</div>
                <div class="value"><?php echo number_format( (float) $fin->withd_total, 2, ',', '.' ); ?><span class="unit">MT</span></div>
                <div class="sub">Hoje: <strong><?php echo number_format( (float) $fin->withd_hoje, 2, ',', '.' ); ?> MT</strong></div>
            </div>
            <div class="rmbz-ov-card gold">
                <div class="label">💼 Saldo Retido (Carteiras)</div>
                <div class="value"><?php echo number_format( (float) $fin->saldo_caixa, 2, ',', '.' ); ?><span class="unit">MT</span></div>
                <div class="sub">Soma dos saldos de artistas activos</div>
            </div>
            <div class="rmbz-ov-card <?php echo $receita_liquida >= 0 ? 'green' : 'red'; ?>">
                <div class="label">💎 Receita Líquida</div>
                <div class="value"><?php echo number_format( $receita_liquida, 2, ',', '.' ); ?><span class="unit">MT</span></div>
                <div class="sub">Depósitos − Levantamentos</div>
            </div>
            <div class="rmbz-ov-card orange">
                <div class="label">⏳ Depósitos Pendentes</div>
                <div class="value"><?php echo (int) $fin->dep_pendente_cnt; ?></div>
                <div class="sub"><?php echo number_format( (float) $fin->dep_pendente_valor, 2, ',', '.' ); ?> MT a aprovar</div>
            </div>
            <div class="rmbz-ov-card orange">
                <div class="label">⏳ Levantamentos Pendentes</div>
                <div class="value"><?php echo (int) $fin->withd_pendente_cnt; ?></div>
                <div class="sub"><?php echo number_format( (float) $fin->withd_pendente_valor, 2, ',', '.' ); ?> MT a pagar</div>
            </div>
            <div class="rmbz-ov-card blue">
                <div class="label">🎬 Receita Produções (Vídeo)</div>
                <div class="value"><?php echo number_format( (float) $fin->receita_projetos, 2, ',', '.' ); ?><span class="unit">MT</span></div>
                <div class="sub">Total pago por videoclipes</div>
            </div>
            <?php if ( $top_vip_pkg && (int) $top_vip_pkg->cnt > 0 ) : ?>
            <div class="rmbz-ov-card purple">
                <div class="label">⭐ Subscrições VIP (30 dias)</div>
                <div class="value"><?php echo number_format( (int) $top_vip_pkg->cnt, 0, ',', '.' ); ?></div>
                <div class="sub"><?php echo number_format( (float) $top_vip_pkg->receita, 2, ',', '.' ); ?> MT em receita</div>
            </div>
            <?php endif; ?>
        </div>

        <!-- 👥 ARTISTAS -->
        <div class="rmbz-ov-section-title"><span class="icon">👥</span> Artistas</div>
        <div class="rmbz-ov-grid">
            <div class="rmbz-ov-card blue">
                <div class="label">Total Activos</div>
                <div class="value"><?php echo number_format( (int) $artists->ativos, 0, ',', '.' ); ?></div>
                <div class="sub"><?php echo (int) $artists->total; ?> registados (<?php echo (int) $artists->lixeira; ?> na lixeira)</div>
            </div>
            <div class="rmbz-ov-card gold">
                <div class="label">💎 VIPs Activos</div>
                <div class="value"><?php echo number_format( $total_vips, 0, ',', '.' ); ?></div>
                <div class="sub"><?php echo $artists->ativos > 0 ? round( ( $total_vips / $artists->ativos ) * 100 ) : 0; ?>% do total</div>
            </div>
            <div class="rmbz-ov-card green">
                <div class="label">🟢 Online Agora</div>
                <div class="value"><?php echo number_format( $online_now, 0, ',', '.' ); ?></div>
                <div class="sub">Última actividade &lt; 5 min</div>
            </div>
            <div class="rmbz-ov-card purple">
                <div class="label">✨ Novos (7 dias)</div>
                <div class="value"><?php echo number_format( $novos_7d, 0, ',', '.' ); ?></div>
                <div class="sub"><?php echo $novos_30d; ?> nos últimos 30 dias</div>
            </div>
            <div class="rmbz-ov-card red">
                <div class="label">⛔ Banidos</div>
                <div class="value"><?php echo number_format( (int) $artists->banidos, 0, ',', '.' ); ?></div>
            </div>
            <div class="rmbz-ov-card orange">
                <div class="label">⚠ Contas Expiradas</div>
                <div class="value"><?php echo number_format( (int) $artists->expirados, 0, ',', '.' ); ?></div>
                <div class="sub">Soft delete pelo CRON</div>
            </div>
        </div>

        <!-- Breakdown origem -->
        <div class="rmbz-ov-breakdown">
            <h4>📲 Origem dos Registos</h4>
            <?php
            $tot_origem = (int) $origem->via_app + (int) $origem->via_site + (int) $origem->antigos;
            $pct = function( $n, $t ) { return $t > 0 ? round( ( $n / $t ) * 100 ) : 0; };
            ?>
            <div class="rmbz-ov-bd-row">
                <div class="rmbz-ov-bd-label">📱 Via App</div>
                <div class="rmbz-ov-bd-bar"><div class="rmbz-ov-bd-bar-fill app" style="width: <?php echo $pct( $origem->via_app, $tot_origem ); ?>%;"></div></div>
                <div class="rmbz-ov-bd-value"><?php echo (int) $origem->via_app; ?> (<?php echo $pct( $origem->via_app, $tot_origem ); ?>%)</div>
            </div>
            <div class="rmbz-ov-bd-row">
                <div class="rmbz-ov-bd-label">🌐 Via Site</div>
                <div class="rmbz-ov-bd-bar"><div class="rmbz-ov-bd-bar-fill site" style="width: <?php echo $pct( $origem->via_site, $tot_origem ); ?>%;"></div></div>
                <div class="rmbz-ov-bd-value"><?php echo (int) $origem->via_site; ?> (<?php echo $pct( $origem->via_site, $tot_origem ); ?>%)</div>
            </div>
            <div class="rmbz-ov-bd-row">
                <div class="rmbz-ov-bd-label">— Antigos</div>
                <div class="rmbz-ov-bd-bar"><div class="rmbz-ov-bd-bar-fill old" style="width: <?php echo $pct( $origem->antigos, $tot_origem ); ?>%;"></div></div>
                <div class="rmbz-ov-bd-value"><?php echo (int) $origem->antigos; ?> (<?php echo $pct( $origem->antigos, $tot_origem ); ?>%)</div>
            </div>
        </div>

        <!-- 📱 APP & DEVICES -->
        <div class="rmbz-ov-section-title"><span class="icon">📱</span> App &amp; Dispositivos</div>
        <div class="rmbz-ov-grid">
            <div class="rmbz-ov-card blue">
                <div class="label">📱 Devices Registados</div>
                <div class="value"><?php echo number_format( $devices_total, 0, ',', '.' ); ?></div>
                <div class="sub">Dispositivos únicos com app instalada</div>
            </div>
            <div class="rmbz-ov-card green">
                <div class="label">🔐 Sessões Activas</div>
                <div class="value"><?php echo number_format( $sessions_active, 0, ',', '.' ); ?></div>
                <div class="sub">Tokens de refresh válidos</div>
            </div>
            <div class="rmbz-ov-card gold">
                <div class="label">📬 Push Tokens</div>
                <div class="value"><?php echo number_format( $push_tokens, 0, ',', '.' ); ?></div>
                <div class="sub">Devices que recebem notificações</div>
            </div>
        </div>

        <?php if ( ! empty( $devices_versoes ) ) : ?>
        <div class="rmbz-ov-breakdown">
            <h4>📦 Versões da App em Uso</h4>
            <?php
            $tot_dev = array_sum( array_map( fn($d) => (int) $d->cnt, $devices_versoes ) );
            foreach ( $devices_versoes as $dv ) :
                $pct_v = $tot_dev > 0 ? round( ( $dv->cnt / $tot_dev ) * 100 ) : 0;
            ?>
                <div class="rmbz-ov-bd-row">
                    <div class="rmbz-ov-bd-label">v<?php echo esc_html( $dv->last_app_version ); ?></div>
                    <div class="rmbz-ov-bd-bar"><div class="rmbz-ov-bd-bar-fill gold" style="width: <?php echo $pct_v; ?>%;"></div></div>
                    <div class="rmbz-ov-bd-value"><?php echo (int) $dv->cnt; ?> (<?php echo $pct_v; ?>%)</div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- 🎵 CONTEÚDO -->
        <div class="rmbz-ov-section-title"><span class="icon">🎵</span> Conteúdo &amp; Produção</div>
        <div class="rmbz-ov-grid">
            <div class="rmbz-ov-card gold">
                <div class="label">🎵 Total Envios (Música + Vídeo)</div>
                <div class="value"><?php echo number_format( $envios_site + $envios_sociais, 0, ',', '.' ); ?></div>
                <div class="sub"><strong><?php echo $envios_site; ?></strong> site · <strong><?php echo $envios_sociais; ?></strong> redes</div>
            </div>
            <div class="rmbz-ov-card red">
                <div class="label">⏳ Fila de Moderação</div>
                <div class="value"><?php echo number_format( $envios_pendentes, 0, ',', '.' ); ?></div>
                <div class="sub"><?php echo $envios_publicados; ?> já publicados</div>
            </div>
            <div class="rmbz-ov-card green">
                <div class="label">🎬 Projetos de Vídeo</div>
                <div class="value"><?php echo number_format( $projetos_abertos, 0, ',', '.' ); ?></div>
                <div class="sub">Abertos (<strong><?php echo $projetos_concluidos; ?></strong> finalizados)</div>
            </div>
            <?php if ( $distro->total > 0 ) : ?>
            <div class="rmbz-ov-card purple">
                <div class="label">🌍 Distribuição Digital</div>
                <div class="value"><?php echo number_format( $distro->total, 0, ',', '.' ); ?></div>
                <div class="sub"><strong><?php echo $distro->pendentes; ?></strong> pendentes · <strong><?php echo $distro->live; ?></strong> live</div>
            </div>
            <?php endif; ?>
        </div>

        <!-- 🏆 TOP ARTISTAS + TOP DEPOSITANTES -->
        <div class="rmbz-ov-section-title"><span class="icon">🏆</span> Rankings</div>
        <div class="rmbz-ov-tops">

            <div class="rmbz-ov-top">
                <div class="rmbz-ov-top-head">🎵 Top 5 Artistas (mais envios)</div>
                <?php if ( empty( $top_artists ) ) : ?>
                    <div class="rmbz-ov-empty">Sem dados ainda.</div>
                <?php else : ?>
                    <ol class="rmbz-ov-top-list">
                        <?php $pos = 1; foreach ( $top_artists as $a ) : ?>
                            <li>
                                <span class="rank"><?php echo $pos; ?></span>
                                <div style="flex:1;">
                                    <div class="name"><?php echo esc_html( $a->user_nome ?: '(sem nome)' ); ?></div>
                                    <div class="tel"><?php echo esc_html( $a->artist_telemovel ); ?></div>
                                </div>
                                <span class="val val-orange"><?php echo (int) $a->total_envios; ?> envios</span>
                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=rmbz-historico-utilizador&user_id=' . urlencode( $a->artist_telemovel ) ) ); ?>" class="action">Ver</a>
                            </li>
                        <?php $pos++; endforeach; ?>
                    </ol>
                <?php endif; ?>
            </div>

            <div class="rmbz-ov-top">
                <div class="rmbz-ov-top-head">💰 Top 5 Depositantes (total pago)</div>
                <?php if ( empty( $top_depositantes ) ) : ?>
                    <div class="rmbz-ov-empty">Sem dados ainda.</div>
                <?php else : ?>
                    <ol class="rmbz-ov-top-list">
                        <?php $pos = 1; foreach ( $top_depositantes as $d ) : ?>
                            <li>
                                <span class="rank"><?php echo $pos; ?></span>
                                <div style="flex:1;">
                                    <div class="name"><?php echo esc_html( $d->user_nome ?: '(sem nome)' ); ?></div>
                                    <div class="tel"><?php echo esc_html( $d->user_telemovel ); ?> · <?php echo (int) $d->dep_cnt; ?> dep.</div>
                                </div>
                                <span class="val"><?php echo number_format( (float) $d->total_dep, 0, ',', '.' ); ?> MT</span>
                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=rmbz-historico-utilizador&user_id=' . urlencode( $d->user_telemovel ) ) ); ?>" class="action">Ver</a>
                            </li>
                        <?php $pos++; endforeach; ?>
                    </ol>
                <?php endif; ?>
            </div>

        </div>

        <!-- ⚙ SISTEMA -->
        <div class="rmbz-ov-section-title"><span class="icon">⚙</span> Sistema</div>
        <div class="rmbz-ov-system">
            <h4>Configuração da Plataforma</h4>
            <div class="rmbz-ov-sys-grid">
                <div class="rmbz-ov-sys-item">
                    <div class="label">DB Version</div>
                    <div class="value"><?php echo esc_html( $db_version ); ?></div>
                </div>
                <div class="rmbz-ov-sys-item">
                    <div class="label">App Min Version</div>
                    <div class="value">code <?php echo (int) $min_app_version; ?></div>
                </div>
                <div class="rmbz-ov-sys-item">
                    <div class="label">App Latest Version</div>
                    <div class="value">code <?php echo (int) $latest_app_version; ?></div>
                </div>
                <div class="rmbz-ov-sys-item">
                    <div class="label">Pacotes VIP Activos</div>
                    <div class="value"><?php echo count( $vip_packages ); ?></div>
                </div>
                <div class="rmbz-ov-sys-item">
                    <div class="label">Taxa Câmbio USD→MT</div>
                    <div class="value"><?php echo number_format( $exchange_rate, 2, ',', '.' ); ?></div>
                </div>
                <div class="rmbz-ov-sys-item">
                    <div class="label">Anúncios App Activos</div>
                    <div class="value"><?php echo (int) $announcements_active; ?></div>
                </div>
                <div class="rmbz-ov-sys-item">
                    <div class="label">Blacklist Convites</div>
                    <div class="value"><?php echo $referral_blacklist_cnt; ?> users</div>
                </div>
                <div class="rmbz-ov-sys-item">
                    <div class="label">Timezone WP</div>
                    <div class="value"><?php echo esc_html( wp_timezone_string() ); ?></div>
                </div>
            </div>
        </div>

    </div>
    <?php
}
