<?php
/**
 * [1.6.116] AVISOS GLOBAIS — PÁGINA ADMIN
 *
 * URL: ?page=rmbz-app-version&tab=announcements
 * (integrado como tab em "Controlo de Versão da App")
 *
 * - Lista todos os avisos (activos e inactivos)
 * - Formulário para criar/editar com preview ao vivo do card
 * - Acções: activar/desactivar, eliminar, duplicar
 *
 * Reutiliza a aparência geral do plugin (estilo minimalista, gold accent).
 *
 * @package 1MZ_For_Artists
 * @since 1.6.116
 */

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


// [1.6.116.6] Integrado como tab em "Controlo de Versão da App".
// REMOVIDO add_menu_page — agora é tab dentro de rmbz-app-version.
// O painel é renderizado pelo `app-version-control.php` que chama
// directamente as funções `rmbz_announcements_render_*`.


/**
 * URL base da página Avisos — usado em redirects e links internos.
 *
 * [1.6.116.6] Agora aponta para a tab dentro de rmbz-app-version.
 */
function rmbz_announcements_admin_url( $args = [] ) {
    $base = admin_url( 'admin.php' );
    $defaults = [
        'page' => 'rmbz-app-version',
        'tab'  => 'announcements',
    ];
    return add_query_arg( array_merge( $defaults, $args ), $base );
}


/**
 * [BUG FIX 1.6.116.1] Processar POST/GET-acções no admin_init (antes do
 * WordPress enviar headers), em vez de dentro do callback de render.
 *
 * [1.6.116.6] Reconhece a nova tab dentro de rmbz-app-version.
 */
add_action( 'admin_init', 'rmbz_announcements_handle_actions' );

function rmbz_announcements_handle_actions() {
    // Aceitar 2 contextos:
    //   - URL antigo (?page=rmbz-announcements) — para compatibilidade
    //   - URL novo (?page=rmbz-app-version&tab=announcements)
    $page = $_GET['page'] ?? '';
    $tab  = $_GET['tab']  ?? '';
    $is_announcements_page = ( $page === 'rmbz-announcements' )
        || ( $page === 'rmbz-app-version' && $tab === 'announcements' );

    if ( ! $is_announcements_page ) return;
    if ( ! current_user_can( 'manage_options' ) ) return;

    // POST: criar/editar
    if ( $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['rmbz_ann_action'] ) ) {
        rmbz_announcements_handle_post();
    }

    // GET: toggle / duplicate / delete
    if ( isset( $_GET['ann_do'] ) && isset( $_GET['ann_id'] ) ) {
        rmbz_announcements_handle_get_action(
            sanitize_key( $_GET['ann_do'] ),
            (int) $_GET['ann_id']
        );
    }
}


/**
 * [1.6.116.6] Wrapper de compatibilidade — se algum sítio antigo
 * apontar para `?page=rmbz-announcements`, redirecciona para o
 * URL novo. Mantém bookmarks/links externos a funcionar.
 */
function rmbz_announcements_admin_render() {
    wp_safe_redirect( rmbz_announcements_admin_url() );
    exit;
}


/**
 * Estilos partilhados da página (uma única vez, inline para evitar
 * dependência de assets externos).
 */
function rmbz_announcements_render_styles() {
    ?>
    <style>
    .rmbz-ann-wrap { font-family: -apple-system, system-ui, sans-serif; max-width: 1200px; }
    .rmbz-ann-card { background:#fff; border:1px solid #e5e5e5; border-radius:8px; padding:16px 20px; margin-bottom:14px; }
    .rmbz-ann-list { width: 100%; border-collapse: collapse; font-size: 13px; }
    .rmbz-ann-list th { background:#fafafa; padding:10px 12px; text-align:left; font-size:10px; text-transform:uppercase; color:#666; font-weight:600; border-bottom:1px solid #e5e5e5; }
    .rmbz-ann-list td { padding:10px 12px; border-bottom:1px solid #f3f4f6; vertical-align:middle; }
    .rmbz-ann-list tr:hover { background:#fffbeb; }
    .rmbz-ann-list tr.inactive { opacity: 0.55; }
    .rmbz-ann-list .lvl { display:inline-block; padding:2px 9px; border-radius:11px; font-size:11px; font-weight:600; }
    .rmbz-ann-list .lvl.info { background:#dbeafe; color:#1e40af; }
    .rmbz-ann-list .lvl.success { background:#d1fae5; color:#065f46; }
    .rmbz-ann-list .lvl.warning { background:#fef3c7; color:#92400e; }
    .rmbz-ann-list .lvl.error { background:#fee2e2; color:#991b1b; }
    .rmbz-ann-list .lvl.promo { background:#e9d5ff; color:#6b21a8; }
    .rmbz-ann-list .actions a { margin-right:8px; font-size:11px; text-decoration:none; }
    .rmbz-ann-empty { text-align:center; padding:40px; color:#888; }
    .rmbz-ann-form-grid { display:grid; grid-template-columns: 1.4fr 1fr; gap:24px; }
    @media (max-width: 1000px) { .rmbz-ann-form-grid { grid-template-columns: 1fr; } }
    .rmbz-ann-form fieldset { border:1px solid #e5e5e5; border-radius:6px; padding:12px 14px; margin-bottom:12px; background:#fff; }
    .rmbz-ann-form legend { font-size:11px; text-transform:uppercase; font-weight:700; color:#666; padding:0 6px; }
    .rmbz-ann-form label { display:block; font-size:12px; font-weight:600; color:#333; margin:8px 0 3px; }
    .rmbz-ann-form input[type=text], .rmbz-ann-form input[type=url], .rmbz-ann-form input[type=number], .rmbz-ann-form input[type=datetime-local], .rmbz-ann-form select, .rmbz-ann-form textarea { width:100%; padding:6px 9px; border:1px solid #ddd; border-radius:4px; font-size:13px; box-sizing:border-box; }
    .rmbz-ann-form textarea { min-height: 80px; font-family: inherit; }
    .rmbz-ann-form .row2 { display:grid; grid-template-columns:1fr 1fr; gap:10px; }
    .rmbz-ann-form .row3 { display:grid; grid-template-columns:1fr 1fr 1fr; gap:10px; }
    .rmbz-ann-form .help { font-size:11px; color:#888; margin-top:3px; line-height:1.4; }
    .rmbz-ann-form .checkbox-row { display:flex; align-items:center; gap:8px; margin-top:8px; }
    .rmbz-ann-form .checkbox-row label { margin:0; font-weight:500; }
    .rmbz-ann-loc-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:4px 12px; margin-top:6px; }
    .rmbz-ann-loc-grid label { font-weight:500; font-size:12px; margin:0; display:flex; align-items:center; gap:4px; }

    /* Preview do card (mimics Material 3 card) */
    .rmbz-ann-preview-wrap { position: sticky; top: 40px; }
    .rmbz-ann-preview-phone {
        background: #1a1a1a;
        border-radius: 30px;
        padding: 30px 14px;
        max-width: 320px;
        min-height: 500px;
        margin: 0 auto;
        box-shadow: 0 8px 24px rgba(0,0,0,0.15);
    }
    .rmbz-ann-preview-phone-screen {
        background: #f5f5f5;
        border-radius: 18px;
        padding: 18px 14px;
        min-height: 440px;
    }
    .rmbz-ann-preview-label { font-size: 10px; color: #aaa; text-transform: uppercase; margin-bottom: 6px; text-align: center; font-weight: 600; }
    /* card preview material 3-ish */
    .preview-card { border-radius: 16px; padding: 14px; display: flex; gap: 12px; align-items: flex-start; box-shadow: 0 1px 3px rgba(0,0,0,0.06); margin-bottom: 8px; transition: all 0.3s; }
    .preview-card .ic { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 18px; }
    .preview-card .body { flex: 1; min-width: 0; }
    .preview-card .body strong { display: block; font-size: 13px; margin-bottom: 3px; }
    .preview-card .body p { margin: 0; font-size: 11.5px; line-height: 1.45; color: #4b5563; }
    .preview-card .body .cta { display: inline-block; margin-top: 8px; padding: 5px 11px; font-size: 11px; font-weight: 600; border-radius: 14px; }
    .preview-card .x { flex-shrink: 0; color: #888; cursor: pointer; font-size: 14px; padding: 2px 6px; }
    .preview-card.level-info { background: #dbeafe; }
    .preview-card.level-info .ic { background: #1e40af; color: #fff; }
    .preview-card.level-info .cta { background: #1e40af; color: #fff; }
    .preview-card.level-success { background: #d1fae5; }
    .preview-card.level-success .ic { background: #065f46; color: #fff; }
    .preview-card.level-success .cta { background: #065f46; color: #fff; }
    .preview-card.level-warning { background: #fef3c7; }
    .preview-card.level-warning .ic { background: #92400e; color: #fff; }
    .preview-card.level-warning .cta { background: #92400e; color: #fff; }
    .preview-card.level-error { background: #fee2e2; }
    .preview-card.level-error .ic { background: #991b1b; color: #fff; }
    .preview-card.level-error .cta { background: #991b1b; color: #fff; }
    .preview-card.level-promo { background: linear-gradient(135deg, #ddd6fe, #e9d5ff); }
    .preview-card.level-promo .ic { background: #6b21a8; color: #fff; }
    .preview-card.level-promo .cta { background: #6b21a8; color: #fff; }
    .preview-card.anim-pulse { animation: ann-pulse 2s ease-in-out infinite; }
    @keyframes ann-pulse {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.02); box-shadow: 0 4px 16px rgba(0,0,0,0.12); }
    }
    .preview-card.anim-slide {
        animation: ann-slide 0.5s ease-out;
    }
    @keyframes ann-slide {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    /* [1.6.116.3] Animações VIP */
    .preview-card.anim-vip_shimmer {
        position: relative;
        overflow: hidden;
    }
    .preview-card.anim-vip_shimmer::before {
        content: '';
        position: absolute;
        top: 0;
        left: -150%;
        width: 75%;
        height: 100%;
        background: linear-gradient(
            105deg,
            transparent 30%,
            rgba(255, 215, 0, 0.55) 50%,
            rgba(255, 230, 130, 0.35) 60%,
            transparent 70%
        );
        animation: ann-vip-shimmer 2.6s ease-in-out infinite;
        pointer-events: none;
    }
    @keyframes ann-vip-shimmer {
        0%   { left: -75%; }
        100% { left: 130%; }
    }

    .preview-card.anim-vip_border {
        position: relative;
        box-shadow:
            0 0 0 2px rgba(255, 215, 0, 0.55),
            0 0 12px rgba(255, 215, 0, 0.35);
        animation: ann-vip-border 2s ease-in-out infinite;
    }
    @keyframes ann-vip-border {
        0%, 100% {
            box-shadow:
                0 0 0 2px rgba(255, 215, 0, 0.45),
                0 0 6px rgba(255, 215, 0, 0.25);
        }
        50% {
            box-shadow:
                0 0 0 2px rgba(255, 215, 0, 0.80),
                0 0 16px rgba(255, 215, 0, 0.55);
        }
    }
    .rmbz-ann-form-actions { margin-top: 16px; padding-top: 14px; border-top: 1px solid #eee; display: flex; gap: 8px; }
    .rmbz-ann-form-actions .button-primary { background: #f0b90b !important; border-color: #c89106 !important; color: #000 !important; text-shadow: none !important; box-shadow: none !important; }
    </style>
    <?php
}


/**
 * Lista de avisos.
 */
function rmbz_announcements_render_list() {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_app_announcements';

    $rows = $wpdb->get_results(
        "SELECT * FROM $t ORDER BY is_active DESC, sort_order ASC, id DESC"
    );

    $new_url = esc_url( rmbz_announcements_admin_url( [ 'view' => 'new' ] ) );

    echo '<p><a href="' . $new_url . '" class="button button-primary">+ Novo aviso</a></p>';

    if ( empty( $rows ) ) {
        echo '<div class="rmbz-ann-card rmbz-ann-empty">';
        echo '<p style="font-size:14px; margin:0 0 10px;">📭 Sem avisos criados ainda.</p>';
        echo '<p style="font-size:12px; color:#888; margin:0;">Cria o primeiro para começar a comunicar com os artistas no app.</p>';
        echo '</div>';
        return;
    }

    echo '<div class="rmbz-ann-card" style="padding:0;">';
    echo '<table class="rmbz-ann-list">';
    echo '<thead><tr>
        <th>#</th>
        <th>Título / Mensagem</th>
        <th>Nível</th>
        <th>Onde</th>
        <th>Audiência</th>
        <th>📊 Métricas</th>
        <th>Estado</th>
        <th style="text-align:right;">Acções</th>
    </tr></thead><tbody>';

    foreach ( $rows as $r ) {
        $is_active = (bool) $r->is_active;
        $row_class = $is_active ? '' : 'inactive';
        $metrics = rmbz_announcements_get_metrics( (int) $r->id );
        $edit_url      = esc_url( rmbz_announcements_admin_url( [ 'view' => 'edit', 'id' => $r->id ] ) );
        $stats_url     = esc_url( rmbz_announcements_admin_url( [ 'view' => 'stats', 'id' => $r->id ] ) );
        $toggle_url    = wp_nonce_url( rmbz_announcements_admin_url( [ 'ann_do' => 'toggle', 'ann_id' => $r->id ] ), 'rmbz_ann_toggle_' . $r->id );
        $dup_url       = wp_nonce_url( rmbz_announcements_admin_url( [ 'ann_do' => 'duplicate', 'ann_id' => $r->id ] ), 'rmbz_ann_dup_' . $r->id );
        $del_url       = wp_nonce_url( rmbz_announcements_admin_url( [ 'ann_do' => 'delete', 'ann_id' => $r->id ] ), 'rmbz_ann_del_' . $r->id );

        echo '<tr class="' . esc_attr( $row_class ) . '">';
        echo '<td>' . (int) $r->id . '</td>';
        echo '<td><strong>' . esc_html( $r->title ?: '(sem título)' ) . '</strong><br>';
        echo '<span style="color:#888; font-size:11.5px;">' . esc_html( wp_trim_words( $r->message, 14 ) ) . '</span></td>';
        echo '<td><span class="lvl ' . esc_attr( $r->level ) . '">' . esc_html( $r->level ) . '</span></td>';
        echo '<td>' . esc_html( $r->location ) . '</td>';
        echo '<td>' . esc_html( $r->audience ) . '</td>';
        echo '<td style="font-size:11.5px; line-height:1.5;">';
        echo '<a href="' . $stats_url . '" style="text-decoration:none; color:#333;">';
        echo '👁 <strong>' . (int) $metrics['views_unique'] . '</strong> <span style="color:#888;">(' . (int) $metrics['views_total'] . ')</span><br>';
        echo '✕ <strong>' . (int) $metrics['dismissals_unique'] . '</strong> &nbsp; ';
        echo '🖱 <strong>' . (int) $metrics['cta_clicks_unique'] . '</strong>';
        echo '</a></td>';
        echo '<td>' . ( $is_active ? '<span style="color:#065f46;">✓ activo</span>' : '<span style="color:#888;">✗ inactivo</span>' ) . '</td>';
        echo '<td class="actions" style="text-align:right;">';
        echo '<a href="' . $stats_url . '">📊 Métricas</a>';
        echo '<a href="' . $edit_url . '">✏️ Editar</a>';
        echo '<a href="' . $toggle_url . '">' . ( $is_active ? '⏸ Pausar' : '▶ Activar' ) . '</a>';
        echo '<a href="' . $dup_url . '">📋 Duplicar</a>';
        echo '<a href="' . $del_url . '" style="color:#c00;" onclick="return confirm(\'Eliminar este aviso? Esta acção não pode ser desfeita.\');">🗑 Eliminar</a>';
        echo '</td></tr>';
    }

    echo '</tbody></table></div>';
}


/**
 * [1.6.116.4] Devolve métricas agregadas de um aviso.
 *   - views_total / views_unique
 *   - dismissals_total / dismissals_unique
 *   - cta_clicks_total / cta_clicks_unique
 */
function rmbz_announcements_get_metrics( $announcement_id ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_app_announcement_events';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t'" ) !== $t ) {
        return [
            'views_total' => 0, 'views_unique' => 0,
            'dismissals_total' => 0, 'dismissals_unique' => 0,
            'cta_clicks_total' => 0, 'cta_clicks_unique' => 0,
        ];
    }
    // 1 query agrega tudo
    $rows = $wpdb->get_results( $wpdb->prepare(
        "SELECT event_type,
                COUNT(*) AS total,
                COUNT(DISTINCT user_telemovel) AS unique_users
           FROM $t
          WHERE announcement_id = %d
          GROUP BY event_type",
        $announcement_id
    ) );

    $out = [
        'views_total' => 0, 'views_unique' => 0,
        'dismissals_total' => 0, 'dismissals_unique' => 0,
        'cta_clicks_total' => 0, 'cta_clicks_unique' => 0,
    ];
    foreach ( $rows as $r ) {
        switch ( $r->event_type ) {
            case 'view':
                $out['views_total']  = (int) $r->total;
                $out['views_unique'] = (int) $r->unique_users;
                break;
            case 'dismiss':
                $out['dismissals_total']  = (int) $r->total;
                $out['dismissals_unique'] = (int) $r->unique_users;
                break;
            case 'cta_click':
                $out['cta_clicks_total']  = (int) $r->total;
                $out['cta_clicks_unique'] = (int) $r->unique_users;
                break;
        }
    }
    return $out;
}


/**
 * Formulário criar/editar.
 */
function rmbz_announcements_render_form( $id = 0 ) {
    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_app_announcements';

    $row = null;
    if ( $id > 0 ) {
        $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $t WHERE id = %d", $id ) );
    }

    // Defaults
    $title       = $row->title       ?? '';
    $message     = $row->message     ?? '';
    $level       = $row->level       ?? 'info';
    $icon        = $row->icon        ?? '';
    $cta_label   = $row->cta_label   ?? '';
    $cta_url     = $row->cta_url     ?? '';
    $dismissible = isset( $row->dismissible ) ? (int) $row->dismissible : 1;
    $animation   = $row->animation   ?? 'slide';
    $location    = $row->location    ?? 'home';
    $audience    = $row->audience    ?? 'all';
    $starts_at   = $row->starts_at   ?? '';
    $ends_at     = $row->ends_at     ?? '';
    $is_active   = isset( $row->is_active ) ? (int) $row->is_active : 1;
    $sort_order  = isset( $row->sort_order ) ? (int) $row->sort_order : 100;

    // Locations possíveis (lista CSV ou "all")
    $loc_options = [
        'home'        => '🏠 Início',
        'wallet'      => '💼 Carteira',
        'releases'    => '🎵 Releases',
        'submissions' => '📤 Submissões',
        'profile'     => '👤 Perfil',
    ];
    $loc_selected = ( $location === 'all' ) ? [] : array_map( 'trim', explode( ',', $location ) );
    $loc_all      = ( $location === 'all' );

    $back_url = esc_url( rmbz_announcements_admin_url() );
    ?>

    <p><a href="<?php echo $back_url; ?>">← Voltar à lista</a></p>

    <form method="post" class="rmbz-ann-form">
        <?php wp_nonce_field( 'rmbz_ann_save', '_rmbz_ann_nonce' ); ?>
        <input type="hidden" name="rmbz_ann_action" value="save">
        <input type="hidden" name="id" value="<?php echo (int) $id; ?>">

        <div class="rmbz-ann-form-grid">

            <!-- COLUNA ESQUERDA: FORMULÁRIO -->
            <div>
                <fieldset>
                    <legend>Conteúdo</legend>

                    <label>Título <small>(opcional, mas recomendado)</small></label>
                    <input type="text" name="title" id="f-title" value="<?php echo esc_attr( $title ); ?>" maxlength="120" placeholder="Ex: Manutenção amanhã às 10h">

                    <label>Mensagem <span style="color:#c00;">*</span></label>
                    <textarea name="message" id="f-message" required maxlength="500" placeholder="O texto do aviso..."><?php echo esc_textarea( $message ); ?></textarea>
                    <p class="help">Máx 500 caracteres. Aparece logo abaixo do título.</p>

                    <div class="row2">
                        <div>
                            <label>CTA (texto do botão) <small>opcional</small></label>
                            <input type="text" name="cta_label" id="f-cta-label" value="<?php echo esc_attr( $cta_label ); ?>" maxlength="60" placeholder="Ex: Saber mais">
                        </div>
                        <div>
                            <label>CTA (URL) <small>opcional</small></label>
                            <input type="text" name="cta_url" id="f-cta-url" value="<?php echo esc_attr( $cta_url ); ?>" maxlength="500" placeholder="https://... ou app://wallet">
                            <p class="help">URL externo (https://) ou deep-link interno (<code>app://wallet</code>, <code>app://releases</code>).</p>
                        </div>
                    </div>
                </fieldset>

                <fieldset>
                    <legend>Aparência</legend>
                    <div class="row3">
                        <div>
                            <label>Nível</label>
                            <select name="level" id="f-level">
                                <?php foreach ( [
                                    'info'    => 'ℹ Info',
                                    'success' => '✓ Sucesso',
                                    'warning' => '⚠ Aviso',
                                    'error'   => '✗ Erro',
                                    'promo'   => '⭐ Promo',
                                ] as $k => $v ): ?>
                                    <option value="<?php echo esc_attr( $k ); ?>" <?php selected( $level, $k ); ?>><?php echo esc_html( $v ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label>Ícone <small>(emoji ou nome)</small></label>
                            <input type="text" name="icon" id="f-icon" value="<?php echo esc_attr( $icon ); ?>" maxlength="40" placeholder="🎉">
                        </div>
                        <div>
                            <label>Animação</label>
                            <select name="animation" id="f-animation">
                                <option value="none"        <?php selected( $animation, 'none' ); ?>>Nenhuma</option>
                                <option value="slide"       <?php selected( $animation, 'slide' ); ?>>Slide-in (suave)</option>
                                <option value="pulse"       <?php selected( $animation, 'pulse' ); ?>>Pulse (atenção)</option>
                                <option value="vip_shimmer" <?php selected( $animation, 'vip_shimmer' ); ?>>✨ VIP — Shimmer dourado</option>
                                <option value="vip_border"  <?php selected( $animation, 'vip_border' ); ?>>👑 VIP — Borda brilhante</option>
                            </select>
                        </div>
                    </div>
                </fieldset>

                <fieldset>
                    <legend>Onde aparece</legend>
                    <div class="checkbox-row">
                        <input type="checkbox" id="loc_all" name="location_all" value="1" <?php checked( $loc_all ); ?> onchange="document.getElementById('loc-grid').style.opacity = this.checked ? 0.3 : 1;">
                        <label for="loc_all"><strong>Mostrar em TODAS as páginas</strong></label>
                    </div>
                    <div class="rmbz-ann-loc-grid" id="loc-grid" style="<?php echo $loc_all ? 'opacity:0.3;' : ''; ?>">
                        <?php foreach ( $loc_options as $k => $v ): ?>
                            <label><input type="checkbox" name="location[]" value="<?php echo esc_attr( $k ); ?>" <?php checked( in_array( $k, $loc_selected, true ) ); ?>> <?php echo esc_html( $v ); ?></label>
                        <?php endforeach; ?>
                    </div>
                    <p class="help">Se desmarcado "TODAS", selecciona pelo menos uma página.</p>
                </fieldset>

                <fieldset>
                    <legend>Comportamento</legend>
                    <div class="row2">
                        <div>
                            <label>Dispensa</label>
                            <select name="dismissible" id="f-dismissible">
                                <option value="0" <?php selected( $dismissible, 0 ); ?>>Não dispensável (sempre visível)</option>
                                <option value="1" <?php selected( $dismissible, 1 ); ?>>Dispensável só na sessão actual</option>
                                <option value="2" <?php selected( $dismissible, 2 ); ?>>Dispensável permanentemente</option>
                            </select>
                        </div>
                        <div>
                            <label>Audiência</label>
                            <select name="audience">
                                <option value="all"     <?php selected( $audience, 'all' ); ?>>Todos os artistas</option>
                                <option value="vip"     <?php selected( $audience, 'vip' ); ?>>Apenas VIP</option>
                                <option value="non_vip" <?php selected( $audience, 'non_vip' ); ?>>Apenas Não-VIP</option>
                            </select>
                        </div>
                    </div>
                </fieldset>

                <fieldset>
                    <legend>Janela de exibição <small>(opcional)</small></legend>
                    <div class="row2">
                        <div>
                            <label>Início (UTC)</label>
                            <input type="datetime-local" name="starts_at" value="<?php echo $starts_at ? esc_attr( str_replace( ' ', 'T', $starts_at ) ) : ''; ?>">
                        </div>
                        <div>
                            <label>Fim (UTC)</label>
                            <input type="datetime-local" name="ends_at" value="<?php echo $ends_at ? esc_attr( str_replace( ' ', 'T', $ends_at ) ) : ''; ?>">
                        </div>
                    </div>
                    <p class="help">Em branco = sempre activo. Datas em UTC (server time).</p>
                </fieldset>

                <fieldset>
                    <legend>Ordem & estado</legend>
                    <div class="row2">
                        <div>
                            <label>Ordem (menor = mais acima)</label>
                            <input type="number" name="sort_order" value="<?php echo (int) $sort_order; ?>" min="1" max="999">
                        </div>
                        <div>
                            <label>Activo?</label>
                            <select name="is_active">
                                <option value="1" <?php selected( $is_active, 1 ); ?>>✓ Activo</option>
                                <option value="0" <?php selected( $is_active, 0 ); ?>>✗ Inactivo</option>
                            </select>
                        </div>
                    </div>
                </fieldset>

                <div class="rmbz-ann-form-actions">
                    <button type="submit" class="button button-primary">💾 Guardar</button>
                    <a href="<?php echo $back_url; ?>" class="button">Cancelar</a>
                </div>
            </div>

            <!-- COLUNA DIREITA: PREVIEW -->
            <div class="rmbz-ann-preview-wrap">
                <div class="rmbz-ann-preview-label">📱 Pré-visualização no app</div>
                <div class="rmbz-ann-preview-phone">
                    <div class="rmbz-ann-preview-phone-screen">
                        <div id="ann-preview-card-host"></div>
                    </div>
                </div>
                <p style="text-align:center; font-size:11px; color:#888; margin-top:10px;">Actualiza ao escreveres</p>
            </div>

        </div>
    </form>

    <script>
    // [1.6.116] Preview ao vivo do card
    (function(){
        function renderPreview() {
            var title = document.getElementById('f-title').value || '';
            var message = document.getElementById('f-message').value || '(escreve uma mensagem)';
            var level = document.getElementById('f-level').value || 'info';
            var icon = document.getElementById('f-icon').value || '';
            var animation = document.getElementById('f-animation').value || 'slide';
            var ctaLabel = document.getElementById('f-cta-label').value || '';
            var dismissible = document.getElementById('f-dismissible').value;

            var defaultIcons = { info:'ℹ', success:'✓', warning:'⚠', error:'✗', promo:'⭐' };
            var displayIcon = icon || defaultIcons[level] || 'ℹ';

            var html = '<div class="preview-card level-' + level + ' anim-' + animation + '">';
            html += '<div class="ic">' + escapeHtml(displayIcon) + '</div>';
            html += '<div class="body">';
            if (title) html += '<strong>' + escapeHtml(title) + '</strong>';
            html += '<p>' + escapeHtml(message) + '</p>';
            if (ctaLabel) html += '<span class="cta">' + escapeHtml(ctaLabel) + '</span>';
            html += '</div>';
            if (dismissible !== '0') html += '<div class="x">✕</div>';
            html += '</div>';

            var host = document.getElementById('ann-preview-card-host');
            host.innerHTML = html;

            // Force re-trigger da animação removendo+adicionando classe
            if (animation === 'slide' || animation === 'pulse') {
                var card = host.querySelector('.preview-card');
                if (card) {
                    card.style.animation = 'none';
                    void card.offsetWidth;
                    card.style.animation = '';
                }
            }
        }

        function escapeHtml(s) {
            return String(s).replace(/[&<>"']/g, function(c){
                return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
            });
        }

        var watched = ['f-title','f-message','f-level','f-icon','f-animation','f-cta-label','f-dismissible'];
        watched.forEach(function(id){
            var el = document.getElementById(id);
            if (el) el.addEventListener('input', renderPreview);
            if (el) el.addEventListener('change', renderPreview);
        });

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


/**
 * Handler POST: criar/editar.
 */
function rmbz_announcements_handle_post() {
    if ( ! isset( $_POST['_rmbz_ann_nonce'] ) || ! wp_verify_nonce( $_POST['_rmbz_ann_nonce'], 'rmbz_ann_save' ) ) {
        wp_die( 'Nonce inválido.' );
    }

    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_app_announcements';

    $id = (int) ( $_POST['id'] ?? 0 );

    // Validar e sanitizar
    $title       = sanitize_text_field( $_POST['title'] ?? '' );
    $message     = sanitize_textarea_field( $_POST['message'] ?? '' );
    if ( $message === '' ) {
        wp_die( 'A mensagem é obrigatória.' );
    }

    $allowed_levels = [ 'info', 'success', 'warning', 'error', 'promo' ];
    $level = in_array( $_POST['level'] ?? '', $allowed_levels, true ) ? $_POST['level'] : 'info';

    $allowed_anims = [ 'none', 'slide', 'pulse', 'vip_shimmer', 'vip_border' ];
    $animation = in_array( $_POST['animation'] ?? '', $allowed_anims, true ) ? $_POST['animation'] : 'slide';

    $allowed_audience = [ 'all', 'vip', 'non_vip' ];
    $audience = in_array( $_POST['audience'] ?? '', $allowed_audience, true ) ? $_POST['audience'] : 'all';

    $icon      = sanitize_text_field( $_POST['icon'] ?? '' );
    $cta_label = sanitize_text_field( $_POST['cta_label'] ?? '' );
    $cta_url   = esc_url_raw( $_POST['cta_url'] ?? '' );

    // CTA URL aceita também app:// — esc_url_raw filtra por defeito esses schemes.
    // Reverter caso comece por app://
    if ( strpos( $_POST['cta_url'] ?? '', 'app://' ) === 0 ) {
        $cta_url = sanitize_text_field( $_POST['cta_url'] );
    }

    $dismissible = in_array( (int) ( $_POST['dismissible'] ?? 1 ), [ 0, 1, 2 ], true ) ? (int) $_POST['dismissible'] : 1;

    // Location: "all" ou lista CSV
    if ( ! empty( $_POST['location_all'] ) ) {
        $location = 'all';
    } else {
        $allowed_locs = [ 'home', 'wallet', 'releases', 'submissions', 'profile' ];
        $locs = isset( $_POST['location'] ) && is_array( $_POST['location'] ) ? $_POST['location'] : [];
        $locs = array_filter( $locs, function ( $l ) use ( $allowed_locs ) {
            return in_array( $l, $allowed_locs, true );
        } );
        $location = empty( $locs ) ? 'home' : implode( ',', $locs );
    }

    // Datas
    $starts_at = ! empty( $_POST['starts_at'] ) ? str_replace( 'T', ' ', sanitize_text_field( $_POST['starts_at'] ) ) . ':00' : null;
    $ends_at   = ! empty( $_POST['ends_at'] )   ? str_replace( 'T', ' ', sanitize_text_field( $_POST['ends_at'] ) )   . ':00' : null;
    if ( $starts_at && ! preg_match( '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $starts_at ) ) $starts_at = null;
    if ( $ends_at   && ! preg_match( '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $ends_at ) )   $ends_at   = null;

    $is_active  = (int) ( $_POST['is_active'] ?? 1 );
    $sort_order = max( 1, min( 999, (int) ( $_POST['sort_order'] ?? 100 ) ) );

    $data = [
        'title'       => $title,
        'message'     => $message,
        'level'       => $level,
        'icon'        => $icon ?: null,
        'cta_label'   => $cta_label ?: null,
        'cta_url'     => $cta_url ?: null,
        'dismissible' => $dismissible,
        'animation'   => $animation,
        'location'    => $location,
        'audience'    => $audience,
        'starts_at'   => $starts_at,
        'ends_at'     => $ends_at,
        'is_active'   => $is_active,
        'sort_order'  => $sort_order,
    ];

    if ( $id > 0 ) {
        $wpdb->update( $t, $data, [ 'id' => $id ] );
        $msg = 'updated';
    } else {
        $current_user = wp_get_current_user();
        $data['created_by'] = $current_user->user_login ?? 'admin';
        $wpdb->insert( $t, $data );
        $msg = 'created';
    }

    wp_safe_redirect( rmbz_announcements_admin_url( [ 'ann_msg' => $msg ] ) );
    exit;
}


/**
 * Handler GET: toggle / duplicate / delete.
 */
function rmbz_announcements_handle_get_action( $action, $id ) {
    if ( $id <= 0 ) return;

    global $wpdb;
    $t = $wpdb->prefix . 'rmbz_app_announcements';

    switch ( $action ) {
        case 'toggle':
            if ( ! wp_verify_nonce( $_GET['_wpnonce'] ?? '', 'rmbz_ann_toggle_' . $id ) ) {
                wp_die( 'Nonce inválido.' );
            }
            $wpdb->query( $wpdb->prepare(
                "UPDATE $t SET is_active = 1 - is_active WHERE id = %d",
                $id
            ) );
            $msg = 'toggled';
            break;

        case 'duplicate':
            if ( ! wp_verify_nonce( $_GET['_wpnonce'] ?? '', 'rmbz_ann_dup_' . $id ) ) {
                wp_die( 'Nonce inválido.' );
            }
            $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $t WHERE id = %d", $id ), ARRAY_A );
            if ( $row ) {
                unset( $row['id'], $row['created_at'], $row['updated_at'] );
                $row['title']     = ( $row['title'] ?: '(sem título)' ) . ' [cópia]';
                $row['is_active'] = 0; // duplicado fica inactivo por defeito
                $wpdb->insert( $t, $row );
            }
            $msg = 'duplicated';
            break;

        case 'delete':
            if ( ! wp_verify_nonce( $_GET['_wpnonce'] ?? '', 'rmbz_ann_del_' . $id ) ) {
                wp_die( 'Nonce inválido.' );
            }
            $wpdb->delete( $t, [ 'id' => $id ] );
            // Também limpar dismissals dessa aviso
            $wpdb->delete( $wpdb->prefix . 'rmbz_app_announcement_dismissals', [ 'announcement_id' => $id ] );
            // [1.6.116.4] E também events (métricas)
            $wpdb->delete( $wpdb->prefix . 'rmbz_app_announcement_events', [ 'announcement_id' => $id ] );
            $msg = 'deleted';
            break;

        default:
            $msg = '';
    }

    $redirect_args = $msg ? [ 'ann_msg' => $msg ] : [];
    wp_safe_redirect( rmbz_announcements_admin_url( $redirect_args ) );
    exit;
}


/**
 * [1.6.116.4] Página de métricas detalhadas de um aviso.
 *
 * Mostra:
 *   - 6 KPIs grandes (views/dismissals/cta totais e únicos)
 *   - Taxa de dispensa e taxa de clique (%)
 *   - Gráfico diário (views/dispensas/cliques) últimos 30 dias
 *   - Top 20 events recentes (timeline)
 */
function rmbz_announcements_render_stats( $id ) {
    global $wpdb;
    $t_ann = $wpdb->prefix . 'rmbz_app_announcements';
    $t_ev  = $wpdb->prefix . 'rmbz_app_announcement_events';

    $ann = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $t_ann WHERE id = %d", $id ) );
    if ( ! $ann ) {
        echo '<div class="rmbz-ann-card"><p>Aviso não encontrado.</p></div>';
        echo '<p><a href="' . esc_url( rmbz_announcements_admin_url() ) . '">← Voltar à lista</a></p>';
        return;
    }

    $metrics = rmbz_announcements_get_metrics( $id );

    // Taxas
    $dismiss_rate = $metrics['views_unique'] > 0
        ? round( ( $metrics['dismissals_unique'] / $metrics['views_unique'] ) * 100, 1 )
        : 0;
    $cta_rate = $metrics['views_unique'] > 0
        ? round( ( $metrics['cta_clicks_unique'] / $metrics['views_unique'] ) * 100, 1 )
        : 0;

    // Série diária (últimos 30 dias)
    $start_day = gmdate( 'Y-m-d', strtotime( '-29 days' ) );
    $end_day   = gmdate( 'Y-m-d' );

    $rows = [];
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t_ev'" ) === $t_ev ) {
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT DATE(created_at) AS day,
                    event_type,
                    COUNT(*) AS n
               FROM $t_ev
              WHERE announcement_id = %d
                AND DATE(created_at) BETWEEN %s AND %s
              GROUP BY DATE(created_at), event_type
              ORDER BY day ASC",
            $id, $start_day, $end_day
        ) );
    }

    // Estruturar matriz dia → {views, dismissals, ctas}
    $daily = [];
    for ( $i = 29; $i >= 0; $i-- ) {
        $d = gmdate( 'Y-m-d', strtotime( "-$i days" ) );
        $daily[ $d ] = [ 'views' => 0, 'dismiss' => 0, 'cta' => 0 ];
    }
    foreach ( $rows as $r ) {
        if ( ! isset( $daily[ $r->day ] ) ) continue;
        switch ( $r->event_type ) {
            case 'view':      $daily[ $r->day ]['views']   = (int) $r->n; break;
            case 'dismiss':   $daily[ $r->day ]['dismiss'] = (int) $r->n; break;
            case 'cta_click': $daily[ $r->day ]['cta']     = (int) $r->n; break;
        }
    }
    $max_daily = 0;
    foreach ( $daily as $d ) {
        $max_daily = max( $max_daily, $d['views'], $d['dismiss'], $d['cta'] );
    }

    // Timeline últimos 20 eventos
    $timeline = [];
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$t_ev'" ) === $t_ev ) {
        $timeline = $wpdb->get_results( $wpdb->prepare(
            "SELECT user_telemovel, event_type, created_at
               FROM $t_ev
              WHERE announcement_id = %d
              ORDER BY id DESC
              LIMIT 20",
            $id
        ) );
    }

    $back_url = esc_url( rmbz_announcements_admin_url() );
    $edit_url = esc_url( rmbz_announcements_admin_url( [ 'view' => 'edit', 'id' => $id ] ) );

    ?>
    <p>
        <a href="<?php echo $back_url; ?>">← Voltar à lista</a>
        &nbsp; · &nbsp;
        <a href="<?php echo $edit_url; ?>">✏️ Editar este aviso</a>
    </p>

    <div class="rmbz-ann-card">
        <h2 style="margin:0 0 4px 0; font-size:18px;">📊 Métricas — <?php echo esc_html( $ann->title ?: '(sem título)' ); ?></h2>
        <p style="color:#666; margin:0; font-size:12.5px;"><?php echo esc_html( wp_trim_words( $ann->message, 25 ) ); ?></p>
    </div>

    <!-- KPI grid -->
    <div style="display:grid; grid-template-columns:repeat(3,1fr); gap:12px; margin-bottom:16px;">
        <div class="rmbz-ann-card" style="border-left:3px solid #1e40af;">
            <div style="font-size:10px; text-transform:uppercase; color:#666; font-weight:600; letter-spacing:0.06em;">👁 Impressões</div>
            <div style="font-size:32px; font-weight:700; line-height:1.1; margin-top:4px;"><?php echo (int) $metrics['views_unique']; ?></div>
            <div style="font-size:11px; color:#888;">artistas únicos · <?php echo (int) $metrics['views_total']; ?> totais</div>
        </div>
        <div class="rmbz-ann-card" style="border-left:3px solid #991b1b;">
            <div style="font-size:10px; text-transform:uppercase; color:#666; font-weight:600; letter-spacing:0.06em;">✕ Dispensas</div>
            <div style="font-size:32px; font-weight:700; line-height:1.1; margin-top:4px;"><?php echo (int) $metrics['dismissals_unique']; ?></div>
            <div style="font-size:11px; color:#888;"><?php echo (int) $metrics['dismissals_total']; ?> totais · <?php echo esc_html( $dismiss_rate ); ?>% taxa</div>
        </div>
        <div class="rmbz-ann-card" style="border-left:3px solid #065f46;">
            <div style="font-size:10px; text-transform:uppercase; color:#666; font-weight:600; letter-spacing:0.06em;">🖱 Cliques CTA</div>
            <div style="font-size:32px; font-weight:700; line-height:1.1; margin-top:4px;"><?php echo (int) $metrics['cta_clicks_unique']; ?></div>
            <div style="font-size:11px; color:#888;">
                <?php if ( ! empty( $ann->cta_label ) ): ?>
                    <?php echo (int) $metrics['cta_clicks_total']; ?> totais · <?php echo esc_html( $cta_rate ); ?>% taxa
                <?php else: ?>
                    (sem CTA configurado)
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Gráfico diário -->
    <div class="rmbz-ann-card">
        <h3 style="margin:0 0 10px 0; font-size:13px;">📅 Últimos 30 dias</h3>
        <?php if ( $max_daily === 0 ): ?>
            <p style="color:#888; font-size:12px; margin:0; text-align:center; padding:30px 0;">
                Sem eventos registados nos últimos 30 dias.
            </p>
        <?php else: ?>
            <div style="display:flex; align-items:flex-end; gap:2px; height:120px; padding:6px 0; border-bottom:1px solid #eee;">
                <?php foreach ( $daily as $day => $d ): ?>
                    <?php
                    $h_v  = $max_daily > 0 ? ( $d['views']   / $max_daily ) * 100 : 0;
                    $h_d  = $max_daily > 0 ? ( $d['dismiss'] / $max_daily ) * 100 : 0;
                    $h_c  = $max_daily > 0 ? ( $d['cta']     / $max_daily ) * 100 : 0;
                    $tooltip = $day . ' · 👁 ' . $d['views'] . ' · ✕ ' . $d['dismiss'] . ' · 🖱 ' . $d['cta'];
                    ?>
                    <div title="<?php echo esc_attr( $tooltip ); ?>" style="flex:1; display:flex; flex-direction:column-reverse; gap:1px; min-width:0;">
                        <div style="height:<?php echo $h_v; ?>%; background:#1e40af; border-radius:1px 1px 0 0;"></div>
                        <div style="height:<?php echo $h_d; ?>%; background:#991b1b; border-radius:1px 1px 0 0;"></div>
                        <div style="height:<?php echo $h_c; ?>%; background:#065f46; border-radius:1px 1px 0 0;"></div>
                    </div>
                <?php endforeach; ?>
            </div>
            <div style="display:flex; gap:14px; margin-top:8px; font-size:11px; color:#666;">
                <span><span style="display:inline-block; width:10px; height:10px; background:#1e40af; border-radius:2px; margin-right:4px; vertical-align:middle;"></span>Impressões</span>
                <span><span style="display:inline-block; width:10px; height:10px; background:#991b1b; border-radius:2px; margin-right:4px; vertical-align:middle;"></span>Dispensas</span>
                <span><span style="display:inline-block; width:10px; height:10px; background:#065f46; border-radius:2px; margin-right:4px; vertical-align:middle;"></span>Cliques CTA</span>
            </div>
            <div style="display:flex; justify-content:space-between; font-size:10px; color:#888; margin-top:4px;">
                <span><?php echo esc_html( date( 'd/m', strtotime( $start_day ) ) ); ?></span>
                <span>hoje</span>
            </div>
        <?php endif; ?>
    </div>

    <!-- Timeline -->
    <div class="rmbz-ann-card">
        <h3 style="margin:0 0 10px 0; font-size:13px;">🕒 Últimos 20 eventos</h3>
        <?php if ( empty( $timeline ) ): ?>
            <p style="color:#888; font-size:12px; margin:0;">Sem eventos ainda.</p>
        <?php else: ?>
            <table class="rmbz-ann-list" style="margin:0;">
                <thead><tr>
                    <th>Tipo</th>
                    <th>Artista (telemóvel)</th>
                    <th>Quando</th>
                </tr></thead>
                <tbody>
                <?php foreach ( $timeline as $t ): ?>
                    <?php
                    $icon = [ 'view'=>'👁 viu', 'dismiss'=>'✕ dispensou', 'cta_click'=>'🖱 clicou CTA' ][ $t->event_type ] ?? $t->event_type;
                    $when = human_time_diff( strtotime( $t->created_at ), time() );
                    $tel_masked = substr( $t->user_telemovel, 0, 4 ) . '...' . substr( $t->user_telemovel, -3 );
                    ?>
                    <tr>
                        <td><?php echo esc_html( $icon ); ?></td>
                        <td><code style="font-size:11px;"><?php echo esc_html( $tel_masked ); ?></code></td>
                        <td style="color:#666; font-size:11.5px;">há <?php echo esc_html( $when ); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php
}
