<?php
// includes/email-manager.php

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

/**
 * ==========================================================================
 * 1. INICIALIZAR TABELA DE LOGS DE E-MAIL
 * ==========================================================================
 */
function rmbz_init_email_logs_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'rmbz_email_logs';
    
    if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) {
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            recipient_email varchar(100) NOT NULL,
            subject varchar(255) NOT NULL,
            body longtext NOT NULL,
            sent_date datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
            status varchar(20) DEFAULT 'sucesso' NOT NULL,
            is_read tinyint(1) DEFAULT 0 NOT NULL,
            is_cleared tinyint(1) DEFAULT 0 NOT NULL,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta( $sql );
    }
}
add_action('admin_init', 'rmbz_init_email_logs_table');

/**
 * [1.5.414] AUDIÊNCIA nos logs de email — quando o email do artista é o
 * MESMO da administração (caso real), o sino do artista mostrava os alertas
 * do sistema ("Novo Depósito Pendente", "Olá Equipa Financeira"…). A coluna
 * `audience` ('artist' | 'admin') separa-os de vez: marca-se na escrita e
 * o sino/painel só lê audience <> 'admin'. Migração + backfill do histórico.
 */
function rmbz_email_logs_install_audience() {
    if ( get_option( 'rmbz_email_logs_audience', '0' ) === '1' ) return;
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_email_logs';
    $col = $wpdb->get_var( $wpdb->prepare(
        "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = 'audience'", $t
    ) );
    if ( ! $col ) {
        $wpdb->query( "ALTER TABLE {$t} ADD COLUMN audience VARCHAR(12) NOT NULL DEFAULT 'artist'" );
    }
    // Backfill: marcar como 'admin' os alertas do sistema já gravados.
    $patterns = [
        "subject LIKE '%Novo Depósito Pendente%'",
        "subject LIKE '%Novo Pedido de Levantamento%'",
        "subject LIKE '%Novo Levantamento%'",
        "body LIKE '%Olá Equipa Financeira%'",
        "body LIKE '%Painel de Audições%'",
        "body LIKE '%Este email é automático. Para parar de o receber%'",
    ];
    $wpdb->query( "UPDATE {$t} SET audience = 'admin' WHERE " . implode( ' OR ', $patterns ) );
    update_option( 'rmbz_email_logs_audience', '1' );
}
add_action( 'init', 'rmbz_email_logs_install_audience', 6 );

function rmbz_log_sent_email($to, $subject, $body, $status, $audience = 'artist') {
    global $wpdb;
    $wpdb->insert(
        $wpdb->prefix . 'rmbz_email_logs',
        [
            'recipient_email' => $to,
            'subject' => $subject,
            'body' => $body,
            'sent_date' => current_time('mysql'),
            'status' => $status,
            // [1.5.414] 'admin' = alerta do sistema — NUNCA aparece no sino do artista.
            'audience' => ( $audience === 'admin' ) ? 'admin' : 'artist',
        ],
        ['%s', '%s', '%s', '%s', '%s', '%s']
    );
}

/**
 * [1.5.400] O sino 🔔 do site NÃO deve renderizar o tema do email (faixa
 * dourada, ™, ícone, rodapé) — alguns fluxos gravavam em rmbz_email_logs o
 * HTML COMPLETO construído por rmbz_build_html_email(), e o modal do sino
 * mostrava o email inteiro cortado. Este helper devolve apenas o CONTEÚDO:
 *   1) se o body não for um email completo → devolve tal e qual;
 *   2) emails novos → extrai os marcadores <!--RMBZ:INNER-->…<!--/RMBZ:INNER-->;
 *   3) emails antigos (sem marcadores) → apanha o cartão de conteúdo do template;
 *   4) último recurso → texto simples sem markup.
 */
function rmbz_bell_body_clean( $body ) {
    $body = (string) $body;
    if ( stripos( $body, '<!DOCTYPE' ) === false && stripos( $body, 'id="rmbz-body"' ) === false && stripos( $body, 'rmbz-shell' ) === false ) {
        return $body; // já é só conteúdo (rmbz_notify e afins)
    }
    if ( preg_match( '/<!--RMBZ:INNER-->(.*?)<!--\/RMBZ:INNER-->/s', $body, $m ) ) {
        return trim( $m[1] );
    }
    // Legado: conteúdo entre o cartão escuro e o divisor da assinatura.
    if ( preg_match( '/class="rmbz-card rmbz-pad"[^>]*>\s*<div[^>]*>(.*?)<\/div>\s*<\/td>\s*<\/tr>\s*<!-- ASSINATURA/s', $body, $m ) ) {
        return trim( $m[1] );
    }
    // Último recurso: só o texto (sem preheader/rodapé habituais do template).
    $text = wp_strip_all_tags( $body );
    $text = preg_replace( '/\s{2,}/', "\n", trim( $text ) );
    return nl2br( esc_html( $text ) );
}

/**
 * ==========================================================================
 * 2. REGISTAR O MENU E INTERFACE DE ADMINISTRAÇÃO PREMIUM
 * ==========================================================================
 */
// [1.6.348] Sem menu próprio — "Configuração de E-mails" passou a ser ABA em
// Configurações 1MZ For Artists ("📧 E-mails"), via rmbz_render_email_settings_body().

function rmbz_render_email_settings_body() {
    // [1.6.348] Vive como aba das Configurações → sub-abas internas em `etab`
    // (o `tab` pertence à página de Configurações).
    $active_tab = isset($_GET['etab']) ? sanitize_text_field($_GET['etab']) : 'settings';

    // Gravar configurações (Com wp_unslash para evitar as barras duplas \\ nas aspas)
    if ( $active_tab === 'settings' && isset($_POST['rmbz_save_emails']) && isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'rmbz_save_emails_nonce') ) {
        $settings = [
            'sender_name'          => sanitize_text_field(wp_unslash($_POST['sender_name'])),
            'sender_email'         => sanitize_email(wp_unslash($_POST['sender_email'])),
            'admin_notify_email'   => sanitize_email(wp_unslash($_POST['admin_notify_email'])),

            'subj_admin_new'       => sanitize_text_field(wp_unslash($_POST['subj_admin_new'])),
            'body_admin_new'       => wp_kses_post(wp_unslash($_POST['body_admin_new'])),

            'subj_artist_received' => sanitize_text_field(wp_unslash($_POST['subj_artist_received'])),
            'body_artist_received' => wp_kses_post(wp_unslash($_POST['body_artist_received'])),

            'subj_artist_approved' => sanitize_text_field(wp_unslash($_POST['subj_artist_approved'])),
            'body_artist_approved' => wp_kses_post(wp_unslash($_POST['body_artist_approved'])),

            'subj_artist_rejected' => sanitize_text_field(wp_unslash($_POST['subj_artist_rejected'])),
            'body_artist_rejected' => wp_kses_post(wp_unslash($_POST['body_artist_rejected'])),
        ];

        // [1.5.138] Gravar também todos os templates novos (welcome, deposit_*,
        // vip_*, referral_*, royalties, release_*). Iteramos a lista canónica
        // para não repetir a definição em vários sítios.
        if ( function_exists('rmbz_notifications_keys_list') ) {
            foreach ( rmbz_notifications_keys_list() as $key ) {
                $sk = 'subj_' . $key;
                $bk = 'body_' . $key;
                if ( isset($_POST[$sk]) ) {
                    $settings[$sk] = sanitize_text_field( wp_unslash($_POST[$sk]) );
                }
                if ( isset($_POST[$bk]) ) {
                    $settings[$bk] = wp_kses_post( wp_unslash($_POST[$bk]) );
                }
            }
        }

        update_option('rmbz_email_templates', $settings);
        echo '<div class="notice notice-success is-dismissible" style="border-left-color: #f0b90b;"><p><strong>Definições e Modelos de E-mail atualizados com sucesso!</strong></p></div>';
    }

    // [1.5.138] Os defaults base são os 4 originais. Os novos templates
    // têm os defaults em rmbz_notifications_default_templates() e são
    // injectados via rmbz_notifications_get_template() quando faltam.
    $tpl = get_option('rmbz_email_templates', [
        'sender_name'          => get_bloginfo('name'),
        'sender_email'         => get_option('admin_email'),
        'admin_notify_email'   => get_option('admin_email'),
        'subj_admin_new'       => '[{site_name}] NOVA SUBMISSÃO: {titulo_musica}',
        'body_admin_new'       => "Temos uma nova música para avaliar.\n\nArtista: {nome_artista}\nMúsica: {titulo_musica}\nGénero: {genero_musica}\n\nAceda ao painel para ouvir e avaliar.",
        'subj_artist_received' => '[{site_name}] Música Recebida: {titulo_musica}',
        'body_artist_received' => "Olá {nome_artista},\n\nRecebemos a sua obra '{titulo_musica}' com sucesso! A nossa equipa já está a analisar.\n\nFique atento a este e-mail, será notificado em breve com o resultado da nossa avaliação.",
        'subj_artist_approved' => 'PARABÉNS! Música Aprovada: {titulo_musica}',
        'body_artist_approved' => "Olá {nome_artista},\n\nÉ com prazer que informamos que a música '{titulo_musica}' foi aprovada!\n\nFoi gerado um contrato de produção. Aceda à sua conta na plataforma para ver o roteiro, o orçamento e começar o chat com a nossa equipa de produção.",
        'subj_artist_rejected' => 'Estado da sua música: {titulo_musica}',
        'body_artist_rejected' => "Olá {nome_artista},\n\nInfelizmente, desta vez a música '{titulo_musica}' não foi selecionada.\n\nFeedback da equipa:\n{motivo_rejeicao}\n\nNão desanime! Continue a trabalhar na sua arte e envie-nos novas músicas em breve."
    ]);
    ?>
    <style>
        .onemz-mail-wrap { max-width: 950px; margin: 20px 20px 20px 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        .onemz-mail-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
        .onemz-mail-header h1 { font-size: 26px; font-weight: 800; color: #1d2327; margin: 0; }
        .onemz-mail-card { background: #fff; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); padding: 25px; border: 1px solid #e2e8f0; margin-bottom: 25px; }
        .onemz-mail-card h3 { margin-top: 0; font-size: 18px; color: #1e293b; border-bottom: 2px solid #f8fafc; padding-bottom: 12px; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
        .onemz-input-group { margin-bottom: 20px; }
        .onemz-input-group label { display: block; font-weight: 600; color: #475569; margin-bottom: 8px; font-size: 14px; }
        .onemz-input-group input[type="text"], .onemz-input-group input[type="email"], .onemz-input-group textarea { width: 100%; padding: 12px 15px; border: 1px solid #cbd5e1; border-radius: 6px; background: #f8fafc; color: #0f172a; font-size: 14px; transition: 0.2s; box-shadow: inset 0 1px 2px rgba(0,0,0,0.02); }
        .onemz-input-group input:focus, .onemz-input-group textarea:focus { border-color: #f0b90b; outline: none; background: #fff; box-shadow: 0 0 0 3px rgba(240, 185, 11, 0.15); }
        .onemz-input-group .desc { font-size: 12px; color: #94a3b8; margin-top: 6px; display: block; }
        .onemz-mail-btn { background: #f0b90b; color: #000; border: none; padding: 12px 30px; font-size: 16px; font-weight: bold; border-radius: 6px; cursor: pointer; box-shadow: 0 4px 10px rgba(240, 185, 11, 0.3); transition: 0.2s; }
        .onemz-mail-btn:hover { background: #d4a000; transform: translateY(-1px); }
        .onemz-tag { background: #eff6ff; color: #2563eb; border: 1px solid #bfdbfe; padding: 4px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; display: inline-block; margin: 0 4px 8px 0; }
        .onemz-row { display: flex; gap: 20px; flex-wrap: wrap; }
        .onemz-col { flex: 1; min-width: 250px; }
    </style>

    <div class="onemz-mail-wrap">
        <div class="onemz-mail-header">
            <div>
                <h2 style="margin:6px 0 0 0;">📧 Configuração de E-mails</h2>
                <p style="margin: 5px 0 0 0; color: #64748b;">Gira como a plataforma comunica com os seus artistas.</p>
            </div>
        </div>

        <h2 class="nav-tab-wrapper" style="margin-bottom:25px; border-bottom: 1px solid #e2e8f0;">
            <a href="?page=rmbz-settings&tab=emails&etab=settings" class="nav-tab <?php echo $active_tab == 'settings' ? 'nav-tab-active' : ''; ?>" style="<?php if($active_tab=='settings') echo 'border-bottom-color:#f8f9f9; background:#fff;'; ?>">Modelos e Textos</a>
            <a href="?page=rmbz-settings&tab=emails&etab=logs" class="nav-tab <?php echo $active_tab == 'logs' ? 'nav-tab-active' : ''; ?>" style="<?php if($active_tab=='logs') echo 'border-bottom-color:#f8f9f9; background:#fff;'; ?>">Histórico de Envios</a>
        </h2>

        <?php if ($active_tab === 'settings'): ?>
            <div class="onemz-mail-card" style="border-left: 5px solid #3b82f6; background: linear-gradient(to right, #ffffff, #f8fafc);">
                <h3>💡 Etiquetas Inteligentes (Tags)</h3>
                <p style="color: #475569; font-size: 14px; margin-bottom: 15px;">Copie e cole estas etiquetas nos textos abaixo. O sistema irá substituí-las automaticamente pelos dados do artista:</p>
                <div>
                    <span class="onemz-tag">{site_name}</span>
                    <span class="onemz-tag">{nome_artista}</span>
                    <span class="onemz-tag">{titulo_musica}</span>
                    <span class="onemz-tag">{genero_musica}</span>
                    <span class="onemz-tag">{motivo_rejeicao}</span>
                </div>
            </div>

            <form method="post" action="">
                <?php wp_nonce_field('rmbz_save_emails_nonce', '_wpnonce'); ?>
                <input type="hidden" name="rmbz_save_emails" value="1">

                <div class="onemz-mail-card" style="border-top: 4px solid #f0b90b;">
                    <h3>⚙️ Identidade do Remetente (Quem envia)</h3>
                    <div class="onemz-row">
                        <div class="onemz-col onemz-input-group">
                            <label>Nome do Remetente Oficial</label>
                            <input type="text" name="sender_name" value="<?php echo esc_attr($tpl['sender_name'] ?? ''); ?>" placeholder="Ex: 1MZ Records">
                            <span class="desc">O nome que aparece em destaque na caixa de entrada do artista.</span>
                        </div>
                        <div class="onemz-col onemz-input-group">
                            <label>E-mail do Remetente</label>
                            <input type="email" name="sender_email" value="<?php echo esc_attr($tpl['sender_email'] ?? ''); ?>" placeholder="Ex: noreply@1musicmoz.com">
                            <span class="desc">O endereço que enviará o e-mail. Recomenda-se um e-mail do seu domínio.</span>
                        </div>
                    </div>
                </div>

                <div class="onemz-mail-card">
                    <h3>🔔 Notificações para a Administração</h3>
                    <div class="onemz-input-group">
                        <label>E-mail que recebe os avisos de novas músicas</label>
                        <input type="email" name="admin_notify_email" value="<?php echo esc_attr($tpl['admin_notify_email'] ?? ''); ?>">
                        <span class="desc">Para onde devemos enviar o alerta quando um artista envia algo?</span>
                    </div>
                    <div class="onemz-input-group">
                        <label>Assunto do Alerta</label>
                        <input type="text" name="subj_admin_new" value="<?php echo esc_attr($tpl['subj_admin_new'] ?? ''); ?>">
                    </div>
                    <div class="onemz-input-group">
                        <label>Corpo da Mensagem</label>
                        <textarea name="body_admin_new" rows="4"><?php echo esc_textarea($tpl['body_admin_new'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="onemz-mail-card" style="border-top: 4px solid #3498db;">
                    <h3>📨 E-mail 1: Recebimento de Música (Para o Artista)</h3>
                    <div class="onemz-input-group">
                        <label>Assunto do E-mail</label>
                        <input type="text" name="subj_artist_received" value="<?php echo esc_attr($tpl['subj_artist_received'] ?? ''); ?>">
                    </div>
                    <div class="onemz-input-group">
                        <label>Corpo da Mensagem</label>
                        <textarea name="body_artist_received" rows="5"><?php echo esc_textarea($tpl['body_artist_received'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="onemz-mail-card" style="border-top: 4px solid #2ecc71;">
                    <h3>🎉 E-mail 2: Música Aprovada (Para o Artista)</h3>
                    <div class="onemz-input-group">
                        <label>Assunto do E-mail</label>
                        <input type="text" name="subj_artist_approved" value="<?php echo esc_attr($tpl['subj_artist_approved'] ?? ''); ?>">
                    </div>
                    <div class="onemz-input-group">
                        <label>Corpo da Mensagem</label>
                        <textarea name="body_artist_approved" rows="5"><?php echo esc_textarea($tpl['body_artist_approved'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="onemz-mail-card" style="border-top: 4px solid #e74c3c;">
                    <h3>❌ E-mail 3: Música Rejeitada (Para o Artista)</h3>
                    <div class="onemz-input-group">
                        <label>Assunto do E-mail</label>
                        <input type="text" name="subj_artist_rejected" value="<?php echo esc_attr($tpl['subj_artist_rejected'] ?? ''); ?>">
                    </div>
                    <div class="onemz-input-group">
                        <label>Corpo da Mensagem (Use a tag {motivo_rejeicao} para mostrar o feedback)</label>
                        <textarea name="body_artist_rejected" rows="5"><?php echo esc_textarea($tpl['body_artist_rejected'] ?? ''); ?></textarea>
                    </div>
                </div>

                <?php
                /* [1.5.138] Renderização dinâmica das novas secções de notificação.
                   Cada key vem de rmbz_notifications_keys_meta() e o template
                   actual é resolvido por rmbz_notifications_get_template() (que
                   cai no default se admin nunca editou). Agrupadas por
                   categoria (Onboarding / Planos VIP / Convites / Distribuição).
                   Cor da borda do card consoante o grupo para leitura rápida. */
                if ( function_exists('rmbz_notifications_keys_meta') ) {
                    $meta_all = rmbz_notifications_keys_meta();

                    // Agrupar por categoria
                    $groups = [];
                    foreach ( $meta_all as $key => $m ) {
                        $g = $m['group'] ?? 'Outros';
                        if ( ! isset($groups[$g]) ) $groups[$g] = [];
                        $groups[$g][$key] = $m;
                    }

                    // Cores por grupo
                    $group_colors = [
                        'Onboarding'   => '#3b82f6',  // azul
                        'Planos VIP'   => '#f0b90b',  // dourado
                        'Convites'     => '#10b981',  // verde
                        'Distribuição' => '#a855f7',  // roxo
                    ];

                    foreach ( $groups as $gname => $gkeys ):
                        $gcolor = $group_colors[$gname] ?? '#94a3b8';
                ?>
                    <div class="onemz-mail-card" style="border-top: 4px solid <?php echo esc_attr($gcolor); ?>;">
                        <h3 style="color: <?php echo esc_attr($gcolor); ?>;">
                            <?php echo esc_html($gname); ?>
                            <span style="font-size:12px;font-weight:400;color:#94a3b8;margin-left:8px;">
                                (<?php echo count($gkeys); ?> notificações)
                            </span>
                        </h3>

                        <?php foreach ( $gkeys as $key => $m ):
                            $subj_val = rmbz_notifications_get_template( $key, 'subj' );
                            $body_val = rmbz_notifications_get_template( $key, 'body' );
                            $vars     = $m['vars'] ?? [];
                        ?>
                            <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:18px;margin-bottom:14px;">
                                <div style="display:flex;align-items:center;gap:10px;margin-bottom:6px;">
                                    <span style="font-size:20px;"><?php echo esc_html($m['icon'] ?? '✉'); ?></span>
                                    <strong style="font-size:14px;color:#1e293b;"><?php echo esc_html($m['label']); ?></strong>
                                </div>
                                <p style="margin:0 0 12px 0;font-size:12px;color:#64748b;line-height:1.5;">
                                    <?php echo esc_html($m['desc']); ?>
                                </p>

                                <?php if ( ! empty($vars) ): ?>
                                    <div style="margin-bottom:12px;">
                                        <span style="font-size:11px;color:#94a3b8;text-transform:uppercase;letter-spacing:0.05em;font-weight:600;margin-right:6px;">Variáveis:</span>
                                        <?php foreach ( $vars as $v ): ?>
                                            <code style="background:#eff6ff;color:#2563eb;border:1px solid #bfdbfe;padding:2px 7px;border-radius:4px;font-size:11px;margin-right:3px;">{<?php echo esc_html($v); ?>}</code>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>

                                <div class="onemz-input-group" style="margin-bottom:10px;">
                                    <label style="font-size:12px;">Assunto</label>
                                    <input type="text" name="subj_<?php echo esc_attr($key); ?>" value="<?php echo esc_attr($subj_val); ?>" style="font-size:13px;">
                                </div>
                                <div class="onemz-input-group" style="margin-bottom:0;">
                                    <label style="font-size:12px;">Corpo da Mensagem</label>
                                    <textarea name="body_<?php echo esc_attr($key); ?>" rows="5" style="font-size:13px;"><?php echo esc_textarea($body_val); ?></textarea>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php
                    endforeach;
                }
                ?>

                <div style="margin-top: 30px;">
                    <button type="submit" class="onemz-mail-btn">💾 Salvar Configurações de E-mail</button>
                </div>
            </form>

        <?php else: ?>

            <div class="onemz-mail-card" style="padding: 0; overflow: hidden;">
                <?php
                global $wpdb;
                $table_logs = $wpdb->prefix . 'rmbz_email_logs';
                
                // SISTEMA DE PAGINAÇÃO DE EMAILS
                $per_page = 15;
                $paged = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
                $offset = ($paged - 1) * $per_page;
                
                $total_logs = $wpdb->get_var("SELECT COUNT(id) FROM {$table_logs}");
                $total_pages = ceil($total_logs / $per_page);
                
                $logs = $wpdb->get_results("SELECT * FROM {$table_logs} ORDER BY sent_date DESC LIMIT {$per_page} OFFSET {$offset}");
                ?>
                <table class="wp-list-table widefat fixed striped" style="border:none;">
                    <thead>
                        <tr>
                            <th style="width:15%; padding:15px;">Data</th>
                            <th style="width:25%; padding:15px;">Destinatário</th>
                            <th style="width:35%; padding:15px;">Assunto</th>
                            <th style="width:10%; padding:15px;">Estado</th>
                            <th style="width:15%; padding:15px;">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($logs)): ?>
                            <tr><td colspan="5" style="text-align:center; padding:40px; color:#888; font-size:14px;">Nenhum e-mail foi enviado ou registado ainda.</td></tr>
                        <?php else: ?>
                            <?php foreach($logs as $log):
                                // [1.6.368] Estado claro: 'so_sino' = NÃO enviou email (só o sino
                                // do artista). Não é erro → azul, não vermelho.
                                $is_placeholder = ( stripos( (string) $log->recipient_email, '@1mz.local' ) !== false );
                                if ( $log->status === 'sucesso' ) {
                                    $color = '#2ecc71'; $estado_label = 'Enviado';
                                } elseif ( $log->status === 'so_sino' ) {
                                    $color = '#6366f1'; $estado_label = 'Só no sino';
                                } else {
                                    $color = '#e74c3c'; $estado_label = 'Falhou';
                                }
                                // Destinatário legível: placeholders não têm email real.
                                if ( $is_placeholder ) {
                                    $dest_display = str_replace( '@1mz.local', '', (string) $log->recipient_email ) . ' — sem email (só sino)';
                                } else {
                                    $dest_display = (string) $log->recipient_email;
                                }
                            ?>
                                <tr>
                                    <td style="padding:15px;"><?php echo date('d/m/Y H:i', strtotime($log->sent_date)); ?></td>
                                    <td style="padding:15px; color:<?php echo $is_placeholder ? '#94a3b8' : '#0f172a'; ?>;"><?php echo esc_html($dest_display); ?></td>
                                    <td style="padding:15px; font-weight:600; color:#1e293b;"><?php echo esc_html($log->subject); ?></td>
                                    <td style="padding:15px;"><span style="background:<?php echo $color; ?>; color:#fff; padding:4px 10px; border-radius:20px; font-size:11px; font-weight:bold; letter-spacing:0.3px;"><?php echo esc_html($estado_label); ?></span></td>
                                    <td style="padding:15px;">
                                        <button onclick="showEmailPreview(<?php echo $log->id; ?>)" class="button">Ver Mensagem</button>
                                        <template id="email-content-<?php echo $log->id; ?>"><?php echo $log->body; ?></template>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                
                <?php if ($total_pages > 1): ?>
                    <div style="padding: 20px; background: #f8fafc; border-top: 1px solid #e2e8f0; text-align: right;">
                        <span style="color:#64748b; font-size:13px; margin-right:10px;">Página <?php echo $paged; ?> de <?php echo $total_pages; ?>:</span>
                        <?php
                        $base_url = admin_url('admin.php?page=rmbz-settings&tab=emails&etab=logs');
                        for ($i = 1; $i <= $total_pages; $i++) {
                            $active = ($i == $paged) ? 'background:#3b82f6; color:#fff; border-color:#3b82f6;' : 'background:#fff; color:#475569; border-color:#cbd5e1;';
                            echo '<a href="' . esc_url(add_query_arg('paged', $i, $base_url)) . '" style="display:inline-block; padding:5px 12px; margin-left:5px; border:1px solid; border-radius:4px; text-decoration:none; font-size:13px; font-weight:600; transition:0.2s; ' . $active . '">' . $i . '</a>';
                        }
                        ?>
                    </div>
                <?php endif; ?>
            </div>

            <div id="emailPreviewModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.85); z-index:999999; justify-content:center; align-items:center;">
                <div style="background:#fff; width:95%; max-width:800px; height:85vh; border-radius:12px; display:flex; flex-direction:column; overflow:hidden; box-shadow: 0 15px 50px rgba(0,0,0,0.5);">
                    <div style="padding:20px 25px; background:#f8fafc; border-bottom:1px solid #e2e8f0; display:flex; justify-content:space-between; align-items:center;">
                        <h3 style="margin:0; font-size:18px; color:#0f172a;">Visualização do E-mail</h3>
                        <button onclick="document.getElementById('emailPreviewModal').style.display='none'" style="background:none; border:none; color:#94a3b8; font-size:24px; cursor:pointer;">&times;</button>
                    </div>
                    <div style="flex:1; padding:0; background:#ddd;">
                        <iframe id="emailPreviewIframe" style="width:100%; height:100%; border:none; background:#fff;"></iframe>
                    </div>
                </div>
            </div>
            <script>
            function showEmailPreview(id) {
                var content = document.getElementById('email-content-'+id).innerHTML;
                var iframe = document.getElementById('emailPreviewIframe');
                iframe.srcdoc = content;
                document.getElementById('emailPreviewModal').style.display = 'flex';
            }
            </script>

        <?php endif; ?>
    </div>
    <?php
}
/**
 * ==========================================================================
 * 3. FUNÇÃO BASE: DESIGN DO E-MAIL (HTML GLOBAL VIP)
 * ==========================================================================
 */
/**
 * [1.6.370] Template de email Material 3 Expressive.
 *
 * Layout em TABELA com estilos INLINE (sobrevive ao stripping de <style> do
 * Gmail/Outlook) + um <style> de progressive-enhancement (dark-mode, hover).
 * Formas grandes e arredondadas, superfície tonal e faixa de marca dourada —
 * coerente com o tema VIP da 1MZ. Opcional: passar $opts['emoji'] / $opts['eyebrow'].
 *
 * @param string $content  Corpo (HTML simples ou texto com \n já em <br>/<p>).
 * @param string $custom_sender_name Nome de marca a mostrar.
 * @param array  $opts      ['emoji' => string, 'eyebrow' => string]
 */
/**
 * [1.5.398] Nome da marca seguro para email: o "™" herdava o tamanho do
 * título (25px/800) e nalguns Android era desenhado como glifo emoji gigante
 * a "sair para fora". Fica pequeno, sobrescrito e com apresentação de TEXTO
 * forçada (U+FE0E) para nunca virar emoji.
 */
function rmbz_email_brand_html( $site_name, $sup_size = 12 ) {
    $safe = esc_html( $site_name );
    // &#xFE0E; = variation selector de texto (impede render como emoji).
    $sup  = '<span style="font-size:' . (int) $sup_size . 'px; line-height:1; vertical-align:top; font-weight:700;">&trade;&#xFE0E;</span>';
    return str_replace( [ '™', '&trade;', 'â„¢' ], $sup, $safe );
}

/**
 * [1.5.398] Template reconstruído — versão robusta (só tabelas aninhadas +
 * estilos inline, à prova de Gmail/Outlook mobile) com estética Material 3:
 * hero dourado com "icon tile" em célula de tabela (o emoji nunca transborda),
 * cartão tonal escuro, cantos 28px e pill expressiva no rodapé.
 */
function rmbz_build_html_email( $content, $custom_sender_name = '', $opts = [] ) {
    $site_name = !empty($custom_sender_name) ? $custom_sender_name : get_bloginfo('name');
    $year      = date('Y');
    $brand     = rmbz_email_brand_html( $site_name, 12 );
    $brand_sm  = rmbz_email_brand_html( $site_name, 9 );

    // Garante parágrafos espaçados a partir do conteúdo (texto ou HTML leve).
    $body_html = ( strpos( $content, '<p' ) !== false || strpos( $content, '<table' ) !== false )
        ? wp_kses_post( $content )
        : wpautop( wp_kses_post( $content ) );

    // Emoji "herói": vem em $opts, senão tenta extrair o 1.º emoji do conteúdo.
    $emoji = isset( $opts['emoji'] ) ? $opts['emoji'] : '';
    if ( $emoji === '' && preg_match( '/[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}\x{2B00}-\x{2BFF}\x{23E9}-\x{23FA}\x{2705}\x{274C}\x{26A0}]/u', wp_strip_all_tags( $content ), $m ) ) {
        $emoji = $m[0];
    }
    if ( $emoji === '' ) $emoji = '🔔';
    $eyebrow = isset( $opts['eyebrow'] ) ? $opts['eyebrow'] : 'Notificação';

    ob_start();
    ?>
    <!DOCTYPE html>
    <html lang="pt" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="color-scheme" content="dark">
        <meta name="supported-color-schemes" content="dark">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!--[if mso]><noscript><xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml></noscript><![endif]-->
        <title><?php echo esc_html($site_name); ?></title>
        <style>
            /* Reset defensivo — clientes móveis. */
            body, table, td { margin:0; padding:0; }
            table { border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt; }
            img { border:0; outline:none; text-decoration:none; -ms-interpolation-mode:bicubic; }
            a { color:#f7c948; }
            .rmbz-card a { color:#f7c948; }
            /* iOS auto-links (telefones/datas) na nossa cor, não azul. */
            .rmbz-card a[x-apple-data-detectors] { color:#f7c948 !important; text-decoration:none !important; }
            u + #rmbz-body a { color:#f7c948; }
            @media (max-width: 620px) {
                .rmbz-shell { width:100% !important; }
                .rmbz-pad { padding-left:20px !important; padding-right:20px !important; }
                .rmbz-hero-pad { padding:28px 20px 24px !important; }
                .rmbz-brand { font-size:21px !important; }
            }
        </style>
    </head>
    <body id="rmbz-body" style="margin:0; padding:0; background:#0d0d10; -webkit-font-smoothing:antialiased; word-spacing:normal; font-family:'Google Sans',Roboto,-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;">
        <!-- preheader (escondido) -->
        <div style="display:none; max-height:0; overflow:hidden; opacity:0; color:transparent; mso-hide:all;">
            <?php echo esc_html( wp_trim_words( wp_strip_all_tags( $content ), 16, '…' ) ); ?>
        </div>
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#0d0d10" style="background:#0d0d10;">
            <tr>
                <td align="center" style="padding:24px 12px;">
                    <table role="presentation" class="rmbz-shell" width="600" cellpadding="0" cellspacing="0" border="0" style="width:600px; max-width:600px;">

                        <!-- HERO / FAIXA DE MARCA (M3: container tonal dourado) -->
                        <tr>
                            <td class="rmbz-hero-pad" align="center" bgcolor="#f0b90b" style="background:#f0b90b; background:linear-gradient(135deg,#ffd86b 0%,#f0b90b 48%,#e0a106 100%); border-radius:28px 28px 0 0; padding:34px 28px 28px;">
                                <!-- Icon tile: célula de tabela com altura fixa — o emoji NUNCA sai fora. -->
                                <table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin:0 auto;">
                                    <tr>
                                        <td width="64" height="64" align="center" valign="middle" bgcolor="#d9a606"
                                            style="width:64px; height:64px; border-radius:20px; background:rgba(0,0,0,0.16); font-size:28px; line-height:64px; mso-line-height-rule:exactly; text-align:center;">
                                            <span style="font-size:28px; line-height:64px;"><?php echo $emoji; // emoji literal ?></span>
                                        </td>
                                    </tr>
                                </table>
                                <div style="margin-top:14px; font-size:11px; letter-spacing:3px; text-transform:uppercase; color:#3a2c00; font-weight:700;"><?php echo esc_html( $eyebrow ); ?></div>
                                <div class="rmbz-brand" style="margin-top:6px; font-size:24px; line-height:1.25; color:#1a1400; font-weight:800; letter-spacing:-0.3px;"><?php echo $brand; ?></div>
                            </td>
                        </tr>

                        <!-- CARTÃO DE CONTEÚDO (M3: surface escura) -->
                        <tr>
                            <td class="rmbz-card rmbz-pad" bgcolor="#1c1c22" style="background:#1c1c22; padding:32px 30px 26px; font-size:16px; line-height:1.7; color:#e8e8ee;">
                                <div style="font-size:16px; line-height:1.7; color:#e8e8ee;">
                                    <!--RMBZ:INNER--><?php echo $body_html; ?><!--/RMBZ:INNER-->
                                </div>
                            </td>
                        </tr>

                        <!-- ASSINATURA / DIVISOR -->
                        <tr>
                            <td class="rmbz-card rmbz-pad" bgcolor="#1c1c22" style="background:#1c1c22; padding:0 30px 26px; border-radius:0 0 28px 28px;">
                                <div style="border-top:1px solid #2c2c34; padding-top:16px; font-size:13px; line-height:1.6; color:#9a9aa6;">
                                    Com carinho,<br>
                                    <span style="color:#f0b90b; font-weight:700;"><?php echo $brand_sm; ?></span>
                                </div>
                            </td>
                        </tr>

                        <!-- RODAPÉ -->
                        <tr>
                            <td align="center" style="padding:20px 24px 4px;">
                                <div style="font-size:12px; line-height:1.6; color:#6b6b76;">
                                    &copy; <?php echo esc_html($year); ?> <?php echo $brand_sm; ?> · Todos os direitos reservados.<br>
                                    Email automático — não é necessário responder.
                                </div>
                            </td>
                        </tr>

                        <!-- pill expressiva M3 no fundo (célula com fundo, não div flutuante) -->
                        <tr>
                            <td align="center" style="padding:8px 24px 22px;">
                                <table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin:0 auto;">
                                    <tr><td width="54" height="5" bgcolor="#f0b90b" style="width:54px; height:5px; border-radius:99px; background:#f0b90b; font-size:0; line-height:0;">&nbsp;</td></tr>
                                </table>
                            </td>
                        </tr>

                    </table>
                </td>
            </tr>
        </table>
    </body>
    </html>
    <?php
    return ob_get_clean();
}

function rmbz_replace_email_tags($text, $data_array) {
    foreach ($data_array as $tag => $value) {
        $text = str_replace('{' . $tag . '}', (string)($value ?? ''), (string)$text);
    }
    return $text;
}

/**
 * ==========================================================================
 * 4. MOTORES DE ENVIO DE E-MAIL (Músicas, Submissões e Projetos)
 * ==========================================================================
 */

function onemz_send_submission_notification( $submission_id ) {
    global $wpdb;
    $sub = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}rmbz_artist_submissions WHERE id = %d", $submission_id) );
    if ( !$sub ) return false;

    $artist = $wpdb->get_row( $wpdb->prepare("SELECT user_email, user_nome FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $sub->artist_telemovel) );
    $artist_email = $artist ? $artist->user_email : '';
    $artist_name  = $artist ? $artist->user_nome : 'Artista';
    
    $tpl = get_option('rmbz_email_templates');
    
    $sender_name = !empty($tpl['sender_name']) ? $tpl['sender_name'] : get_bloginfo('name');
    $sender_email = is_email($tpl['sender_email'] ?? '') ? $tpl['sender_email'] : get_option('admin_email');
    $admin_notify_email = is_email($tpl['admin_notify_email'] ?? '') ? $tpl['admin_notify_email'] : get_option('admin_email');

    $tags = [
        'site_name' => $sender_name,
        'nome_artista' => $artist_name,
        'titulo_musica' => $sub->music_title,
        'genero_musica' => $sub->music_genre,
        'motivo_rejeicao' => ''
    ];

    $headers = ['Content-Type: text/html; charset=UTF-8'];
    $final_headers = array_merge($headers, ['From: ' . $sender_name . ' <' . $sender_email . '>']);

    // 1. Notificar Artista & Gravar Log
    if ( is_email($artist_email) && strpos( (string)$artist_email, '@1mz.local' ) === false ) {
        $subj = rmbz_replace_email_tags($tpl['subj_artist_received'] ?? '', $tags);
        $body = rmbz_replace_email_tags($tpl['body_artist_received'] ?? '', $tags);
        $html_body = rmbz_build_html_email($body, $sender_name);
        
        $sent = wp_mail( $artist_email, $subj, $html_body, $final_headers );
        rmbz_log_sent_email($artist_email, $subj, $html_body, $sent ? 'sucesso' : 'falha');
    }

    // 2. Notificar Admin & Gravar Log
    if ( is_email($admin_notify_email) ) {
        $subj_admin = rmbz_replace_email_tags($tpl['subj_admin_new'] ?? '', $tags);
        $body_admin = rmbz_replace_email_tags($tpl['body_admin_new'] ?? '', $tags);
        $body_admin .= "\n\n<a href='".admin_url('admin.php?page=rmbz-dashboard')."' class='btn'>Ver Painel de Audições</a>";
        $html_body_admin = rmbz_build_html_email($body_admin, $sender_name);
        
        $sent_admin = wp_mail( $admin_notify_email, $subj_admin, $html_body_admin, $final_headers );
        rmbz_log_sent_email($admin_notify_email, $subj_admin, $html_body_admin, $sent_admin ? 'sucesso' : 'falha', 'admin');
        return $sent_admin;
    }
    return false;
}

function onemz_send_contract_notification( $project_id ) {
    global $wpdb;
    $proj = $wpdb->get_row( $wpdb->prepare("SELECT p.*, s.music_title FROM {$wpdb->prefix}rmbz_artist_projects p JOIN {$wpdb->prefix}rmbz_artist_submissions s ON p.submission_id = s.id WHERE p.id = %d", $project_id) );
    if ( !$proj ) return false;

    $artist = $wpdb->get_row( $wpdb->prepare("SELECT user_email, user_nome FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $proj->artist_telemovel) );
    $artist_email = $artist ? $artist->user_email : '';
    
    if ( ! is_email($artist_email) || strpos( (string)$artist_email, '@1mz.local' ) !== false ) return false;

    $tpl = get_option('rmbz_email_templates');
    $sender_name = !empty($tpl['sender_name']) ? $tpl['sender_name'] : get_bloginfo('name');
    $sender_email = is_email($tpl['sender_email'] ?? '') ? $tpl['sender_email'] : get_option('admin_email');
    
    $tags = [
        'site_name' => $sender_name,
        'nome_artista' => $artist ? $artist->user_nome : 'Artista',
        'titulo_musica' => $proj->music_title,
        'genero_musica' => '',
        'motivo_rejeicao' => ''
    ];

    $subj = rmbz_replace_email_tags($tpl['subj_artist_approved'] ?? '', $tags);
    $body = rmbz_replace_email_tags($tpl['body_artist_approved'] ?? '', $tags);
    $body .= "\n\n<a href='".home_url('/minha-conta/')."' class='btn'>Aceder à Minha Conta</a>";
    
    $html_body = rmbz_build_html_email($body, $sender_name);
    $final_headers = ['Content-Type: text/html; charset=UTF-8', 'From: ' . $sender_name . ' <' . $sender_email . '>'];
    
    $sent = wp_mail( $artist_email, $subj, $html_body, $final_headers );
    rmbz_log_sent_email($artist_email, $subj, $html_body, $sent ? 'sucesso' : 'falha');
    
    return $sent;
}

function onemz_send_rejection_notification( $submission_id, $reason ) {
    global $wpdb;
    $sub = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}rmbz_artist_submissions WHERE id = %d", $submission_id) );
    if ( !$sub ) return false;

    $artist = $wpdb->get_row( $wpdb->prepare("SELECT user_email, user_nome FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel = %s", $sub->artist_telemovel) );
    $artist_email = $artist ? $artist->user_email : '';

    if ( ! is_email($artist_email) || strpos( (string)$artist_email, '@1mz.local' ) !== false ) return false;

    $tpl = get_option('rmbz_email_templates');
    $sender_name = !empty($tpl['sender_name']) ? $tpl['sender_name'] : get_bloginfo('name');
    $sender_email = is_email($tpl['sender_email'] ?? '') ? $tpl['sender_email'] : get_option('admin_email');
    
    $tags = [
        'site_name' => $sender_name,
        'nome_artista' => $artist ? $artist->user_nome : 'Artista',
        'titulo_musica' => $sub->music_title,
        'genero_musica' => $sub->music_genre,
        'motivo_rejeicao' => $reason
    ];

    $subj = rmbz_replace_email_tags($tpl['subj_artist_rejected'] ?? '', $tags);
    $body = rmbz_replace_email_tags($tpl['body_artist_rejected'] ?? '', $tags);
    
    $html_body = rmbz_build_html_email($body, $sender_name);
    $final_headers = ['Content-Type: text/html; charset=UTF-8', 'From: ' . $sender_name . ' <' . $sender_email . '>'];
    
    $sent = wp_mail( $artist_email, $subj, $html_body, $final_headers );
    rmbz_log_sent_email($artist_email, $subj, $html_body, $sent ? 'sucesso' : 'falha');
    
    return $sent;
}

/**
 * ==========================================================================
 * 5. ALERTAS DE DEPÓSITO (ADMINISTRADOR E ARTISTA)
 * ==========================================================================
 */

// 1. Alerta para a Administração
function rmbz_send_admin_deposit_alert($user_name, $amount, $method, $transaction_id, $deposit_id = 0) {
    $admin_email = 'jaimemetano@gmail.com'; // O e-mail que recebe os alertas
    
    // PUXAR CONFIGURAÇÕES DO REMETENTE
    $tpl = get_option('rmbz_email_templates');
    $sender_name = !empty($tpl['sender_name']) ? $tpl['sender_name'] : get_bloginfo('name');
    $sender_email = is_email($tpl['sender_email'] ?? '') ? $tpl['sender_email'] : get_option('admin_email');
    
    // Formatar o ID da Base de Dados para ter 6 dígitos (ex: 15 vira 000015)
    $formatted_id = str_pad($deposit_id, 6, '0', STR_PAD_LEFT);
    
    // NOVO ASSUNTO COM O ID DE 6 DÍGITOS
    $subject = "💰 Novo Depósito Pendente: ID - {$formatted_id} ({$amount} MT)";
    
    $body = "Olá Equipa Financeira,\n\n";
    $body .= "Um novo pedido de depósito acabou de entrar no sistema e aguarda aprovação.\n\n";
    $body .= "📋 DADOS DO DEPÓSITO:\n";
    $body .= "- ID do Sistema: $formatted_id\n";
    $body .= "- Artista: $user_name\n";
    $body .= "- Valor: $amount MT\n";
    $body .= "- Método: $method\n";
    $body .= "- Comprovativo/ID: $transaction_id\n\n";
    $body .= "Aceda ao Painel de Administração do WordPress para rever o comprovativo e Aprovar ou Rejeitar.\n";
    
    if ( function_exists('rmbz_build_html_email') ) {
        $html_body = rmbz_build_html_email($body, $sender_name);
        $headers = ['Content-Type: text/html; charset=UTF-8', 'From: ' . $sender_name . ' <' . $sender_email . '>'];
    } else {
        $html_body = $body;
        $headers = ['From: ' . $sender_name . ' <' . $sender_email . '>'];
    }
    
    $sent = wp_mail($admin_email, $subject, $html_body, $headers);
    
    if (function_exists('rmbz_log_sent_email')) {
        rmbz_log_sent_email($admin_email, $subject, $html_body, $sent ? 'sucesso' : 'falha', 'admin');
    }
}

// 2. Alerta para o Artista
function rmbz_send_user_deposit_status($to_email, $user_name, $amount, $status, $reason = '') {
    if ( empty($to_email) || strpos($to_email, '@1mz.local') !== false ) return; 
    
    // PUXAR CONFIGURAÇÕES DO REMETENTE
    $tpl = get_option('rmbz_email_templates');
    $sender_name = !empty($tpl['sender_name']) ? $tpl['sender_name'] : get_bloginfo('name');
    $sender_email = is_email($tpl['sender_email'] ?? '') ? $tpl['sender_email'] : get_option('admin_email');
    
    $is_approved = ($status === 'aprovado');
    $subject = $is_approved ? '✅ Depósito Aprovado com Sucesso!' : '❌ Depósito Rejeitado';
    
    $body = "Olá $user_name,\n\n";
    if ( $is_approved ) {
        $body .= "Temos boas notícias! O seu depósito no valor de {$amount} MT foi APROVADO.\n\n";
        $body .= "O saldo já está disponível na sua Carteira Principal e pode usá-lo para ativar a sua subscrição VIP ou outros serviços.\n\n";
    } else {
        $body .= "Infelizmente, o seu pedido de depósito de {$amount} MT foi REJEITADO.\n\n";
        if ( !empty($reason) ) { $body .= "Motivo: $reason\n\n"; }
        $body .= "Por favor, verifique se enviou o comprovativo correto ou contacte o nosso suporte.\n\n";
    }
    $body .= "Um abraço,\nA Equipa " . $sender_name;
    
    if ( function_exists('rmbz_build_html_email') ) {
        $html_body = rmbz_build_html_email($body, $sender_name);
        $headers = ['Content-Type: text/html; charset=UTF-8', 'From: ' . $sender_name . ' <' . $sender_email . '>'];
    } else {
        $html_body = $body;
        $headers = ['From: ' . $sender_name . ' <' . $sender_email . '>'];
    }
    
    $sent = wp_mail($to_email, $subject, $html_body, $headers);
    
    if (function_exists('rmbz_log_sent_email')) {
        rmbz_log_sent_email($to_email, $subject, $html_body, $sent ? 'sucesso' : 'falha');
    }
}

/**
 * ============================================================================
 * [FEAT 1.6.21] EMAIL — RESUMO DE IMPORT APROVADO
 *
 * Disparado quando o admin aprova um import. Envia para jaimemetano@gmail.com
 * (o admin) um sumário do que aconteceu:
 *   - Período + total bruto + total distribuído (líquido)
 *   - Top 10 artistas que mais ganharam
 *   - Detalhes do log (file hash, processadas, erros)
 *   - Link directo para o admin do plugin
 *
 * Não substitui o sino interno — é só para ti teres registo no email sem
 * precisares de entrar no admin.
 * ============================================================================
 */
function rmbz_send_admin_import_approved_summary( $log, $credits_by_user, $artists = [] ) {
    if ( empty($log) || ! is_object($log) ) return;

    $admin_email = 'jaimemetano@gmail.com';
    $tpl         = get_option('rmbz_email_templates');
    $sender_name = ! empty($tpl['sender_name']) ? $tpl['sender_name'] : get_bloginfo('name');
    $sender_email = is_email($tpl['sender_email'] ?? '') ? $tpl['sender_email'] : get_option('admin_email');

    // Construir label PT-PT do período (ex: "Janeiro 2026")
    $period_label = $log->reporting_period ?? '';
    if ( ! empty($period_label) && preg_match('/^(\d{4})-(\d{2})$/', $period_label, $pm) ) {
        $names = ['', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
                  'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
        $mo = (int) $pm[2];
        if ( isset( $names[$mo] ) ) {
            $period_label = $names[$mo] . ' ' . $pm[1];
        }
    }

    // Stats do log
    $total_bruto_usd = (float) ( $log->total_amount_usd ?? 0 );
    $total_distrib   = array_sum( (array) $credits_by_user );
    $processed       = (int) ( $log->processed_rows ?? 0 );
    $unclaimed       = (int) ( $log->unclaimed_rows ?? 0 );
    $skipped         = (int) ( $log->skipped_rows ?? 0 );
    $artistas_n      = is_array($artists) ? count($artists) : ( is_array($credits_by_user) ? count($credits_by_user) : 0 );
    $source_name     = $log->source_name ?? '—';
    $file_name       = $log->file_name ?? '';

    // Top 10 artistas — buscar nomes
    global $wpdb;
    $top_rows = [];
    if ( ! empty( $credits_by_user ) ) {
        arsort( $credits_by_user );
        $top10 = array_slice( $credits_by_user, 0, 10, true );
        $tels = array_keys( $top10 );
        if ( ! empty( $tels ) ) {
            $placeholders = implode(',', array_fill(0, count($tels), '%s'));
            $names_rows = $wpdb->get_results( $wpdb->prepare(
                "SELECT user_telemovel, user_nome FROM {$wpdb->prefix}rmbz_wallets WHERE user_telemovel IN ($placeholders)",
                $tels
            ), OBJECT_K );
            foreach ( $top10 as $tel => $amt ) {
                $name = isset($names_rows[$tel]) ? ($names_rows[$tel]->user_nome ?: $tel) : $tel;
                $top_rows[] = [ 'name' => $name, 'tel' => $tel, 'amount' => (float) $amt ];
            }
        }
    }

    $formatted_id = str_pad( (int) ($log->id ?? 0), 6, '0', STR_PAD_LEFT );
    $subject = "✓ Import #{$formatted_id} aprovado · {$period_label} · $" . number_format($total_distrib, 2);

    // Corpo HTML — usar tabela inline porque o template builder não suporta tudo
    $admin_url = admin_url('admin.php?page=rmbz-admin-distribution&tab=royalties&rsub=imports');

    $html = '<div style="font-family:Arial,Helvetica,sans-serif; color:#1a1a1a;">';
    $html .= '<h2 style="color:#065f46; margin:0 0 10px 0;">✓ Importação aprovada</h2>';
    $html .= '<p style="margin:0 0 18px 0; color:#555;">Olá Jaime, um import foi aprovado no sistema. Aqui está o resumo:</p>';

    // Card stats
    $html .= '<table cellpadding="0" cellspacing="0" style="width:100%; background:#f9fafb; border:1px solid #e5e7eb; border-radius:8px; margin-bottom:18px;">';
    $html .= '<tr><td style="padding:14px 18px;">';
    $html .= '<table cellpadding="0" cellspacing="0" style="width:100%;">';
    $html .= '<tr>';
    $html .= '<td style="padding:6px 14px 6px 0; font-size:11px; color:#6b7280; text-transform:uppercase;">Período</td>';
    $html .= '<td style="padding:6px 0; font-size:13px; font-weight:600;">' . esc_html($period_label) . '</td>';
    $html .= '</tr>';
    $html .= '<tr>';
    $html .= '<td style="padding:6px 14px 6px 0; font-size:11px; color:#6b7280; text-transform:uppercase;">Distribuidora</td>';
    $html .= '<td style="padding:6px 0; font-size:13px; font-weight:600;">' . esc_html($source_name) . '</td>';
    $html .= '</tr>';
    $html .= '<tr>';
    $html .= '<td style="padding:6px 14px 6px 0; font-size:11px; color:#6b7280; text-transform:uppercase;">Bruto recebido</td>';
    $html .= '<td style="padding:6px 0; font-size:13px; font-weight:600;">$' . number_format($total_bruto_usd, 2) . ' USD</td>';
    $html .= '</tr>';
    $html .= '<tr>';
    $html .= '<td style="padding:6px 14px 6px 0; font-size:11px; color:#6b7280; text-transform:uppercase;">Distribuído aos artistas</td>';
    $html .= '<td style="padding:6px 0; font-size:13px; font-weight:700; color:#065f46;">$' . number_format($total_distrib, 2) . ' USD</td>';
    $html .= '</tr>';
    $html .= '<tr>';
    $html .= '<td style="padding:6px 14px 6px 0; font-size:11px; color:#6b7280; text-transform:uppercase;">Artistas afectados</td>';
    $html .= '<td style="padding:6px 0; font-size:13px; font-weight:600;">' . $artistas_n . '</td>';
    $html .= '</tr>';
    $html .= '<tr>';
    $html .= '<td style="padding:6px 14px 6px 0; font-size:11px; color:#6b7280; text-transform:uppercase;">Linhas processadas</td>';
    $html .= '<td style="padding:6px 0; font-size:13px;">' . number_format($processed) . '</td>';
    $html .= '</tr>';
    if ( $unclaimed > 0 ) {
        $html .= '<tr>';
        $html .= '<td style="padding:6px 14px 6px 0; font-size:11px; color:#6b7280; text-transform:uppercase;">Não reclamadas (Black Box)</td>';
        $html .= '<td style="padding:6px 0; font-size:13px; color:#dc2626;">' . number_format($unclaimed) . '</td>';
        $html .= '</tr>';
    }
    if ( $skipped > 0 ) {
        $html .= '<tr>';
        $html .= '<td style="padding:6px 14px 6px 0; font-size:11px; color:#6b7280; text-transform:uppercase;">Skipped (microcêntimos)</td>';
        $html .= '<td style="padding:6px 0; font-size:13px; color:#6b7280;">' . number_format($skipped) . '</td>';
        $html .= '</tr>';
    }
    $html .= '</table>';
    $html .= '</td></tr></table>';

    // Top 10 artistas
    if ( ! empty( $top_rows ) ) {
        $html .= '<h3 style="margin:18px 0 8px 0; font-size:14px; color:#1a1a1a;">🏆 Top ' . count($top_rows) . ' artistas que mais ganharam</h3>';
        $html .= '<table cellpadding="0" cellspacing="0" style="width:100%; border:1px solid #e5e7eb; border-radius:8px; overflow:hidden;">';
        $html .= '<tr style="background:#f9fafb;">';
        $html .= '<th style="text-align:left; padding:8px 14px; font-size:10px; text-transform:uppercase; color:#6b7280;">Artista</th>';
        $html .= '<th style="text-align:right; padding:8px 14px; font-size:10px; text-transform:uppercase; color:#6b7280;">Recebeu</th>';
        $html .= '</tr>';
        $rank = 1;
        foreach ( $top_rows as $tr ) {
            $medal = $rank === 1 ? '🥇 ' : ( $rank === 2 ? '🥈 ' : ( $rank === 3 ? '🥉 ' : '' ) );
            $html .= '<tr>';
            $html .= '<td style="padding:8px 14px; border-top:1px solid #f3f4f6; font-size:13px;">' . $medal . esc_html($tr['name']) . '</td>';
            $html .= '<td style="padding:8px 14px; border-top:1px solid #f3f4f6; text-align:right; font-weight:700; color:#065f46; font-size:13px;">$' . number_format($tr['amount'], 2) . '</td>';
            $html .= '</tr>';
            $rank++;
        }
        $html .= '</table>';
    }

    // Ficheiro original
    if ( ! empty( $file_name ) ) {
        $html .= '<p style="font-size:11px; color:#9ca3af; margin:14px 0 6px 0;">📄 Ficheiro: <code>' . esc_html($file_name) . '</code></p>';
    }

    // CTA
    $html .= '<p style="margin:24px 0 6px 0;"><a href="' . esc_url($admin_url) . '" style="background:#10b981; color:#fff; padding:10px 18px; border-radius:6px; text-decoration:none; font-weight:600; font-size:13px;">Ver no admin →</a></p>';
    $html .= '<p style="font-size:10px; color:#9ca3af; margin-top:18px;">Este email é automático. Para parar de o receber, contacta o administrador do plugin.</p>';
    $html .= '</div>';

    // Wrap com template oficial se existir
    if ( function_exists('rmbz_build_html_email') ) {
        $html_body = rmbz_build_html_email( $html, $sender_name );
    } else {
        $html_body = $html;
    }

    $headers = [
        'Content-Type: text/html; charset=UTF-8',
        'From: ' . $sender_name . ' <' . $sender_email . '>',
    ];
    $sent = wp_mail( $admin_email, $subject, $html_body, $headers );

    if ( function_exists('rmbz_log_sent_email') ) {
        rmbz_log_sent_email( $admin_email, $subject, $html_body, $sent ? 'sucesso' : 'falha', 'admin' );
    }
}
