<?php
/**
 * Painel nativo Músicas & Ganhos.
 * Usa o Art Track como catálogo e a carteira 1MZ como única fonte financeira.
 */
if ( ! defined( 'ABSPATH' ) ) exit;

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

function imz_native_dashboard_money( $amount ) {
    return number_format_i18n( (float) $amount, 2 );
}

function imz_native_dashboard_date( $value, $with_time = false ) {
    $stamp = $value ? strtotime( (string) $value ) : false;
    if ( ! $stamp ) return 'Não informado';
    return date_i18n( $with_time ? 'd/m/Y H:i' : 'd/m/Y', $stamp );
}

function imz_native_dashboard_music_ids( $artist_id, $art_track_id ) {
    $ids = [];
    if ( $art_track_id && function_exists( 'rmbz_art_track_music_ids' ) ) {
        $ids = array_map( 'absint', rmbz_art_track_music_ids( $art_track_id ) );
    }
    if ( ! $ids && $art_track_id ) {
        $ids = get_posts( [
            'post_type'      => 'post',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'fields'         => 'ids',
            'meta_key'       => '_imz_artista_id',
            'meta_value'     => $art_track_id,
            'no_found_rows'  => true,
        ] );
    }

    return array_values( array_unique( array_filter( array_map( 'absint', $ids ) ) ) );
}

function imz_native_dashboard_clean_title( $post_id ) {
    remove_filter( 'the_title', 'imz_add_verified_badge_to_title', 10 );
    $title = get_the_title( $post_id );
    add_filter( 'the_title', 'imz_add_verified_badge_to_title', 10, 2 );
    return trim( wp_strip_all_tags( (string) $title ) );
}

add_shortcode( 'painel_artista', 'imz_render_artist_dashboard_shortcode' );

function imz_render_artist_dashboard_shortcode() {
    $logged_in = function_exists( 'imz_rmbz_is_artist_logged_in' ) ? imz_rmbz_is_artist_logged_in() : is_user_logged_in();
    if ( ! $logged_in ) {
        $login_url = function_exists( 'imz_rmbz_account_url' ) ? imz_rmbz_account_url() : wp_login_url( get_permalink() );
        return '<div class="rmbz-mg-empty"><span class="ms">lock</span><h3>Acesso reservado</h3><p>Entra na tua conta 1MZ For Artists para consultar o catálogo.</p><a class="rmbz-mg-button primary" href="' . esc_url( $login_url ) . '">Entrar na conta</a></div>';
    }

    $phone = function_exists( 'rmbz_get_current_user_telemovel' ) ? trim( (string) rmbz_get_current_user_telemovel() ) : '';
    if ( defined( 'RMBZ_ARTISTS_EMBEDDED' ) && function_exists( 'rmbz_partnership_has_access' ) && ! rmbz_partnership_has_access( $phone ) ) {
        return function_exists( 'rmbz_render_partnership_program' )
            ? rmbz_render_partnership_program( $phone )
            : '<div class="rmbz-mg-empty"><h3>Programa de Parceria necessário</h3></div>';
    }

    global $wpdb;
    $artist_id = function_exists( 'imz_get_current_artist_user_id' ) ? absint( imz_get_current_artist_user_id() ) : get_current_user_id();
    if ( ! $artist_id ) return '<div class="rmbz-mg-empty"><h3>Conta não associada</h3><p>Atualiza a página ou contacta o suporte.</p></div>';

    $account_status = function_exists( 'imz_rmbz_artist_account_status' ) ? imz_rmbz_artist_account_status( $artist_id ) : 'active';
    if ( $account_status === 'blocked' ) return '<div class="rmbz-mg-empty danger"><span class="ms">block</span><h3>Conta bloqueada</h3><p>O catálogo e as operações financeiras estão temporariamente indisponíveis.</p></div>';

    $art_track_id = function_exists( 'rmbz_artists_get_art_track_for_user' ) ? absint( rmbz_artists_get_art_track_for_user( $artist_id ) ) : 0;
    $art_track = $art_track_id && function_exists( 'rmbz_art_track_get' ) ? rmbz_art_track_get( $art_track_id ) : null;
    $music_ids = imz_native_dashboard_music_ids( $artist_id, $art_track_id );
    $music_posts = $music_ids ? get_posts( [
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'post__in'       => $music_ids,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'no_found_rows'  => true,
    ] ) : [];
    if ( function_exists( 'rmbz_site_publication_is_visible' ) ) {
        $music_posts = array_values( array_filter( $music_posts, static function( $post ) {
            return rmbz_site_publication_is_visible( $post->ID );
        } ) );
    }
    $music_ids = array_map( 'absint', wp_list_pluck( $music_posts, 'ID' ) );

    $wallet = function_exists( 'rmbz_artists_get_wallet' ) ? rmbz_artists_get_wallet( $phone ) : null;
    $wallet_total = function_exists( 'rmbz_get_wallet_balance_by_phone' ) ? (float) rmbz_get_wallet_balance_by_phone( $phone ) : ( $wallet ? (float) $wallet->balance : 0.0 );
    $wallet_withdrawable = function_exists( 'rmbz_get_withdrawable_balance' ) ? (float) rmbz_get_withdrawable_balance( $phone ) : $wallet_total;
    $wallet_promotional = max( 0, $wallet_total - $wallet_withdrawable );
    $wallet_url = function_exists( 'imz_rmbz_account_url' ) ? imz_rmbz_account_url( 'financas' ) : add_query_arg( 'sect', 'financas', home_url( '/minha-conta/' ) );

    $today_downloads = [];
    $regions = [];
    $analytics_table = $wpdb->prefix . 'imz_analytics';
    if ( $music_ids && imz_native_dashboard_table_exists( $analytics_table ) ) {
        $safe_ids = implode( ',', array_map( 'absint', $music_ids ) );
        $today_rows = $wpdb->get_results( "SELECT music_id,COUNT(*) qty FROM {$analytics_table} WHERE music_id IN ({$safe_ids}) AND DATE(download_date)=CURDATE() GROUP BY music_id" );
        foreach ( (array) $today_rows as $row ) $today_downloads[ absint( $row->music_id ) ] = (int) $row->qty;
        $regions = $wpdb->get_results( "SELECT region,COUNT(*) qty FROM {$analytics_table} WHERE music_id IN ({$safe_ids}) AND region<>'' AND region<>'N/A' GROUP BY region ORDER BY qty DESC LIMIT 5" );
    }

    $boost_map = [];
    $active_boost_map = [];
    if ( $music_ids ) {
        $boost_ids = get_posts( [
            'post_type'      => 'impulsionamento',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'fields'         => 'ids',
            'meta_query'     => [
                [ 'key'=>'post_id_original', 'value'=>$music_ids, 'compare'=>'IN', 'type'=>'NUMERIC' ],
                [ 'key'=>'status', 'value'=>'aprovado' ],
            ],
            'no_found_rows'  => true,
        ] );
        foreach ( $boost_ids as $boost_id ) {
            $mid = absint( get_post_meta( $boost_id, 'post_id_original', true ) );
            if ( ! isset( $boost_map[ $mid ] ) ) $boost_map[ $mid ] = 0;
            $boost_map[ $mid ]++;
            if ( function_exists( 'imz_boost_is_active' ) && imz_boost_is_active( $boost_id ) ) {
                $end = (string) get_post_meta( $boost_id, '_boost_data_fim', true );
                $current_end = (string) ( $active_boost_map[ $mid ]['end'] ?? '' );
                if ( ! isset( $active_boost_map[ $mid ] ) || $end === '' || ( $current_end !== '' && strtotime( $end ) > strtotime( $current_end ) ) ) {
                    $active_boost_map[ $mid ] = [ 'id' => absint( $boost_id ), 'end' => $end ];
                }
            }
        }
    }

    $sales_map = [];
    $purchases_table = $wpdb->prefix . 'imz_purchases';
    if ( imz_native_dashboard_table_exists( $purchases_table ) ) {
        $sales_rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT music_id,COUNT(*) qty,COALESCE(SUM(price),0) total FROM {$purchases_table} WHERE artist_id=%d AND status='usado' GROUP BY music_id",
            $artist_id
        ) );
        foreach ( (array) $sales_rows as $row ) $sales_map[ absint( $row->music_id ) ] = [ 'qty'=>(int)$row->qty, 'total'=>(float)$row->total ];
    }


    $tracks = [];
    $total_downloads = 0;
    $total_plays = 0;
    $total_boosts = 0;
    $total_artist_earnings = 0.0;
    $total_pending_earnings = 0.0;
    $total_sales = 0.0;
    $incomplete_count = 0;
    foreach ( $music_posts as $music ) {
        $mid = absint( $music->ID );
        $title = imz_native_dashboard_clean_title( $mid );
        $custom_artist = trim( (string) get_post_meta( $mid, '_imz_custom_audio_artist', true ) );
        $cover = (string) get_the_post_thumbnail_url( $mid, 'medium' );
        $release_raw = (string) get_post_meta( $mid, '_imz_release_date', true );
        $quality = trim( (string) get_post_meta( $mid, '_imz_quality', true ) );
        $downloads = (int) get_post_meta( $mid, '_imz_download_count', true );
        $plays = function_exists( 'imz_get_play_count' ) ? (int) imz_get_play_count( $mid ) : 0;
        $boosts = (int) ( $boost_map[ $mid ] ?? 0 );
        $monetization = function_exists( 'rmbz_dm_music_summary' ) ? rmbz_dm_music_summary( $mid ) : [ 'status'=>'inactive', 'rate'=>0, 'valid_downloads'=>0, 'pending_downloads'=>0, 'rejected_downloads'=>0, 'pending_amount'=>0, 'paid_amount'=>0 ];
        $artist_earnings = (float) $monetization['paid_amount'];
        $gross_earnings = (float) $monetization['paid_amount'] + (float) $monetization['pending_amount'];
        $sales = $sales_map[ $mid ] ?? [ 'qty'=>0, 'total'=>0.0 ];
        $stores = get_post_meta( $mid, '_imz_digital_stores', true );
        $stores = is_array( $stores ) ? array_values( array_filter( $stores, 'is_array' ) ) : [];
        $paid_state = (string) get_post_meta( $mid, '_imz_enable_paid_download', true );
        $paid_price = (float) get_post_meta( $mid, '_imz_paid_download_price', true );
        $download_enabled = (string) get_post_meta( $mid, '_imz_enable_download', true ) === 'yes';
        $protected = (string) get_post_meta( $mid, '_imz_protected_for_artists', true ) === 'yes';
        $verified = (string) get_post_meta( $mid, '_is_verified_by_boosts', true ) === 'yes' || ( $art_track && ! empty( $art_track->verified ) );
        $monetized = $monetization['status'] === 'active';
        $youtube = (string) get_post_meta( $mid, '_imz_youtube_url', true );
        if ( $youtube === '' ) $youtube = (string) get_post_meta( $mid, '_imz_audio_player_url', true );
        $total_limit = absint( get_post_meta( $mid, '_imz_download_limit_per_post', true ) );
        $daily_limit = absint( get_post_meta( $mid, '_imz_daily_download_limit', true ) );
        $blocked = get_post_meta( $mid, '_imz_blocked_countries_per_post', true );
        $blocked_list = is_array( $blocked ) ? $blocked : array_filter( array_map( 'trim', explode( ',', (string) $blocked ) ) );
        $category_names = wp_get_post_terms( $mid, 'category', [ 'fields'=>'names' ] );
        if ( is_wp_error( $category_names ) ) $category_names = [];
        $genre = $category_names ? implode( ', ', $category_names ) : 'Não informado';
        $role = $art_track_id && function_exists( 'rmbz_art_track_music_role' ) ? rmbz_art_track_music_role( $art_track_id, $mid ) : 'primary';
        $feat_ids = get_post_meta( $mid, '_imz_feat_artista_ids', true );
        $feat_names = [];
        foreach ( array_map( 'absint', (array) $feat_ids ) as $feat_id ) {
            $feat_name = function_exists( 'rmbz_art_track_name' ) ? rmbz_art_track_name( $feat_id ) : get_the_title( $feat_id );
            if ( $feat_name ) $feat_names[] = (string) $feat_name;
        }
        $missing = [];
        if ( $cover === '' ) $missing[] = 'capa';
        if ( $release_raw === '' ) $missing[] = 'data de lançamento';
        if ( $quality === '' ) $missing[] = 'qualidade';
        if ( ! $stores ) $missing[] = 'lojas';
        if ( $missing ) $incomplete_count++;
        $flags = [ 'all' ];
        if ( $monetized ) $flags[] = 'monetized';
        if ( in_array( $paid_state, [ 'yes', 'expired_pro' ], true ) ) $flags[] = 'paid';
        if ( $protected ) $flags[] = 'protected';
        if ( $missing ) $flags[] = 'incomplete';
        $active_boost = $active_boost_map[ $mid ] ?? null;
        $tracks[] = [
            'id'=>$mid, 'title'=>$title ?: 'Música sem título', 'artist'=>$custom_artist, 'cover'=>$cover,
            'release'=>$release_raw, 'quality'=>$quality ?: 'Não informada', 'downloads'=>$downloads,
            'today'=>(int)($today_downloads[$mid]??0), 'plays'=>$plays, 'boosts'=>$boosts,
            'boost_active'=>(bool)$active_boost, 'boost_end'=>$active_boost ? (string)$active_boost['end'] : '',
            'artist_earnings'=>$artist_earnings, 'gross_earnings'=>$gross_earnings,
            'monet_status'=>(string)$monetization['status'], 'monet_rate'=>(float)$monetization['rate'],
            'monet_valid'=>(int)$monetization['valid_downloads'], 'monet_pending_downloads'=>(int)$monetization['pending_downloads'],
            'monet_rejected'=>(int)$monetization['rejected_downloads'], 'monet_pending'=>(float)$monetization['pending_amount'],
            'sales_qty'=>(int)$sales['qty'], 'sales_total'=>(float)$sales['total'], 'stores'=>$stores,
            'paid'=>in_array($paid_state,['yes','expired_pro'],true), 'paid_price'=>$paid_price,
            'download_enabled'=>$download_enabled, 'protected'=>$protected, 'verified'=>$verified,
            'monetized'=>$monetized, 'youtube'=>$youtube, 'total_limit'=>$total_limit,
            'daily_limit'=>$daily_limit, 'blocked'=>$blocked_list, 'genre'=>$genre, 'role'=>$role ?: 'primary',
            'feats'=>$feat_names, 'missing'=>$missing, 'flags'=>$flags, 'permalink'=>get_permalink($mid),
            'published'=>$music->post_date, 'updated'=>$music->post_modified,
        ];
        $total_downloads += $downloads;
        $total_plays += $plays;
        $total_boosts += $boosts;
        $total_artist_earnings += $artist_earnings;
        $total_pending_earnings += (float) $monetization['pending_amount'];
        $total_sales += (float) $sales['total'];
    }

    usort( $tracks, static function( $a, $b ) { return $b['downloads'] <=> $a['downloads']; } );
    $top_track = $tracks[0] ?? null;
    $expiry = function_exists( 'imz_rmbz_subscription_expiry_for_user' ) ? imz_rmbz_subscription_expiry_for_user( $artist_id ) : '';
    $expiry_label = $expiry ? imz_native_dashboard_date( $expiry ) : 'Sem data definida';

    $boost_notice = sanitize_key( wp_unslash( $_GET['boost_notice'] ?? '' ) );
    $boost_notices = [
        'success'              => [ 'success', 'Campanha ativada', 'A música já está em destaque. O valor foi debitado da carteira.' ],
        'insufficient_balance' => [ 'danger', 'Saldo insuficiente', 'Deposita saldo na carteira para ativar este período.' ],
        'already_processed'    => [ 'success', 'Campanha já processada', 'Este pedido já foi concluído e não foi cobrado novamente.' ],
        'invalid_music'        => [ 'danger', 'Música indisponível', 'Só podes impulsionar músicas publicadas e ligadas ao teu Art Track.' ],
        'account_blocked'      => [ 'danger', 'Operação bloqueada', 'A conta não pode criar campanhas neste momento.' ],
        'partnership_required' => [ 'danger', 'Programa de Parceria necessário', 'O impulsionamento está disponível no painel Músicas & Ganhos.' ],
        'security_error'       => [ 'danger', 'Pedido expirado', 'Atualiza a página e tenta novamente.' ],
        'debit_error'          => [ 'danger', 'Pagamento não concluído', 'Não foi possível debitar a carteira. Nenhuma campanha foi criada.' ],
        'save_error'           => [ 'danger', 'Campanha não criada', 'A operação foi revertida. Tenta novamente.' ],
        'try_again'            => [ 'danger', 'Sistema ocupado', 'Espera alguns segundos e tenta novamente.' ],
        'wallet_unavailable'   => [ 'danger', 'Carteira indisponível', 'Tenta novamente dentro de alguns instantes.' ],
        'account_error'        => [ 'danger', 'Conta não associada', 'Atualiza a página ou contacta o suporte.' ],
        'invalid_duration'     => [ 'danger', 'Período inválido', 'Seleciona uma das durações disponíveis.' ],
        'login_required'       => [ 'danger', 'Sessão terminada', 'Entra novamente na tua conta.' ],
    ];
    $price_per_day = max( 0.01, (float) get_option( 'imz_boost_price_per_day', 50 ) );
    $boost_request_key = wp_generate_uuid4();
    $boost_signature = hash_hmac( 'sha256', $artist_id . '|' . $phone . '|' . $boost_request_key, wp_salt( 'auth' ) );
    $monet_notice = sanitize_key( wp_unslash( $_GET['monet_notice'] ?? '' ) );
    $monet_notices = [
        'activated'            => [ 'success', 'Monetização ativada', 'Os próximos downloads válidos começam a gerar ganhos pendentes.' ],
        'terms_required'       => [ 'danger', 'Confirmações obrigatórias', 'Confirma a titularidade e aceita as regras antes de ativar.' ],
        'download_disabled'    => [ 'danger', 'Download indisponível', 'A equipa precisa ativar o download gratuito desta música.' ],
        'partnership_required' => [ 'danger', 'Parceria necessária', 'O Programa de Parceria precisa estar aprovado.' ],
        'not_owner'            => [ 'danger', 'Música não associada', 'Esta música não está ligada como faixa principal do teu Art Track.' ],
        'not_primary'          => [ 'danger', 'Participação não elegível', 'A ativação deve ser feita pelo titular da faixa principal.' ],
        'suspended'            => [ 'danger', 'Monetização suspensa', 'Contacta a equipa para consultar o motivo.' ],
        'archived'             => [ 'danger', 'Monetização arquivada', 'Esta faixa foi encerrada pela equipa e não pode ser reativada no painel.' ],
        'security_error'       => [ 'danger', 'Pedido expirado', 'Atualiza a página e tenta novamente.' ],
        'save_error'           => [ 'danger', 'Não foi possível ativar', 'Nenhum estado financeiro foi alterado.' ],
        'login_required'       => [ 'danger', 'Sessão terminada', 'Entra novamente na tua conta.' ],
    ];

    ob_start();
    ?>    <?php $strikes = function_exists( 'imz_get_valid_artist_strikes' ) ? (int) imz_get_valid_artist_strikes( $artist_id ) : 0; ?>
    <div class="rmbz-mg" data-rmbz-music-dashboard>
        <?php if ( isset( $monet_notices[ $monet_notice ] ) ): $notice = $monet_notices[ $monet_notice ]; ?>
            <div class="rmbz-mg-alert <?php echo esc_attr( $notice[0] ); ?>"><span class="ms"><?php echo $notice[0] === 'success' ? 'check_circle' : 'error'; ?></span><div><strong><?php echo esc_html( $notice[1] ); ?></strong><span><?php echo esc_html( $notice[2] ); ?></span></div></div>
        <?php endif; ?>
        <?php if ( isset( $boost_notices[ $boost_notice ] ) ): $notice = $boost_notices[ $boost_notice ]; ?>
            <div class="rmbz-mg-alert <?php echo esc_attr( $notice[0] ); ?>"><span class="ms"><?php echo $notice[0] === 'success' ? 'check_circle' : 'error'; ?></span><div><strong><?php echo esc_html( $notice[1] ); ?></strong><span><?php echo esc_html( $notice[2] ); ?></span></div></div>
        <?php endif; ?>
        <?php if ( $strikes > 0 ): ?>
            <div class="rmbz-mg-alert danger"><span class="ms">warning</span><div><strong><?php echo esc_html( sprintf( _n( '%d aviso ativo', '%d avisos ativos', $strikes, '1mz-for-artists' ), $strikes ) ); ?></strong><span>Revê as políticas da plataforma. Três avisos ativos bloqueiam a conta.</span></div></div>
        <?php endif; ?>

        <header class="rmbz-mg-header">
            <div class="rmbz-mg-header-icon"><span class="ms">library_music</span></div>
            <div class="rmbz-mg-header-copy">
                <span class="rmbz-mg-eyebrow">PAINEL DO PROGRAMA DE PARCERIA</span>
                <h2>Catálogo e desempenho</h2>
                <p>Informação consolidada das músicas publicadas e ligadas ao teu Art Track.</p>
            </div>
            <div class="rmbz-mg-header-badges">
                <span class="rmbz-mg-chip success"><span class="ms">verified</span>Parceria ativa</span>
                <span class="rmbz-mg-chip"><span class="ms">album</span>Art Track #<?php echo (int) $art_track_id; ?></span>
                <span class="rmbz-mg-chip"><span class="ms">workspace_premium</span>VIP até <?php echo esc_html( $expiry_label ); ?></span>
            </div>
        </header>

        <section class="rmbz-mg-finance-grid" aria-label="Resumo financeiro">
            <article class="rmbz-mg-wallet-card">
                <div class="rmbz-mg-wallet-head"><span class="ms">account_balance_wallet</span><span>Carteira oficial 1MZ</span><span class="rmbz-mg-live"><i></i>Ligada</span></div>
                <div class="rmbz-mg-wallet-value"><?php echo esc_html( imz_native_dashboard_money( $wallet_total ) ); ?><small>MT</small></div>
                <div class="rmbz-mg-wallet-facts">
                    <span><small>Retirável</small><strong><?php echo esc_html( imz_native_dashboard_money( $wallet_withdrawable ) ); ?> MT</strong></span>
                    <span><small>Promocional</small><strong><?php echo esc_html( imz_native_dashboard_money( $wallet_promotional ) ); ?> MT</strong></span>
                </div>
                <div class="rmbz-mg-wallet-footer">
                    <p>Depósitos, pagamentos, extrato e levantamentos são geridos apenas na carteira do artista.</p>
                    <a class="rmbz-mg-button light" href="<?php echo esc_url( $wallet_url ); ?>"><span class="ms">arrow_forward</span>Abrir Finanças</a>
                </div>
            </article>
            <article class="rmbz-mg-finance-card">
                <span class="rmbz-mg-tonal-icon"><span class="ms">monitoring</span></span>
                <small>MONETIZAÇÃO POR DOWNLOAD</small>
                <strong><?php echo esc_html( imz_native_dashboard_money( $total_artist_earnings ) ); ?> MT</strong>
                <p><?php echo esc_html( imz_native_dashboard_money( $total_pending_earnings ) ); ?> MT pendentes durante a verificação antifraude.</p>
            </article>
            <article class="rmbz-mg-finance-card">
                <span class="rmbz-mg-tonal-icon"><span class="ms">shopping_bag</span></span>
                <small>VENDAS CONCLUÍDAS</small>
                <strong><?php echo esc_html( imz_native_dashboard_money( $total_sales ) ); ?> MT</strong>
                <p>Total registado nas vendas diretas das músicas deste catálogo.</p>
            </article>
        </section>

        <section class="rmbz-mg-kpis" aria-label="Indicadores do catálogo">
            <?php foreach ( [
                [ 'library_music', count( $tracks ), 'Músicas publicadas', 'Catálogo ligado ao Art Track' ],
                [ 'download', $total_downloads, 'Downloads', 'Acumulados no site' ],
                [ 'play_circle', $total_plays, 'Reproduções', 'No leitor da plataforma' ],
                [ 'campaign', $total_boosts, 'Impulsionamentos', 'Campanhas aprovadas' ],
            ] as $kpi ): ?>
                <article class="rmbz-mg-kpi"><span class="ms"><?php echo esc_html( $kpi[0] ); ?></span><div><strong><?php echo esc_html( number_format_i18n( $kpi[1] ) ); ?></strong><b><?php echo esc_html( $kpi[2] ); ?></b><small><?php echo esc_html( $kpi[3] ); ?></small></div></article>
            <?php endforeach; ?>
        </section>

        <section class="rmbz-mg-insights">
            <article class="rmbz-mg-insight featured">
                <div class="rmbz-mg-insight-head"><span class="ms">trending_up</span><span>Faixa com maior alcance</span></div>
                <?php if ( $top_track ): ?>
                    <div class="rmbz-mg-top-track">
                        <div class="rmbz-mg-mini-cover"><?php if ( $top_track['cover'] ): ?><img src="<?php echo esc_url( $top_track['cover'] ); ?>" alt=""><?php else: ?><span class="ms">music_note</span><?php endif; ?></div>
                        <div><strong><?php echo esc_html( $top_track['title'] ); ?></strong><small><?php echo esc_html( number_format_i18n( $top_track['downloads'] ) ); ?> downloads · <?php echo esc_html( number_format_i18n( $top_track['plays'] ) ); ?> reproduções</small></div>
                    </div>
                <?php else: ?><p>Ainda não existem músicas publicadas.</p><?php endif; ?>
            </article>
            <article class="rmbz-mg-insight">
                <div class="rmbz-mg-insight-head"><span class="ms">location_on</span><span>Principais localizações</span></div>
                <?php if ( $regions ): ?><div class="rmbz-mg-region-list"><?php foreach ( $regions as $index=>$region ): ?><div><span><?php echo (int)$index+1; ?></span><b><?php echo esc_html( (string)$region->region ); ?></b><small><?php echo esc_html( number_format_i18n( (int)$region->qty ) ); ?></small></div><?php endforeach; ?></div><?php else: ?><p>Ainda não existem localizações suficientes.</p><?php endif; ?>
            </article>
            <article class="rmbz-mg-insight">
                <div class="rmbz-mg-insight-head"><span class="ms">fact_check</span><span>Saúde do catálogo</span></div>
                <div class="rmbz-mg-health"><strong><?php echo (int) max( 0, count( $tracks ) - $incomplete_count ); ?>/<?php echo (int) count( $tracks ); ?></strong><div><span style="width:<?php echo count($tracks)?esc_attr(round(((count($tracks)-$incomplete_count)/count($tracks))*100)):0; ?>%"></span></div><small><?php echo $incomplete_count ? esc_html( sprintf( '%d faixa(s) com informação por completar', $incomplete_count ) ) : 'Todas as faixas estão completas'; ?></small></div>
            </article>
        </section>

        <section class="rmbz-mg-catalog">
            <div class="rmbz-mg-section-head">
                <div><span class="rmbz-mg-eyebrow">CATÁLOGO DO ART TRACK</span><h3>As tuas músicas</h3><p>Pesquisa, filtra e abre a ficha completa de cada publicação.</p></div>
                <span class="rmbz-mg-result-count" data-mg-count><?php echo (int) count( $tracks ); ?> resultado(s)</span>
            </div>
            <div class="rmbz-mg-toolbar">
                <label class="rmbz-mg-search"><span class="ms">search</span><input type="search" placeholder="Pesquisar título, artista ou género" data-mg-search></label>
                <div class="rmbz-mg-filters" role="group" aria-label="Filtrar catálogo">
                    <button type="button" class="on" data-mg-filter="all">Todas</button>
                    <button type="button" data-mg-filter="monetized">Monetizadas</button>
                    <button type="button" data-mg-filter="paid">Venda direta</button>
                    <button type="button" data-mg-filter="protected">Protegidas</button>
                    <button type="button" data-mg-filter="incomplete">A completar</button>
                </div>
            </div>

            <?php if ( ! $tracks ): ?>
                <div class="rmbz-mg-empty"><span class="ms">library_add</span><h3>O catálogo ainda está vazio</h3><p>As músicas aparecem aqui depois de serem publicadas e validadas pela equipa 1MZ.</p><a class="rmbz-mg-button primary" href="<?php echo esc_url( function_exists('imz_rmbz_account_url') ? imz_rmbz_account_url('envios') : home_url('/minha-conta/') ); ?>">Ver os meus envios</a></div>
            <?php else: ?>
                <div class="rmbz-mg-track-list" data-mg-list>
                    <?php foreach ( $tracks as $track ):
                        $search_text = trim( $track['title'].' '.$track['artist'].' '.$track['genre'].' '.implode(' ',$track['feats']) );
                        $search_text = function_exists('mb_strtolower') ? mb_strtolower($search_text) : strtolower($search_text);
                        $role_label = $track['role']==='featured' ? 'Participação' : 'Faixa principal';
                        $monet_labels = [ 'inactive'=>'Não ativada', 'pending'=>'Pendente', 'active'=>'Monetizada', 'suspended'=>'Suspensa', 'archived'=>'Arquivada' ];
                        $monet_label = $monet_labels[$track['monet_status']] ?? ucfirst($track['monet_status']);
                    ?>
                    <article class="rmbz-mg-track" data-mg-track data-search="<?php echo esc_attr( $search_text ); ?>" data-flags="<?php echo esc_attr( implode(' ',$track['flags']) ); ?>">
                        <div class="rmbz-mg-track-main">
                            <div class="rmbz-mg-cover"><?php if($track['cover']):?><img loading="lazy" src="<?php echo esc_url($track['cover']);?>" alt="Capa de <?php echo esc_attr($track['title']);?>"><?php else:?><span class="ms">music_note</span><?php endif;?></div>
                            <div class="rmbz-mg-track-copy">
                                <div class="rmbz-mg-track-badges">
                                    <span class="rmbz-mg-chip"><?php echo esc_html($role_label);?></span>
                                    <span class="rmbz-mg-chip monet-<?php echo esc_attr($track['monet_status']);?>"><span class="ms"><?php echo $track['monet_status']==='active'?'paid':($track['monet_status']==='suspended'?'pause_circle':'pending_actions');?></span><?php echo esc_html($monet_label);?></span>
                                    <?php if($track['verified']):?><span class="rmbz-mg-chip success"><span class="ms">verified</span>Verificada</span><?php endif;?>
                                    <?php if($track['protected']):?><span class="rmbz-mg-chip info"><span class="ms">shield</span>Protegida</span><?php endif;?>
                                    <?php if($track['paid']):?><span class="rmbz-mg-chip warning"><span class="ms">sell</span><?php echo esc_html(imz_native_dashboard_money($track['paid_price']));?> MT</span><?php endif;?>
                                    <?php if($track['boost_active']):?><span class="rmbz-mg-chip boosted"><span class="ms">campaign</span><?php echo $track['boost_end'] ? 'Impulsionada até '.esc_html(imz_native_dashboard_date($track['boost_end'])) : 'Impulsionada';?></span><?php endif;?>
                                </div>
                                <h4><?php echo esc_html($track['title']);?></h4>
                                <p><?php echo esc_html($track['artist']?:($art_track?(string)$art_track->artist_name:'Artista 1MZ'));?><?php if($track['feats']):?> · feat. <?php echo esc_html(implode(', ',$track['feats']));?><?php endif;?></p>
                                <div class="rmbz-mg-track-meta"><span><span class="ms">calendar_month</span><?php echo esc_html(imz_native_dashboard_date($track['release']));?></span><span><span class="ms">graphic_eq</span><?php echo esc_html($track['quality']);?></span><span><span class="ms">category</span><?php echo esc_html($track['genre']);?></span></div>
                            </div>
                            <div class="rmbz-mg-track-actions">
                                <a class="rmbz-mg-icon-button" href="<?php echo esc_url($track['permalink']);?>" target="_blank" rel="noopener" aria-label="Abrir publicação"><span class="ms">open_in_new</span></a>
                                <button type="button" class="rmbz-mg-button tonal" data-mg-boost-open data-music-id="<?php echo (int)$track['id'];?>" data-music-title="<?php echo esc_attr($track['title']);?>" data-boost-active="<?php echo $track['boost_active']?'1':'0';?>"><span class="ms">campaign</span><?php echo $track['boost_active']?'Prolongar':'Impulsionar';?></button>
                            </div>
                        </div>
                        <div class="rmbz-mg-track-stats">
                            <div><span class="ms">download</span><strong><?php echo esc_html(number_format_i18n($track['downloads']));?></strong><small>Downloads</small><em>+<?php echo esc_html(number_format_i18n($track['today']));?> hoje</em></div>
                            <div><span class="ms">play_circle</span><strong><?php echo esc_html(number_format_i18n($track['plays']));?></strong><small>Reproduções</small></div>
                            <div><span class="ms">campaign</span><strong><?php echo esc_html(number_format_i18n($track['boosts']));?></strong><small>Impulsos</small></div>
                            <div><span class="ms">shopping_bag</span><strong><?php echo esc_html(number_format_i18n($track['sales_qty']));?></strong><small>Vendas</small><em><?php echo esc_html(imz_native_dashboard_money($track['sales_total']));?> MT</em></div>
                            <div><span class="ms">payments</span><strong><?php echo esc_html(imz_native_dashboard_money($track['artist_earnings']));?></strong><small>Pago por downloads</small><em><?php echo esc_html(imz_native_dashboard_money($track['monet_pending']));?> MT pendentes</em></div>
                        </div>
                        <details class="rmbz-mg-details">
                            <summary><span><span class="ms">info</span>Ficha completa da música</span><span class="ms chevron">expand_more</span></summary>
                            <div class="rmbz-mg-details-body">
                                <section><h5><span class="ms">badge</span>Identidade e publicação</h5><dl class="rmbz-mg-data-grid">
                                    <div><dt>ID da publicação</dt><dd>#<?php echo (int)$track['id'];?></dd></div><div><dt>Art Track</dt><dd>#<?php echo (int)$art_track_id;?></dd></div><div><dt>Participação</dt><dd><?php echo esc_html($role_label);?></dd></div><div><dt>Publicado</dt><dd><?php echo esc_html(imz_native_dashboard_date($track['published'],true));?></dd></div><div><dt>Última atualização</dt><dd><?php echo esc_html(imz_native_dashboard_date($track['updated'],true));?></dd></div><div><dt>Estado</dt><dd>Publicado no site</dd></div>
                                </dl></section>
                                <section><h5><span class="ms">tune</span>Disponibilidade e controlo</h5><dl class="rmbz-mg-data-grid">
                                    <div><dt>Download</dt><dd><?php echo $track['download_enabled']?'Ativo':'Desativado';?></dd></div><div><dt>Venda direta</dt><dd><?php echo $track['paid']?esc_html(imz_native_dashboard_money($track['paid_price']).' MT'):'Não ativa';?></dd></div><div><dt>Limite total</dt><dd><?php echo $track['total_limit']?esc_html(number_format_i18n($track['total_limit'])):'Sem limite';?></dd></div><div><dt>Limite diário</dt><dd><?php echo $track['daily_limit']?esc_html(number_format_i18n($track['daily_limit'])):'Sem limite';?></dd></div><div><dt>Países bloqueados</dt><dd><?php echo $track['blocked']?esc_html(implode(', ',$track['blocked'])):'Nenhum';?></dd></div><div><dt>Proteção digital</dt><dd><?php echo $track['protected']?'Ativa':'Não ativa';?></dd></div>
                                </dl></section>
                                <section><h5><span class="ms">account_balance</span>Monetização por download</h5><dl class="rmbz-mg-data-grid">
                                    <div><dt>Estado</dt><dd><?php echo esc_html($monet_label);?></dd></div><div><dt>Tarifa atual</dt><dd><?php echo esc_html(imz_native_dashboard_money($track['monet_rate']));?> MT / válido</dd></div><div><dt>Downloads válidos</dt><dd><?php echo esc_html(number_format_i18n($track['monet_valid']));?></dd></div><div><dt>Em verificação</dt><dd><?php echo esc_html(number_format_i18n($track['monet_pending_downloads']));?></dd></div><div><dt>Ganhos pendentes</dt><dd><?php echo esc_html(imz_native_dashboard_money($track['monet_pending']));?> MT</dd></div><div><dt>Pago na carteira</dt><dd><?php echo esc_html(imz_native_dashboard_money($track['artist_earnings']));?> MT</dd></div><div><dt>Eventos rejeitados</dt><dd><?php echo esc_html(number_format_i18n($track['monet_rejected']));?></dd></div><div><dt>Venda direta</dt><dd><?php echo esc_html(imz_native_dashboard_money($track['sales_total']));?> MT</dd></div>
                                </dl></section>
                                <section class="rmbz-mg-monetization-box <?php echo esc_attr($track['monet_status']);?>">
                                    <div class="rmbz-mg-monetization-head"><span class="ms"><?php echo $track['monet_status']==='active'?'verified':($track['monet_status']==='suspended'?'gpp_bad':'currency_exchange');?></span><div><h5>Monetização por download válido</h5><p><?php echo $track['monet_status']==='active'?'Ativa. A tarifa aplicada a cada evento fica guardada e não muda retroativamente.':($track['monet_status']==='suspended'?'Suspensa pela equipa. Os novos downloads não geram ganhos.':'Ativa esta faixa sem enviar links ou documentos novamente.');?></p></div></div>
                                    <?php if(!in_array($track['monet_status'],['active','suspended','archived'],true)&&$track['role']==='primary'&&$track['download_enabled']):?>
                                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php'));?>" class="rmbz-mg-monetization-form"><input type="hidden" name="action" value="rmbz_dm_activate_music"><input type="hidden" name="music_id" value="<?php echo (int)$track['id'];?>"><?php wp_nonce_field('rmbz_dm_activate_'.$track['id']);?><label><input type="checkbox" name="rights_confirmed" value="1" required><span>Confirmo que sou titular ou representante autorizado desta faixa principal.</span></label><label><input type="checkbox" name="terms_accepted" value="1" required><span>Aceito a validação antifraude, retenção e regras do Programa de Parceria.</span></label><button class="rmbz-mg-button primary"><span class="ms">paid</span>Ativar monetização</button></form>
                                    <?php elseif(!$track['download_enabled']):?><div class="rmbz-mg-monetization-note"><span class="ms">download_off</span>O download gratuito precisa ser ativado pela equipa.</div><?php endif;?>
                                </section>                                <section><h5><span class="ms">storefront</span>Lojas e ligações</h5>
                                    <div class="rmbz-mg-store-list">
                                        <?php if($track['youtube']):?><a href="<?php echo esc_url($track['youtube']);?>" target="_blank" rel="noopener"><span class="ms">play_circle</span>Ouvir</a><?php endif;?>
                                        <?php foreach($track['stores'] as $store):$store_name=(string)($store['name']??$store['store_key']??'Loja');$store_url=(string)($store['url']??'');?><?php if($store_url):?><a href="<?php echo esc_url($store_url);?>" target="_blank" rel="noopener"><span class="ms">storefront</span><?php echo esc_html($store_name);?></a><?php else:?><span><span class="ms">storefront</span><?php echo esc_html($store_name);?></span><?php endif;?><?php endforeach;?>
                                        <?php if(!$track['youtube']&&!$track['stores']):?><span class="muted">Nenhuma ligação de loja informada.</span><?php endif;?>
                                    </div>
                                </section>
                                <?php if($track['missing']):?><div class="rmbz-mg-missing"><span class="ms">assignment_late</span><div><strong>Informação por completar</strong><p><?php echo esc_html(implode(', ',$track['missing']));?>.</p></div></div><?php endif;?>
                            </div>
                        </details>
                    </article>
                    <?php endforeach; ?>
                </div>
                <div class="rmbz-mg-empty filtered" data-mg-empty hidden><span class="ms">search_off</span><h3>Nenhuma música corresponde ao filtro</h3><p>Altera a pesquisa ou seleciona outro estado.</p></div>
            <?php endif; ?>
        </section>

        <dialog class="rmbz-mg-boost-dialog" data-mg-boost-dialog>
            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" data-mg-boost-form data-balance="<?php echo esc_attr( $wallet_total ); ?>" data-price-per-day="<?php echo esc_attr( $price_per_day ); ?>">
                <input type="hidden" name="action" value="imz_artist_wallet_boost">
                <input type="hidden" name="music_id" value="" data-mg-boost-music-id>
                <input type="hidden" name="boost_request_key" value="<?php echo esc_attr( $boost_request_key ); ?>">
                <input type="hidden" name="boost_signature" value="<?php echo esc_attr( $boost_signature ); ?>">
                <?php wp_nonce_field( 'imz_artist_wallet_boost', 'imz_artist_boost_nonce' ); ?>
                <header class="rmbz-mg-boost-head">
                    <span class="rmbz-mg-boost-icon ms">campaign</span>
                    <div><span class="rmbz-mg-eyebrow">CAMPANHA DA MÚSICA</span><h3>Impulsionar <b data-mg-boost-title></b></h3><p data-mg-boost-state>Escolhe o período. A campanha começa imediatamente após o débito.</p></div>
                    <button type="button" class="rmbz-mg-dialog-close" data-mg-boost-close aria-label="Fechar"><span class="ms">close</span></button>
                </header>
                <div class="rmbz-mg-boost-body">
                    <section>
                        <div class="rmbz-mg-boost-section-title"><span class="ms">date_range</span><div><strong>Duração da campanha</strong><small>O mesmo período vale para todos os espaços.</small></div></div>
                        <div class="rmbz-mg-duration-grid">
                            <?php foreach ( imz_artist_boost_durations() as $days => $duration ): $cost = $price_per_day * $days; ?>
                                <label class="rmbz-mg-duration<?php echo $days === 7 ? ' selected' : ''; ?>">
                                    <input type="radio" name="boost_days" value="<?php echo (int)$days; ?>" data-cost="<?php echo esc_attr( $cost ); ?>" <?php checked( $days, 7 ); ?>>
                                    <span><b><?php echo esc_html( $duration['label'] ); ?></b><small><?php echo esc_html( $duration['description'] ); ?></small></span>
                                    <strong><?php echo esc_html( imz_native_dashboard_money( $cost ) ); ?> MT</strong>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </section>
                    <section>
                        <div class="rmbz-mg-boost-section-title"><span class="ms">auto_awesome</span><div><strong>Visibilidade incluída</strong><small>A música ganha prioridade enquanto a campanha estiver ativa.</small></div></div>
                        <div class="rmbz-mg-placement-grid">
                            <article><span class="ms">featured_play_list</span><div><strong>Posts patrocinados</strong><small>Entra nos espaços de Música Destacada.</small></div><span class="ms ok">check_circle</span></article>
                            <article><span class="ms">download</span><div><strong>Área de downloads</strong><small>Recebe exposição nas páginas de download.</small></div><span class="ms ok">check_circle</span></article>
                            <article><span class="ms">recommend</span><div><strong>Outras músicas</strong><small>Aparece com prioridade nas recomendações.</small></div><span class="ms ok">check_circle</span></article>
                            <article><span class="ms">verified</span><div><strong>Selo azul</strong><small>Mantém o marcador Impulsionado enquanto estiver ativa.</small></div><span class="ms ok">check_circle</span></article>
                        </div>
                    </section>
                </div>
                <footer class="rmbz-mg-boost-footer">
                    <div class="rmbz-mg-boost-wallet"><span class="ms">account_balance_wallet</span><div><small>Saldo da carteira</small><strong><?php echo esc_html( imz_native_dashboard_money( $wallet_total ) ); ?> MT</strong></div></div>
                    <div class="rmbz-mg-boost-total"><small>Total a debitar</small><strong data-mg-boost-total><?php echo esc_html( imz_native_dashboard_money( $price_per_day * 7 ) ); ?> MT</strong><span data-mg-boost-balance-status></span></div>
                    <div class="rmbz-mg-boost-actions"><button type="button" class="rmbz-mg-button ghost" data-mg-boost-close>Cancelar</button><button type="submit" class="rmbz-mg-button primary" data-mg-boost-submit><span class="ms">rocket_launch</span>Ativar campanha</button></div>
                </footer>
            </form>
        </dialog>
    </div>
    <?php
    return ob_get_clean();
}