<?php
/**
 * Visao Geral da Plataforma.
 *
 * Consolida operações, financas e as antigas Estatisticas da Plataforma numa
 * unica dashboard administrativa, sem dependencias externas no navegador.
 */

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

function rmbz_admin_overview_table_exists( $table ) {
    global $wpdb;
    return $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table;
}

function rmbz_admin_overview_period() {
    $key = sanitize_key( wp_unslash( $_GET['period'] ?? '30d' ) );
    if ( ! in_array( $key, [ '7d', '30d', '90d', 'all', 'custom' ], true ) ) $key = '30d';

    $timezone = wp_timezone();
    $today = new DateTimeImmutable( 'today', $timezone );
    $to = $today;
    $from = null;
    $labels = [
        '7d'  => 'Últimos 7 dias',
        '30d' => 'Últimos 30 dias',
        '90d' => 'Últimos 90 dias',
        'all' => 'Todo o histórico',
    ];

    if ( $key === '7d' ) $from = $today->modify( '-6 days' );
    if ( $key === '30d' ) $from = $today->modify( '-29 days' );
    if ( $key === '90d' ) $from = $today->modify( '-89 days' );

    if ( $key === 'custom' ) {
        $raw_from = sanitize_text_field( wp_unslash( $_GET['date_from'] ?? '' ) );
        $raw_to = sanitize_text_field( wp_unslash( $_GET['date_to'] ?? '' ) );
        $custom_from = DateTimeImmutable::createFromFormat( '!Y-m-d', $raw_from, $timezone );
        $custom_to = DateTimeImmutable::createFromFormat( '!Y-m-d', $raw_to, $timezone );
        if ( ! $custom_from || ! $custom_to || $custom_from->format( 'Y-m-d' ) !== $raw_from || $custom_to->format( 'Y-m-d' ) !== $raw_to ) {
            $key = '30d';
            $from = $today->modify( '-29 days' );
        } else {
            if ( $custom_from > $custom_to ) [ $custom_from, $custom_to ] = [ $custom_to, $custom_from ];
            if ( $custom_to > $today ) $custom_to = $today;
            if ( $custom_from > $custom_to ) $custom_from = $custom_to;
            $from = $custom_from;
            $to = $custom_to;
            $labels['custom'] = wp_date( 'd/m/Y', $from->getTimestamp(), $timezone ) . ' a ' . wp_date( 'd/m/Y', $to->getTimestamp(), $timezone );
        }
    }

    return [
        'key'      => $key,
        'from'     => $from ? $from->format( 'Y-m-d' ) : '',
        'to'       => $to->format( 'Y-m-d' ),
        'label'    => $labels[ $key ] ?? $labels['30d'],
        'filtered' => $key !== 'all',
    ];
}

function rmbz_admin_overview_date_clause( $column, array $period ) {
    global $wpdb;
    if ( ! $period['filtered'] || ! preg_match( '/^[A-Za-z0-9_.]+$/', $column ) ) return '';
    return $wpdb->prepare( " AND {$column} >= %s AND {$column} < DATE_ADD(%s, INTERVAL 1 DAY)", $period['from'], $period['to'] );
}

function rmbz_admin_overview_icon( $name ) {
    $paths = [
        'dashboard' => '<path d="M4 4h6v6H4zM14 4h6v10h-6zM4 14h6v6H4zM14 18h6v2h-6z"/>',
        'download'  => '<path d="M12 3v11m0 0 4-4m-4 4-4-4M5 19h14"/>',
        'play'      => '<path d="M8 5v14l11-7z"/>',
        'payments'  => '<path d="M4 6h16v12H4zM8 10h8M8 14h5"/>',
        'sales'     => '<path d="M5 4h14l1 6-8 10-8-8zM9 8h.01"/>',
        'campaign'  => '<path d="M4 10v4h4l7 4V6l-7 4zm11 0h3a2 2 0 0 1 0 4h-3"/>',
        'groups'    => '<path d="M8 12a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm8-1a2.5 2.5 0 1 0 0-5M3 19c0-3 2-5 5-5s5 2 5 5m1-5c3 0 5 2 5 5"/>',
        'wallet'    => '<path d="M4 6h15v13H4zM4 9h15M15 13h4v3h-4z"/>',
        'music'     => '<path d="M9 18V6l10-2v12M9 9l10-2M6.5 21A2.5 2.5 0 1 0 6.5 16 2.5 2.5 0 0 0 6.5 21zm10-2A2.5 2.5 0 1 0 16.5 14a2.5 2.5 0 0 0 0 5z"/>',
        'phone'     => '<path d="M7 2h10v20H7zM10 5h4M11 19h2"/>',
        'public'    => '<path d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm0 0c2.5-2.4 3.5-5.4 3.5-9S14.5 5.4 12 3m0 18c-2.5-2.4-3.5-5.4-3.5-9S9.5 5.4 12 3M3 12h18"/>',
        'warning'   => '<path d="M12 3 2.5 20h19zM12 9v5m0 3h.01"/>',
        'clock'     => '<path d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm0-13v5l3 2"/>',
        'report'    => '<path d="M5 3h14v18H5zM8 8h8M8 12h8M8 16h5"/>',
        'shield'    => '<path d="M12 3 5 6v5c0 4.7 2.8 8 7 10 4.2-2 7-5.3 7-10V6zM9 12l2 2 4-4"/>',
        'refresh'   => '<path d="M20 7v5h-5M4 17v-5h5m9.5-3A7 7 0 0 0 6 7m0 10a7 7 0 0 0 12.5-2"/>',
        'open'      => '<path d="M14 4h6v6M20 4l-9 9M18 13v7H4V6h7"/>',
        'back'      => '<path d="M20 12H5m0 0 6-6m-6 6 6 6"/>',
    ];
    $path = $paths[ $name ] ?? $paths['dashboard'];
    return '<svg class="rmbz-po-svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false">' . $path . '</svg>';
}

function rmbz_admin_overview_metric( $label, $value, $detail, $icon, $tone = 'neutral', $url = '' ) {
    $tag = $url ? 'a' : 'article';
    $href = $url ? ' href="' . esc_url( $url ) . '"' : '';
    echo '<' . $tag . $href . ' class="rmbz-po-metric tone-' . esc_attr( $tone ) . '">';
    echo '<span class="rmbz-po-tonal">' . rmbz_admin_overview_icon( $icon ) . '</span>';
    echo '<div class="rmbz-po-metric-copy"><small>' . esc_html( $label ) . '</small><strong>' . wp_kses_post( $value ) . '</strong><span>' . wp_kses_post( $detail ) . '</span></div>';
    if ( $url ) echo '<span class="rmbz-po-card-open">' . rmbz_admin_overview_icon( 'open' ) . '</span>';
    echo '</' . $tag . '>';
}

function rmbz_admin_overview_chart_points( array $values, $width = 1000, $height = 250 ) {
    $count = count( $values );
    if ( ! $count ) return '';
    $max = max( 1, max( $values ) );
    $left = 28;
    $right = $width - 22;
    $top = 20;
    $bottom = $height - 28;
    $usable_x = $right - $left;
    $usable_y = $bottom - $top;
    $points = [];
    foreach ( array_values( $values ) as $index => $value ) {
        $x = $count === 1 ? ( $left + $right ) / 2 : $left + ( $index / ( $count - 1 ) ) * $usable_x;
        $y = $bottom - ( (float) $value / $max ) * $usable_y;
        $points[] = round( $x, 2 ) . ',' . round( $y, 2 );
    }
    return implode( ' ', $points );
}

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.' );

    $view = sanitize_key( wp_unslash( (string) ( $_GET['view'] ?? '' ) ) );
    if ( $view === 'download-logs' && function_exists( 'rmbz_render_admin_download_logs_page' ) ) {
        rmbz_render_admin_download_logs_page();
        return;
    }

    global $wpdb;
    $period = rmbz_admin_overview_period();
    $tables = [
        'wallets'       => $wpdb->prefix . 'rmbz_wallets',
        'subscriptions' => $wpdb->prefix . 'rmbz_subscriptions',
        'deposits'      => $wpdb->prefix . 'rmbz_deposit_requests',
        'withdrawals'   => $wpdb->prefix . 'rmbz_withdrawal_requests',
        'submissions'   => $wpdb->prefix . 'rmbz_artist_submissions',
        'projects'      => $wpdb->prefix . 'rmbz_artist_projects',
        'devices'       => $wpdb->prefix . 'rmbz_app_devices',
        'tokens'        => $wpdb->prefix . 'rmbz_api_refresh_tokens',
        'push'          => $wpdb->prefix . 'rmbz_app_push_tokens',
        'announcements' => $wpdb->prefix . 'rmbz_app_announcements',
        'releases'      => $wpdb->prefix . 'rmbz_distro_releases',
        'analytics'     => $wpdb->prefix . 'imz_analytics',
        'plays'         => $wpdb->prefix . 'imz_plays',
        'purchases'     => $wpdb->prefix . 'imz_purchases',
        'reports'       => $wpdb->prefix . 'imz_reports',
        'ads'           => $wpdb->prefix . 'imz_ad_stats',
        'dm_events'     => $wpdb->prefix . 'rmbz_download_earnings',
        'dm_enroll'     => $wpdb->prefix . 'rmbz_download_monetization',
        'dm_settlements'=> $wpdb->prefix . 'rmbz_download_settlements',
    ];
    $has = [];
    foreach ( $tables as $key => $table ) $has[ $key ] = rmbz_admin_overview_table_exists( $table );

    $number = static function( $value ) { return number_format_i18n( (float) $value, 0 ); };
    $money = static function( $value ) { return number_format_i18n( (float) $value, 2 ) . ' MT'; };

    $dl_where = rmbz_admin_overview_date_clause( 'download_date', $period );
    $pl_where = rmbz_admin_overview_date_clause( 'play_date', $period );
    $purchase_where = rmbz_admin_overview_date_clause( 'date', $period );
    $ad_where = rmbz_admin_overview_date_clause( 'event_date', $period );
    $dep_where = rmbz_admin_overview_date_clause( 'processed_date', $period );
    $withd_where = rmbz_admin_overview_date_clause( 'processed_date', $period );
    $submission_where = rmbz_admin_overview_date_clause( 'submission_date', $period );
    $project_where = rmbz_admin_overview_date_clause( 'contract_date', $period );
    $boost_where = rmbz_admin_overview_date_clause( 'post_date', $period );
    $dm_event_where = rmbz_admin_overview_date_clause( 'occurred_at', $period );

    $downloads = $has['analytics'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['analytics']} WHERE 1=1 {$dl_where}" ) : 0;
    $plays = $has['plays'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['plays']} WHERE 1=1 {$pl_where}" ) : 0;
    $sales = $has['purchases'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['purchases']} WHERE status='usado' {$purchase_where}" ) : 0;
    $sales_revenue = $has['purchases'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(price),0) FROM {$tables['purchases']} WHERE status='usado' {$purchase_where}" ) : 0;
    $reports_open = $has['reports'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['reports']} WHERE status='novo'" ) : 0;
    $ad_impressions = $has['ads'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['ads']} WHERE event_type='impression' {$ad_where}" ) : 0;
    $ad_clicks = $has['ads'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['ads']} WHERE event_type='click' {$ad_where}" ) : 0;
    $ad_ctr = $ad_impressions ? round( ( $ad_clicks / $ad_impressions ) * 100, 1 ) : 0;

    $published_music = (int) $wpdb->get_var(
        "SELECT COUNT(DISTINCT p.ID) FROM {$wpdb->posts} p LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id=p.ID AND pm.meta_key='_imz_nao_e_musica' WHERE p.post_type='post' AND p.post_status='publish' AND (pm.meta_value IS NULL OR pm.meta_value!='1')"
    );
    $boosts = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type='impulsionamento' AND post_status='publish' {$boost_where}" );

    $dep_approved = $has['deposits'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount),0) FROM {$tables['deposits']} WHERE status='aprovado' {$dep_where}" ) : 0;
    $dep_approved_count = $has['deposits'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['deposits']} WHERE status='aprovado' {$dep_where}" ) : 0;
    $dep_pending = $has['deposits'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['deposits']} WHERE status='pendente'" ) : 0;
    $dep_pending_amount = $has['deposits'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount),0) FROM {$tables['deposits']} WHERE status='pendente'" ) : 0;
    $withd_approved = $has['withdrawals'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount),0) FROM {$tables['withdrawals']} WHERE status='aprovado' {$withd_where}" ) : 0;
    $withd_approved_count = $has['withdrawals'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['withdrawals']} WHERE status='aprovado' {$withd_where}" ) : 0;
    $withd_pending = $has['withdrawals'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['withdrawals']} WHERE status='pendente'" ) : 0;
    $withd_pending_amount = $has['withdrawals'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount),0) FROM {$tables['withdrawals']} WHERE status='pendente'" ) : 0;
    $wallet_balance = $has['wallets'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(balance),0) FROM {$tables['wallets']} WHERE extra_data NOT LIKE '%\"deleted_at\"%' OR extra_data IS NULL" ) : 0;
    $project_revenue = $has['projects'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount_paid),0) FROM {$tables['projects']} WHERE 1=1 {$project_where}" ) : 0;
    $net_flow = $dep_approved - $withd_approved;

    $dm_paid = $has['dm_events'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount),0) FROM {$tables['dm_events']} WHERE status='paid' {$dm_event_where}" ) : 0;
    $dm_pending = $has['dm_events'] ? (float) $wpdb->get_var( "SELECT COALESCE(SUM(amount),0) FROM {$tables['dm_events']} WHERE status IN ('pending','processing')" ) : 0;
    $dm_active = $has['dm_enroll'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['dm_enroll']} WHERE status='active'" ) : 0;
    $dm_failed = $has['dm_settlements'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['dm_settlements']} WHERE status='failed'" ) : 0;

    $artist_stats = (object) [ 'total' => 0, 'active' => 0, 'banned' => 0, 'trash' => 0 ];
    $online_now = 0;
    if ( $has['wallets'] ) {
        $artist_stats = $wpdb->get_row(
            "SELECT COUNT(*) total,
             SUM(CASE WHEN extra_data NOT LIKE '%\"deleted_at\"%' OR extra_data IS NULL THEN 1 ELSE 0 END) active,
             SUM(CASE WHEN is_banned=1 AND (extra_data NOT LIKE '%\"deleted_at\"%' OR extra_data IS NULL) THEN 1 ELSE 0 END) banned,
             SUM(CASE WHEN extra_data LIKE '%\"deleted_at\"%' THEN 1 ELSE 0 END) trash
             FROM {$tables['wallets']}"
        );
        $last_seen_rows = $wpdb->get_col( "SELECT extra_data FROM {$tables['wallets']} WHERE extra_data LIKE '%last_seen%' AND (extra_data NOT LIKE '%\"deleted_at\"%' OR extra_data IS NULL)" );
        $online_cutoff = time() - 300;
        foreach ( $last_seen_rows as $extra_json ) {
            $extra = json_decode( $extra_json, true );
            if ( is_array( $extra ) && (int) ( $extra['last_seen'] ?? 0 ) > $online_cutoff ) $online_now++;
        }
    }
    $vip_active = $has['subscriptions'] ? (int) $wpdb->get_var( "SELECT COUNT(DISTINCT user_telemovel) FROM {$tables['subscriptions']} WHERE status='active' AND end_date>NOW()" ) : 0;
    $vip_expiring = $has['subscriptions'] ? (int) $wpdb->get_var( "SELECT COUNT(DISTINCT user_telemovel) FROM {$tables['subscriptions']} WHERE status='active' AND end_date>NOW() AND end_date<=NOW()+INTERVAL 48 HOUR" ) : 0;

    $submissions_period = $has['submissions'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['submissions']} WHERE 1=1 {$submission_where}" ) : 0;
    $submissions_pending = $has['submissions'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['submissions']} WHERE review_status='pendente'" ) : 0;
    $submissions_published = $has['submissions'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['submissions']} WHERE review_status IN ('publicado','aprovado')" ) : 0;
    $stale_submissions = $has['submissions'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['submissions']} WHERE review_status='pendente' AND submission_date<NOW()-INTERVAL 3 DAY" ) : 0;
    $projects_total = $has['projects'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['projects']}" ) : 0;
    $projects_done = $has['projects'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['projects']} WHERE production_status='done'" ) : 0;
    $projects_active = $has['projects'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['projects']} WHERE production_status NOT IN ('done','rejected','cancelled_deadline','cancelled_no_confirmation')" ) : 0;
    $releases_total = $has['releases'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['releases']}" ) : 0;
    $releases_live = $has['releases'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['releases']} WHERE status IN ('publicado','live')" ) : 0;
    $releases_pending = $has['releases'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['releases']} WHERE status IN ('pendente','em_revisao','enviado')" ) : 0;

    $devices = $has['devices'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['devices']}" ) : 0;
    $sessions = $has['tokens'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['tokens']} WHERE (revoked_at IS NULL OR revoked_at='') AND expires_at>NOW()" ) : 0;
    $push_tokens = $has['push'] ? (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$tables['push']}" ) : 0;
    $device_versions = $has['devices'] ? $wpdb->get_results( "SELECT last_app_version version,COUNT(*) total FROM {$tables['devices']} WHERE last_app_version IS NOT NULL AND last_app_version!='' GROUP BY last_app_version ORDER BY total DESC LIMIT 6" ) : [];
    $registration_origin = $has['deposits'] ? $wpdb->get_row(
        "SELECT SUM(CASE WHEN source_platform='app' THEN 1 ELSE 0 END) app,
         SUM(CASE WHEN source_platform='site' THEN 1 ELSE 0 END) site,
         SUM(CASE WHEN source_platform IS NULL OR source_platform='' THEN 1 ELSE 0 END) old
         FROM {$tables['deposits']} WHERE is_first_deposit=1"
    ) : (object) [ 'app' => 0, 'site' => 0, 'old' => 0 ];

    $chart_to = new DateTimeImmutable( $period['to'], wp_timezone() );
    $chart_from = $period['filtered'] ? new DateTimeImmutable( $period['from'], wp_timezone() ) : $chart_to->modify( '-89 days' );
    if ( $chart_from < $chart_to->modify( '-179 days' ) ) $chart_from = $chart_to->modify( '-179 days' );
    $chart_from_sql = $chart_from->format( 'Y-m-d' );
    $chart_to_sql = $chart_to->format( 'Y-m-d' );
    $download_daily = $has['analytics'] ? $wpdb->get_results( $wpdb->prepare( "SELECT DATE(download_date) day,COUNT(*) total FROM {$tables['analytics']} WHERE download_date>=%s AND download_date<DATE_ADD(%s,INTERVAL 1 DAY) GROUP BY DATE(download_date) ORDER BY day", $chart_from_sql, $chart_to_sql ) ) : [];
    $play_daily = $has['plays'] ? $wpdb->get_results( $wpdb->prepare( "SELECT DATE(play_date) day,COUNT(*) total FROM {$tables['plays']} WHERE play_date>=%s AND play_date<DATE_ADD(%s,INTERVAL 1 DAY) GROUP BY DATE(play_date) ORDER BY day", $chart_from_sql, $chart_to_sql ) ) : [];
    $download_map = [];
    $play_map = [];
    foreach ( $download_daily as $row ) $download_map[ $row->day ] = (int) $row->total;
    foreach ( $play_daily as $row ) $play_map[ $row->day ] = (int) $row->total;
    $chart_labels = [];
    $chart_downloads = [];
    $chart_plays = [];
    for ( $cursor = $chart_from; $cursor <= $chart_to; $cursor = $cursor->modify( '+1 day' ) ) {
        $key = $cursor->format( 'Y-m-d' );
        $chart_labels[] = $cursor->format( 'd/m' );
        $chart_downloads[] = $download_map[ $key ] ?? 0;
        $chart_plays[] = $play_map[ $key ] ?? 0;
    }
    $chart_max = max( 1, max( array_merge( $chart_downloads, $chart_plays, [ 1 ] ) ) );
    $download_points = rmbz_admin_overview_chart_points( $chart_downloads );
    $play_points = rmbz_admin_overview_chart_points( $chart_plays );
    $chart_label_indexes = array_values( array_unique( [ 0, (int) floor( ( count( $chart_labels ) - 1 ) / 2 ), max( 0, count( $chart_labels ) - 1 ) ] ) );

    $dl_alias_where = rmbz_admin_overview_date_clause( 'a.download_date', $period );
    $pl_alias_where = rmbz_admin_overview_date_clause( 'p.play_date', $period );
    $top_downloads = $has['analytics'] ? $wpdb->get_results( "SELECT a.music_id,COUNT(*) total FROM {$tables['analytics']} a WHERE 1=1 {$dl_alias_where} GROUP BY a.music_id ORDER BY total DESC LIMIT 7" ) : [];
    $top_plays = $has['plays'] ? $wpdb->get_results( "SELECT p.music_id,COUNT(*) total FROM {$tables['plays']} p WHERE 1=1 {$pl_alias_where} GROUP BY p.music_id ORDER BY total DESC LIMIT 7" ) : [];
    $top_regions = $has['analytics'] ? $wpdb->get_results( "SELECT region label,COUNT(*) total FROM {$tables['analytics']} a WHERE region!='' AND region!='N/A' {$dl_alias_where} GROUP BY region ORDER BY total DESC LIMIT 6" ) : [];
    $top_countries = $has['analytics'] ? $wpdb->get_results( "SELECT country label,COUNT(*) total FROM {$tables['analytics']} a WHERE country!='' {$dl_alias_where} GROUP BY country ORDER BY total DESC LIMIT 6" ) : [];

    $top_download_artists = [];
    if ( $has['analytics'] && function_exists( 'rmbz_art_tracks_native_tables' ) && function_exists( 'rmbz_art_tracks_native_ready' ) && rmbz_art_tracks_native_ready() ) {
        $art = rmbz_art_tracks_native_tables();
        $top_download_artists = $wpdb->get_results(
            "SELECT t.artist_name label,COUNT(*) total FROM {$tables['analytics']} a
             INNER JOIN {$art['catalog']} c ON c.site_post_id=a.music_id AND c.role='primary' AND c.publication_status='published'
             INNER JOIN {$art['tracks']} t ON t.id=c.art_track_id
             WHERE 1=1 {$dl_alias_where} GROUP BY t.id,t.artist_name ORDER BY total DESC LIMIT 6"
        );
    }
    $dep_alias_where = rmbz_admin_overview_date_clause( 'd.processed_date', $period );
    $top_depositors = ( $has['deposits'] && $has['wallets'] ) ? $wpdb->get_results(
        "SELECT COALESCE(w.user_nome,d.user_telemovel) label,SUM(d.amount) total FROM {$tables['deposits']} d LEFT JOIN {$tables['wallets']} w ON w.user_telemovel=d.user_telemovel WHERE d.status='aprovado' {$dep_alias_where} GROUP BY d.user_telemovel,w.user_nome ORDER BY total DESC LIMIT 6"
    ) : [];

    $alerts = [];
    if ( $dep_pending ) $alerts[] = [ 'tone'=>'warning', 'icon'=>'clock', 'title'=>$dep_pending . ' depósito(s) aguardam aprovação', 'detail'=>$money( $dep_pending_amount ) . ' pendentes', 'url'=>admin_url( 'admin.php?page=rmbz-depositos' ) ];
    if ( $withd_pending ) $alerts[] = [ 'tone'=>'danger', 'icon'=>'payments', 'title'=>$withd_pending . ' levantamento(s) aguardam pagamento', 'detail'=>$money( $withd_pending_amount ) . ' pendentes', 'url'=>admin_url( 'admin.php?page=rmbz-pedidos-levantamento' ) ];
    if ( $stale_submissions ) $alerts[] = [ 'tone'=>'warning', 'icon'=>'report', 'title'=>$stale_submissions . ' envio(s) sem revisão há mais de 3 dias', 'detail'=>'Rever a fila de moderacao', 'url'=>admin_url( 'admin.php?page=rmbz-envios-site' ) ];
    if ( $reports_open ) $alerts[] = [ 'tone'=>'danger', 'icon'=>'warning', 'title'=>$reports_open . ' problema(s) reportado(s)', 'detail'=>'Existem ocorrencias ainda abertas', 'url'=>admin_url( 'edit.php?post_type=impulsionamento&page=imz_reports_manager' ) ];
    if ( $dm_failed ) $alerts[] = [ 'tone'=>'danger', 'icon'=>'wallet', 'title'=>$dm_failed . ' liquidação(ões) de downloads falharam', 'detail'=>'Nenhum valor falhado foi marcado como pago', 'url'=>admin_url( 'edit.php?post_type=impulsionamento&page=rmbz-download-monetization' ) ];
    if ( $vip_expiring ) $alerts[] = [ 'tone'=>'info', 'icon'=>'groups', 'title'=>$vip_expiring . ' VIP(s) expiram nas próximas 48 horas', 'detail'=>'Acompanhar renovações', 'url'=>admin_url( 'admin.php?page=rmbz-pacotes' ) ];

    $origin_total = (int) $registration_origin->app + (int) $registration_origin->site + (int) $registration_origin->old;
    $origin_pct = static function( $value, $total ) { return $total ? round( ( $value / $total ) * 100 ) : 0; };
    $updated_at = wp_date( 'd/m/Y H:i', time(), wp_timezone() );
    ?>
    <style>
        .rmbz-platform-overview{--po-bg:#f6f7f3;--po-surface:#fff;--po-soft:#eef2ed;--po-line:#dce3dd;--po-ink:#18201c;--po-muted:#66716a;--po-primary:#08664b;--po-primary-soft:#dcefe7;--po-gold:#efb700;--po-blue:#315ea8;--po-danger:#b3261e;--po-warning:#8b5f00;max-width:none;margin:0 20px 0 2px;padding:26px 24px 70px;color:var(--po-ink);font-family:Inter,"Segoe UI",Roboto,sans-serif;background:var(--po-bg);min-height:100vh}.rmbz-platform-overview *{box-sizing:border-box}.rmbz-po-svg{width:22px;height:22px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}.rmbz-po-head{display:flex;justify-content:space-between;align-items:flex-start;gap:24px;margin-bottom:18px}.rmbz-po-kicker{display:flex;align-items:center;gap:8px;color:var(--po-primary);font-size:12px;font-weight:800;letter-spacing:.08em;text-transform:uppercase}.rmbz-po-kicker .rmbz-po-svg{width:18px}.rmbz-po-head h1{font-size:32px;line-height:1.08;letter-spacing:-.035em;margin:8px 0 7px}.rmbz-po-head p{margin:0;color:var(--po-muted);font-size:14px}.rmbz-po-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.rmbz-po-button{min-height:42px;display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:0 16px;border:1px solid var(--po-line);border-radius:999px;background:var(--po-surface);color:var(--po-ink);text-decoration:none;font-size:13px;font-weight:750}.rmbz-po-button.primary{background:var(--po-primary);border-color:var(--po-primary);color:#fff}.rmbz-po-button .rmbz-po-svg{width:17px;height:17px}.rmbz-po-nav{display:flex;gap:5px;overflow-x:auto;padding:5px;background:#e8ece7;border-radius:999px;margin-bottom:18px;scrollbar-width:none}.rmbz-po-nav a{white-space:nowrap;padding:9px 14px;border-radius:999px;color:#445049;text-decoration:none;font-size:13px;font-weight:700}.rmbz-po-nav a:first-child{background:#fff;color:var(--po-primary);box-shadow:0 1px 3px rgba(0,0,0,.06)}.rmbz-po-filter{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:14px;padding:16px;border:1px solid var(--po-line);border-radius:22px;background:var(--po-surface);margin-bottom:16px}.rmbz-po-presets{display:flex;gap:7px;align-items:center;flex-wrap:wrap}.rmbz-po-preset{padding:9px 13px;border:1px solid var(--po-line);border-radius:999px;color:var(--po-muted);text-decoration:none;font-size:13px;font-weight:750}.rmbz-po-preset.active{background:var(--po-primary-soft);border-color:#a6cdbd;color:var(--po-primary)}.rmbz-po-custom{display:flex;align-items:center;gap:7px}.rmbz-po-custom input{min-height:39px;border:1px solid var(--po-line);border-radius:11px;background:var(--po-soft);box-shadow:none;padding:0 10px}.rmbz-po-custom button{min-height:39px;border:0;border-radius:999px;padding:0 14px;background:var(--po-ink);color:#fff;font-weight:750;cursor:pointer}.rmbz-po-hero{position:relative;overflow:hidden;display:grid;grid-template-columns:minmax(0,1.35fr) minmax(280px,.65fr);gap:22px;padding:28px;border-radius:28px;background:linear-gradient(135deg,#183447,#173e32 65%,#466026);color:#fff;box-shadow:0 14px 38px rgba(26,49,41,.13);margin-bottom:18px}.rmbz-po-hero:after{content:"";position:absolute;width:260px;height:260px;right:-80px;top:-130px;border-radius:50%;background:rgba(239,183,0,.18)}.rmbz-po-hero-copy{position:relative;z-index:1}.rmbz-po-hero-copy small{font-size:12px;font-weight:800;letter-spacing:.09em;color:#bbd4ca}.rmbz-po-hero-copy h2{font-size:27px;line-height:1.18;margin:9px 0 8px;color:#fff}.rmbz-po-hero-copy p{max-width:760px;margin:0;color:#c9d9d2;font-size:14px}.rmbz-po-hero-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:9px;margin-top:22px}.rmbz-po-hero-stat{padding:12px 14px;border:1px solid rgba(255,255,255,.13);border-radius:16px;background:rgba(255,255,255,.07)}.rmbz-po-hero-stat span,.rmbz-po-hero-stat strong{display:block}.rmbz-po-hero-stat span{font-size:11px;color:#bcd0c8;text-transform:uppercase;font-weight:750}.rmbz-po-hero-stat strong{font-size:20px;margin-top:5px}.rmbz-po-status{position:relative;z-index:1;align-self:stretch;padding:18px;border:1px solid rgba(255,255,255,.14);border-radius:20px;background:rgba(10,20,17,.2);display:flex;flex-direction:column;justify-content:center}.rmbz-po-status-icon{width:48px;height:48px;border-radius:16px;display:grid;place-items:center;background:#dff3e9;color:#08664b}.rmbz-po-status h3{color:#fff;margin:13px 0 4px;font-size:18px}.rmbz-po-status p{color:#bfd1c9;margin:0;font-size:12px}.rmbz-po-alerts{display:grid;gap:8px;margin:18px 0}.rmbz-po-alert{display:grid;grid-template-columns:42px minmax(0,1fr) auto;align-items:center;gap:12px;padding:12px 14px;border:1px solid var(--po-line);border-radius:16px;background:#fff;color:inherit;text-decoration:none}.rmbz-po-alert-icon{width:40px;height:40px;border-radius:13px;display:grid;place-items:center;background:var(--po-soft);color:var(--po-primary)}.rmbz-po-alert.warning .rmbz-po-alert-icon{background:#fff2cc;color:var(--po-warning)}.rmbz-po-alert.danger .rmbz-po-alert-icon{background:#ffdad6;color:var(--po-danger)}.rmbz-po-alert-copy strong,.rmbz-po-alert-copy span{display:block}.rmbz-po-alert-copy strong{font-size:14px}.rmbz-po-alert-copy span{font-size:12px;color:var(--po-muted);margin-top:2px}.rmbz-po-alert-open{font-size:12px;font-weight:750;color:var(--po-primary)}.rmbz-po-section{scroll-margin-top:42px;margin-top:24px}.rmbz-po-section-head{display:flex;justify-content:space-between;align-items:end;gap:16px;margin:0 0 12px}.rmbz-po-section-head h2{font-size:20px;letter-spacing:-.02em;margin:0}.rmbz-po-section-head p{margin:4px 0 0;color:var(--po-muted);font-size:13px}.rmbz-po-chip{padding:7px 10px;border-radius:999px;background:#ece8d8;color:#6d5700;font-size:11px;font-weight:800}.rmbz-po-metrics{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:11px}.rmbz-po-metric{position:relative;min-width:0;display:flex;align-items:flex-start;gap:13px;padding:17px;border:1px solid var(--po-line);border-radius:20px;background:var(--po-surface);color:inherit;text-decoration:none;transition:.16s}.rmbz-po-metric:hover{border-color:#aab8b0;transform:translateY(-1px);box-shadow:0 7px 18px rgba(24,32,28,.05)}.rmbz-po-tonal{width:43px;height:43px;display:grid;place-items:center;border-radius:14px;background:var(--po-soft);color:var(--po-primary);flex:0 0 auto}.rmbz-po-metric.tone-green .rmbz-po-tonal{background:#dcefe7;color:#08664b}.rmbz-po-metric.tone-gold .rmbz-po-tonal{background:#fff0bd;color:#7a5b00}.rmbz-po-metric.tone-blue .rmbz-po-tonal{background:#dce5f8;color:#315ea8}.rmbz-po-metric.tone-red .rmbz-po-tonal{background:#ffdad6;color:#b3261e}.rmbz-po-metric-copy{min-width:0}.rmbz-po-metric-copy small,.rmbz-po-metric-copy strong,.rmbz-po-metric-copy span{display:block}.rmbz-po-metric-copy small{font-size:10px;letter-spacing:.055em;color:var(--po-muted);font-weight:800;text-transform:uppercase}.rmbz-po-metric-copy strong{font-size:26px;line-height:1.15;margin-top:6px;letter-spacing:-.025em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.rmbz-po-metric-copy span{margin-top:5px;color:var(--po-muted);font-size:12px}.rmbz-po-card-open{position:absolute;right:13px;top:13px;color:#8b958f}.rmbz-po-card-open .rmbz-po-svg{width:15px;height:15px}.rmbz-po-activity{display:grid;grid-template-columns:minmax(0,1.55fr) minmax(290px,.45fr);gap:12px}.rmbz-po-panel{border:1px solid var(--po-line);border-radius:22px;background:var(--po-surface);overflow:hidden}.rmbz-po-panel-head{display:flex;justify-content:space-between;align-items:flex-start;gap:14px;padding:17px 18px;border-bottom:1px solid var(--po-line)}.rmbz-po-panel-head h3{font-size:16px;margin:0}.rmbz-po-panel-head p{font-size:12px;color:var(--po-muted);margin:3px 0 0}.rmbz-po-legend{display:flex;gap:12px;font-size:11px;font-weight:750;color:var(--po-muted)}.rmbz-po-legend span{display:flex;align-items:center;gap:5px}.rmbz-po-dot{width:8px;height:8px;border-radius:50%}.rmbz-po-dot.downloads{background:#0b8f67}.rmbz-po-dot.plays{background:#315ea8}.rmbz-po-chart{padding:8px 13px 14px}.rmbz-po-chart svg{display:block;width:100%;height:270px}.rmbz-po-chart-grid{stroke:#e2e7e3;stroke-width:1}.rmbz-po-chart-downloads{fill:none;stroke:#0b8f67;stroke-width:3;stroke-linecap:round;stroke-linejoin:round}.rmbz-po-chart-plays{fill:none;stroke:#315ea8;stroke-width:3;stroke-linecap:round;stroke-linejoin:round}.rmbz-po-chart text{font:12px "Segoe UI",sans-serif;fill:#7b8580}.rmbz-po-now{display:grid;gap:8px;padding:14px}.rmbz-po-now-item{display:flex;justify-content:space-between;gap:10px;padding:13px;border-radius:15px;background:var(--po-soft)}.rmbz-po-now-item span{font-size:12px;color:var(--po-muted)}.rmbz-po-now-item strong{font-size:17px}.rmbz-po-rank-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.rmbz-po-rank-list{list-style:none;padding:0;margin:0}.rmbz-po-rank-list li{display:grid;grid-template-columns:31px minmax(0,1fr) auto;gap:10px;align-items:center;padding:11px 17px;border-bottom:1px solid #edf0ed}.rmbz-po-rank-list li:last-child{border-bottom:0}.rmbz-po-rank{width:27px;height:27px;border-radius:10px;display:grid;place-items:center;background:var(--po-soft);color:var(--po-primary);font-size:10px;font-weight:850}.rmbz-po-rank-name{min-width:0;font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.rmbz-po-rank-value{font-size:12px;font-weight:800;color:var(--po-primary);white-space:nowrap}.rmbz-po-empty{padding:28px;text-align:center;color:var(--po-muted);font-size:13px}.rmbz-po-three{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.rmbz-po-progress-list{padding:8px 17px 15px}.rmbz-po-progress{display:grid;grid-template-columns:minmax(90px,.55fr) minmax(100px,1fr) auto;gap:10px;align-items:center;padding:8px 0}.rmbz-po-progress label{font-size:12px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.rmbz-po-progress-track{height:8px;border-radius:999px;background:var(--po-soft);overflow:hidden}.rmbz-po-progress-fill{height:100%;border-radius:inherit;background:linear-gradient(90deg,var(--po-primary),#45a27e)}.rmbz-po-progress-fill.gold{background:linear-gradient(90deg,#d9a900,#f2c94c)}.rmbz-po-progress b{font-size:11px;color:var(--po-muted)}.rmbz-po-system{display:grid;grid-template-columns:repeat(4,1fr);gap:1px;border:1px solid var(--po-line);border-radius:22px;overflow:hidden;background:var(--po-line)}.rmbz-po-system-item{padding:15px;background:#1d2924;color:#fff}.rmbz-po-system-item small,.rmbz-po-system-item strong{display:block}.rmbz-po-system-item small{font-size:10px;color:#aebdb6;text-transform:uppercase;font-weight:800;letter-spacing:.06em}.rmbz-po-system-item strong{font-size:14px;margin-top:6px}.rmbz-po-foot{margin-top:16px;text-align:center;color:var(--po-muted);font-size:11px}@media(max-width:1180px){.rmbz-po-metrics{grid-template-columns:1fr 1fr}.rmbz-po-activity,.rmbz-po-hero{grid-template-columns:1fr}.rmbz-po-three{grid-template-columns:1fr 1fr}.rmbz-po-system{grid-template-columns:1fr 1fr}}@media(max-width:782px){.rmbz-platform-overview{padding:18px 10px 55px;margin:0}.rmbz-po-head,.rmbz-po-filter,.rmbz-po-section-head{display:grid}.rmbz-po-actions{justify-content:flex-start}.rmbz-po-custom{flex-wrap:wrap}.rmbz-po-custom input{width:calc(50% - 4px)}.rmbz-po-hero{padding:21px;border-radius:22px}.rmbz-po-hero-stats,.rmbz-po-metrics,.rmbz-po-rank-grid,.rmbz-po-three,.rmbz-po-system{grid-template-columns:1fr}.rmbz-po-alert{grid-template-columns:42px 1fr}.rmbz-po-alert-open{grid-column:2}.rmbz-po-chart svg{height:220px}.rmbz-po-nav{border-radius:16px}.rmbz-po-metric-copy strong{font-size:21px}}
    </style>

    <div class="wrap rmbz-platform-overview">
        <header class="rmbz-po-head">
            <div>
                <div class="rmbz-po-kicker"><?php echo rmbz_admin_overview_icon( 'dashboard' ); ?> Centro de controlo 1MZ</div>
                <h1>Visao Geral da Plataforma</h1>
                <p>Financas, operações, artistas, app e desempenho do catalogo numa unica pagina.</p>
            </div>
            <div class="rmbz-po-actions">
                <a class="rmbz-po-button" href="<?php echo esc_url( rmbz_admin_download_logs_url() ); ?>"><?php echo rmbz_admin_overview_icon( 'report' ); ?> Logs de downloads</a>
                <a class="rmbz-po-button primary" href="<?php echo esc_url( add_query_arg( array_filter( [ 'page'=>'rmbz-dashboard', 'period'=>$period['key'], 'date_from'=>$period['from'], 'date_to'=>$period['to'] ] ), admin_url( 'admin.php' ) ) ); ?>"><?php echo rmbz_admin_overview_icon( 'refresh' ); ?> Atualizar</a>
            </div>
        </header>

        <nav class="rmbz-po-nav" aria-label="Secções da visão geral"><a href="#resumo">Resumo</a><a href="#atividade">Atividade</a><a href="#financas">Finanças</a><a href="#comunidade">Comunidade</a><a href="#conteudo">Conteúdo</a><a href="#rankings">Rankings</a><a href="#sistema">Sistema</a></nav>

        <section class="rmbz-po-filter" aria-label="Filtro temporal">
            <div class="rmbz-po-presets">
                <?php foreach ( [ '7d'=>'7 dias', '30d'=>'30 dias', '90d'=>'90 dias', 'all'=>'Tudo' ] as $key=>$label ): ?>
                    <a class="rmbz-po-preset <?php echo $period['key']===$key?'active':''; ?>" href="<?php echo esc_url( add_query_arg( [ 'page'=>'rmbz-dashboard', 'period'=>$key ], admin_url( 'admin.php' ) ) ); ?>"><?php echo esc_html( $label ); ?></a>
                <?php endforeach; ?>
                <span class="rmbz-po-chip"><?php echo esc_html( $period['label'] ); ?></span>
            </div>
            <form class="rmbz-po-custom" method="get" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>"><input type="hidden" name="page" value="rmbz-dashboard"><input type="hidden" name="period" value="custom"><input type="date" name="date_from" value="<?php echo esc_attr( $period['from'] ); ?>" required aria-label="Data inicial"><input type="date" name="date_to" value="<?php echo esc_attr( $period['to'] ); ?>" required aria-label="Data final"><button>Aplicar datas</button></form>
        </section>

        <section id="resumo" class="rmbz-po-hero">
            <div class="rmbz-po-hero-copy"><small>RESUMO EXECUTIVO / <?php echo esc_html( strtoupper( $period['label'] ) ); ?></small><h2>A plataforma esta a movimentar conteudo, audiencia e pagamentos.</h2><p>Os totais abaixo respeitam o periodo escolhido. Filas operacionais, saldos e estados atuais permanecem em tempo real.</p><div class="rmbz-po-hero-stats"><div class="rmbz-po-hero-stat"><span>Interacoes</span><strong><?php echo esc_html( $number( $downloads + $plays ) ); ?></strong></div><div class="rmbz-po-hero-stat"><span>Fluxo financeiro</span><strong><?php echo esc_html( $money( $net_flow ) ); ?></strong></div><div class="rmbz-po-hero-stat"><span>Fila operacional</span><strong><?php echo esc_html( $number( $dep_pending + $withd_pending + $submissions_pending ) ); ?></strong></div></div></div>
            <aside class="rmbz-po-status"><span class="rmbz-po-status-icon"><?php echo rmbz_admin_overview_icon( empty( $alerts ) ? 'shield' : 'warning' ); ?></span><h3><?php echo empty( $alerts ) ? 'Operacao normal' : count( $alerts ) . ' ponto(s) pedem atencao'; ?></h3><p>Atualizado em <?php echo esc_html( $updated_at ); ?>, fuso <?php echo esc_html( wp_timezone_string() ); ?>.</p></aside>
        </section>

        <?php if ( $alerts ): ?><div class="rmbz-po-alerts"><?php foreach ( $alerts as $alert ): ?><a class="rmbz-po-alert <?php echo esc_attr( $alert['tone'] ); ?>" href="<?php echo esc_url( $alert['url'] ); ?>"><span class="rmbz-po-alert-icon"><?php echo rmbz_admin_overview_icon( $alert['icon'] ); ?></span><span class="rmbz-po-alert-copy"><strong><?php echo esc_html( $alert['title'] ); ?></strong><span><?php echo esc_html( $alert['detail'] ); ?></span></span><span class="rmbz-po-alert-open">Abrir</span></a><?php endforeach; ?></div><?php endif; ?>

        <section class="rmbz-po-section"><div class="rmbz-po-section-head"><div><h2>Indicadores principais</h2><p>Desempenho real no periodo selecionado.</p></div><span class="rmbz-po-chip"><?php echo esc_html( $period['label'] ); ?></span></div><div class="rmbz-po-metrics">
            <?php rmbz_admin_overview_metric( 'Downloads', $number( $downloads ), $published_music . ' músicas publicadas', 'download', 'green', rmbz_admin_download_logs_url() ); ?>
            <?php rmbz_admin_overview_metric( 'Reproduções', $number( $plays ), 'Player oficial do site', 'play', 'blue' ); ?>
            <?php rmbz_admin_overview_metric( 'Vendas concluidas', $number( $sales ), $money( $sales_revenue ) . ' em vendas', 'sales', 'gold', admin_url( 'edit.php?post_type=impulsionamento&page=imz_purchases_manager&status=usado' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Impulsionamentos', $number( $boosts ), 'Campanhas publicadas no periodo', 'campaign', 'gold' ); ?>
            <?php rmbz_admin_overview_metric( 'Publicidade', number_format_i18n( $ad_ctr, 1 ) . '% CTR', $number( $ad_clicks ) . ' cliques em ' . $number( $ad_impressions ) . ' impressoes', 'campaign', 'blue' ); ?>
            <?php rmbz_admin_overview_metric( 'Problemas abertos', $number( $reports_open ), 'Reportes que aguardam decisao', 'warning', $reports_open ? 'red' : 'green', admin_url( 'edit.php?post_type=impulsionamento&page=imz_reports_manager' ) ); ?>
        </div></section>

        <section id="atividade" class="rmbz-po-section"><div class="rmbz-po-section-head"><div><h2>Atividade da plataforma</h2><p>Downloads e reproduções por dia. O gráfico mostra no máximo os ultimos 180 dias.</p></div></div><div class="rmbz-po-activity"><article class="rmbz-po-panel"><header class="rmbz-po-panel-head"><div><h3>Movimento do catálogo</h3><p><?php echo esc_html( wp_date( 'd/m/Y', $chart_from->getTimestamp(), wp_timezone() ) . ' a ' . wp_date( 'd/m/Y', $chart_to->getTimestamp(), wp_timezone() ) ); ?></p></div><div class="rmbz-po-legend"><span><i class="rmbz-po-dot downloads"></i>Downloads</span><span><i class="rmbz-po-dot plays"></i>Reproduções</span></div></header><div class="rmbz-po-chart"><svg viewBox="0 0 1000 250" preserveAspectRatio="none" role="img" aria-label="Grafico de downloads e reproducoes"><line class="rmbz-po-chart-grid" x1="28" y1="20" x2="978" y2="20"/><line class="rmbz-po-chart-grid" x1="28" y1="121" x2="978" y2="121"/><line class="rmbz-po-chart-grid" x1="28" y1="222" x2="978" y2="222"/><text x="30" y="16"><?php echo esc_html( $number( $chart_max ) ); ?></text><text x="30" y="117"><?php echo esc_html( $number( round( $chart_max / 2 ) ) ); ?></text><polyline class="rmbz-po-chart-downloads" points="<?php echo esc_attr( $download_points ); ?>"/><polyline class="rmbz-po-chart-plays" points="<?php echo esc_attr( $play_points ); ?>"/><?php foreach ( $chart_label_indexes as $label_index ): $x = count($chart_labels)<=1?500:28+($label_index/(count($chart_labels)-1))*950; ?><text x="<?php echo esc_attr( round($x,2) ); ?>" y="244" text-anchor="middle"><?php echo esc_html( $chart_labels[$label_index] ?? '' ); ?></text><?php endforeach; ?></svg></div></article><aside class="rmbz-po-panel"><header class="rmbz-po-panel-head"><div><h3>Agora</h3><p>Estado operacional em tempo real</p></div></header><div class="rmbz-po-now"><div class="rmbz-po-now-item"><span>Artistas online</span><strong><?php echo esc_html( $number( $online_now ) ); ?></strong></div><div class="rmbz-po-now-item"><span>Depósitos pendentes</span><strong><?php echo esc_html( $number( $dep_pending ) ); ?></strong></div><div class="rmbz-po-now-item"><span>Levantamentos pendentes</span><strong><?php echo esc_html( $number( $withd_pending ) ); ?></strong></div><div class="rmbz-po-now-item"><span>Envios para moderar</span><strong><?php echo esc_html( $number( $submissions_pending ) ); ?></strong></div><div class="rmbz-po-now-item"><span>Ganhos de download pendentes</span><strong><?php echo esc_html( $money( $dm_pending ) ); ?></strong></div></div></aside></div></section>

        <section id="financas" class="rmbz-po-section"><div class="rmbz-po-section-head"><div><h2>Finanças</h2><p>Entradas e saidas respeitam o periodo; saldos e pendencias mostram o estado atual.</p></div><span class="rmbz-po-chip"><?php echo esc_html( $period['label'] ); ?></span></div><div class="rmbz-po-metrics">
            <?php rmbz_admin_overview_metric( 'Depósitos aprovados', $money( $dep_approved ), $number( $dep_approved_count ) . ' operações', 'download', 'green', admin_url( 'admin.php?page=rmbz-depositos' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Levantamentos pagos', $money( $withd_approved ), $number( $withd_approved_count ) . ' operações', 'payments', 'red', admin_url( 'admin.php?page=rmbz-pedidos-levantamento' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Fluxo liquido', $money( $net_flow ), 'Depositos menos levantamentos', 'wallet', $net_flow>=0?'green':'red' ); ?>
            <?php rmbz_admin_overview_metric( 'Saldo nas carteiras', $money( $wallet_balance ), 'Responsabilidade atual da plataforma', 'wallet', 'gold', admin_url( 'admin.php?page=rmbz-utilizadores' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Receita de produções', $money( $project_revenue ), 'Pagamentos de videoclipes no periodo', 'music', 'blue', admin_url( 'admin.php?page=rmbz-projetos' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Monetização de downloads', $money( $dm_paid ), $dm_active . ' faixas ativas / ' . $money( $dm_pending ) . ' pendentes', 'payments', 'green', admin_url( 'edit.php?post_type=impulsionamento&page=rmbz-download-monetization' ) ); ?>
        </div></section>

        <section id="comunidade" class="rmbz-po-section"><div class="rmbz-po-section-head"><div><h2>Artistas e app</h2><p>Dimensao da comunidade e alcance dos dispositivos.</p></div></div><div class="rmbz-po-metrics">
            <?php rmbz_admin_overview_metric( 'Artistas ativos', $number( $artist_stats->active ), $artist_stats->total . ' contas / ' . $artist_stats->banned . ' banidas', 'groups', 'blue', admin_url( 'admin.php?page=rmbz-utilizadores' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Subscrições VIP', $number( $vip_active ), $vip_expiring . ' expiram em 48 horas', 'shield', 'gold', admin_url( 'admin.php?page=rmbz-pacotes' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Online agora', $number( $online_now ), 'Atividade nos ultimos 5 minutos', 'groups', 'green' ); ?>
            <?php rmbz_admin_overview_metric( 'Dispositivos', $number( $devices ), $number( $sessions ) . ' sessoes ativas', 'phone', 'blue' ); ?>
            <?php rmbz_admin_overview_metric( 'Push notifications', $number( $push_tokens ), 'Dispositivos aptos a receber avisos', 'campaign', 'green' ); ?>
            <?php rmbz_admin_overview_metric( 'Registos apagados', $number( $artist_stats->trash ), 'Contas na lixeira segura', 'report', 'red' ); ?>
        </div></section>

        <section id="conteudo" class="rmbz-po-section"><div class="rmbz-po-section-head"><div><h2>Conteúdo e produção</h2><p>Publicação no site, videoclipes e distribuição digital.</p></div></div><div class="rmbz-po-metrics">
            <?php rmbz_admin_overview_metric( 'Envios no periodo', $number( $submissions_period ), $submissions_published . ' publicados no total', 'music', 'gold', admin_url( 'admin.php?page=rmbz-envios-site' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Fila de moderação', $number( $submissions_pending ), $stale_submissions . ' aguardam há mais de 3 dias', 'clock', $submissions_pending?'red':'green', admin_url( 'admin.php?page=rmbz-envios-site' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Músicas publicadas', $number( $published_music ), 'Catalogo disponivel no site', 'music', 'green' ); ?>
            <?php rmbz_admin_overview_metric( 'Projetos de vídeo', $number( $projects_active ), $projects_done . ' concluídos de ' . $projects_total, 'play', 'blue', admin_url( 'admin.php?page=rmbz-projetos' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Distribuição digital', $number( $releases_total ), $releases_live . ' live / ' . $releases_pending . ' pendentes', 'public', 'green', admin_url( 'admin.php?page=rmbz-admin-distribution' ) ); ?>
            <?php rmbz_admin_overview_metric( 'Faixas monetizadas', $number( $dm_active ), $money( $dm_pending ) . ' em verificação', 'payments', 'gold', admin_url( 'edit.php?post_type=impulsionamento&page=rmbz-download-monetization' ) ); ?>
        </div></section>

        <section id="rankings" class="rmbz-po-section"><div class="rmbz-po-section-head"><div><h2>Rankings do período</h2><p>Conteudo, artistas e territorios com maior atividade.</p></div><span class="rmbz-po-chip"><?php echo esc_html( $period['label'] ); ?></span></div><div class="rmbz-po-rank-grid">
            <?php foreach ( [ [ 'title'=>'Músicas mais descarregadas', 'rows'=>$top_downloads, 'unit'=>'downloads' ], [ 'title'=>'Músicas mais reproduzidas', 'rows'=>$top_plays, 'unit'=>'plays' ] ] as $block ): ?><article class="rmbz-po-panel"><header class="rmbz-po-panel-head"><h3><?php echo esc_html( $block['title'] ); ?></h3></header><?php if(!$block['rows']):?><div class="rmbz-po-empty">Sem dados neste período.</div><?php else:?><ol class="rmbz-po-rank-list"><?php $rank=1;foreach($block['rows'] as $row):?><li><span class="rmbz-po-rank"><?php echo $rank++; ?></span><span class="rmbz-po-rank-name"><?php echo esc_html( get_the_title( $row->music_id ) ?: 'Musica #' . $row->music_id ); ?></span><span class="rmbz-po-rank-value"><?php echo esc_html( $number( $row->total ) . ' ' . $block['unit'] ); ?></span></li><?php endforeach;?></ol><?php endif;?></article><?php endforeach; ?>
        </div><div class="rmbz-po-three" style="margin-top:12px"><?php foreach ( [ [ 'title'=>'Artistas por downloads', 'rows'=>$top_download_artists, 'unit'=>'downloads' ], [ 'title'=>'Províncias', 'rows'=>$top_regions, 'unit'=>'downloads' ], [ 'title'=>'Paises', 'rows'=>$top_countries, 'unit'=>'downloads' ] ] as $block ): ?><article class="rmbz-po-panel"><header class="rmbz-po-panel-head"><h3><?php echo esc_html( $block['title'] ); ?></h3></header><?php if(!$block['rows']):?><div class="rmbz-po-empty">Sem dados neste período.</div><?php else:?><ol class="rmbz-po-rank-list"><?php $rank=1;foreach($block['rows'] as $row):?><li><span class="rmbz-po-rank"><?php echo $rank++; ?></span><span class="rmbz-po-rank-name"><?php echo esc_html( $row->label ?: 'Não informado' ); ?></span><span class="rmbz-po-rank-value"><?php echo esc_html( $number( $row->total ) ); ?></span></li><?php endforeach;?></ol><?php endif;?></article><?php endforeach; ?></div>
        <div class="rmbz-po-rank-grid" style="margin-top:12px"><article class="rmbz-po-panel"><header class="rmbz-po-panel-head"><h3>Maiores depositantes</h3></header><?php if(!$top_depositors):?><div class="rmbz-po-empty">Sem depósitos aprovados neste período.</div><?php else:?><ol class="rmbz-po-rank-list"><?php $rank=1;foreach($top_depositors as $row):?><li><span class="rmbz-po-rank"><?php echo $rank++; ?></span><span class="rmbz-po-rank-name"><?php echo esc_html( $row->label ); ?></span><span class="rmbz-po-rank-value"><?php echo esc_html( $money( $row->total ) ); ?></span></li><?php endforeach;?></ol><?php endif;?></article><article class="rmbz-po-panel"><header class="rmbz-po-panel-head"><h3>Origem dos registos</h3></header><div class="rmbz-po-progress-list"><?php foreach([['App',(int)$registration_origin->app,''],['Site',(int)$registration_origin->site,'gold'],['Histórico',(int)$registration_origin->old,'']] as $origin):$pct=$origin_pct($origin[1],$origin_total);?><div class="rmbz-po-progress"><label><?php echo esc_html($origin[0]);?></label><div class="rmbz-po-progress-track"><div class="rmbz-po-progress-fill <?php echo esc_attr($origin[2]);?>" style="width:<?php echo esc_attr($pct);?>%"></div></div><b><?php echo esc_html($origin[1].' / '.$pct.'%');?></b></div><?php endforeach;?></div></article></div></section>

        <section id="sistema" class="rmbz-po-section"><div class="rmbz-po-section-head"><div><h2>Sistema</h2><p>Configuracao e cobertura tecnica da plataforma.</p></div></div><?php if($device_versions):?><article class="rmbz-po-panel" style="margin-bottom:12px"><header class="rmbz-po-panel-head"><h3>Versões da app em uso</h3></header><div class="rmbz-po-progress-list"><?php $device_total=max(1,array_sum(array_map(static function($row){return(int)$row->total;},$device_versions)));foreach($device_versions as $version):$pct=round(($version->total/$device_total)*100);?><div class="rmbz-po-progress"><label>v<?php echo esc_html($version->version);?></label><div class="rmbz-po-progress-track"><div class="rmbz-po-progress-fill" style="width:<?php echo esc_attr($pct);?>%"></div></div><b><?php echo esc_html($version->total.' / '.$pct.'%');?></b></div><?php endforeach;?></div></article><?php endif;?><div class="rmbz-po-system"><div class="rmbz-po-system-item"><small>Plugin</small><strong>v<?php echo esc_html( defined('RMBZ_PLUGIN_VERSION')?RMBZ_PLUGIN_VERSION:'-' );?></strong></div><div class="rmbz-po-system-item"><small>Base de dados</small><strong><?php echo esc_html(get_option('rmbz_db_version','-'));?></strong></div><div class="rmbz-po-system-item"><small>App mínima / atual</small><strong><?php echo (int)get_option('rmbz_min_app_version_code',0);?> / <?php echo (int)get_option('rmbz_latest_app_version_code',0);?></strong></div><div class="rmbz-po-system-item"><small>Fuso horário</small><strong><?php echo esc_html(wp_timezone_string());?></strong></div><div class="rmbz-po-system-item"><small>Tabelas monitorizadas</small><strong><?php echo esc_html(count(array_filter($has)).' / '.count($has));?></strong></div><div class="rmbz-po-system-item"><small>Liquidação automática</small><strong><?php $next=wp_next_scheduled('rmbz_dm_hourly_settlement');echo $next?esc_html(wp_date('d/m H:i',$next,wp_timezone())):'Não agendada';?></strong></div><div class="rmbz-po-system-item"><small>Taxa USD para MT</small><strong><?php echo esc_html(number_format_i18n((float)get_option('rmbz_exchange_rate',0),2));?></strong></div><div class="rmbz-po-system-item"><small>Atualização</small><strong><?php echo esc_html($updated_at);?></strong></div></div></section>

        <footer class="rmbz-po-foot">Os indicadores usam dados reais das tabelas 1MZ. O período não altera filas, saldos ou estados atuais.</footer>
    </div>
    <?php
}
