<?php
/**
 * [1.5.235] FASE 3 — Notificações no site (centro + preferências).
 *
 * Reconstrói no site (PHP) os ecrãs de Notificações que a app
 * tem, para quem entra pelo PC/mobile sem instalar a app.
 *
 * Reusa a lógica dos endpoints REST:
 *   - GET  /notifications        → rmbz_api_notif_get_filtered
 *   - POST /notifications/{id}/dismiss
 *   - GET/PUT /notifications/prefs → rmbz_notif_get_user_prefs / set
 */

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

/* ============================================================================
 * Categorias de preferências (espelho do notification-prefs-controller)
 * ============================================================================ */
function rmbz_notif_site_categories() {
    return [
        'releases'    => [
            'label' => 'Releases',
            'desc'  => 'Quando um release fica live ou volta para correcção',
            'icon'  => '🎵',
        ],
        'submissions' => [
            'label' => 'Submissões',
            'desc'  => 'Mudanças de estado das submissões Site e Redes Sociais',
            'icon'  => '📤',
        ],
        'money'       => [
            'label' => 'Levantamentos',
            'desc'  => 'Aprovação ou rejeição de pedidos de levantamento',
            'icon'  => '💰',
        ],
        'license'     => [
            'label' => 'Licenças e SOMAS',
            'desc'  => 'Estado de pedidos de licença e SOMAS',
            'icon'  => '📜',
        ],
    ];
}

/* ============================================================================
 * Handler de POST do site (dismiss + guardar preferências)
 * ============================================================================ */
function rmbz_notif_site_handle_post() {
    if ( empty( $_POST['rmbz_notif_action'] ) ) return;

    $tel = function_exists( 'rmbz_get_current_user_telemovel' )
        ? rmbz_get_current_user_telemovel()
        : '';
    if ( empty( $tel ) ) return;

    $action = sanitize_text_field( $_POST['rmbz_notif_action'] );

    // Dispensar uma notificação
    if ( $action === 'dismiss' && ! empty( $_POST['notif_id'] )
         && check_admin_referer( 'rmbz_notif_dismiss' ) ) {
        $nid = (int) $_POST['notif_id'];
        if ( $nid > 0 ) {
            global $wpdb;
            $clean = preg_replace( '/[^0-9+]/', '', $tel );
            // Evitar duplicado
            $exists = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}rmbz_notifications_dismissed
                 WHERE notification_id = %d AND telemovel = %s",
                $nid, $clean
            ) );
            if ( $exists === 0 ) {
                $wpdb->insert(
                    $wpdb->prefix . 'rmbz_notifications_dismissed',
                    [
                        'notification_id' => $nid,
                        'telemovel'       => $clean,
                        'dismissed_at'    => current_time( 'mysql' ),
                    ]
                );
            }
        }
        wp_safe_redirect( add_query_arg( [ 'distro_action' => 'notifications', 'ok' => 'dismissed' ],
            remove_query_arg( [ 'ok' ] ) ) );
        exit;
    }

    // Guardar preferências
    if ( $action === 'save_prefs' && check_admin_referer( 'rmbz_notif_prefs' ) ) {
        $cats = rmbz_notif_site_categories();
        foreach ( array_keys( $cats ) as $key ) {
            $enabled = ! empty( $_POST['pref_' . $key] );
            if ( function_exists( 'rmbz_notif_set_user_pref' ) ) {
                rmbz_notif_set_user_pref( $tel, $key, $enabled );
            }
        }
        wp_safe_redirect( add_query_arg( [ 'distro_action' => 'notifications', 'ok' => 'prefs' ],
            remove_query_arg( [ 'ok' ] ) ) );
        exit;
    }
}
add_action( 'init', 'rmbz_notif_site_handle_post', 5 );

/* ============================================================================
 * Vista de Notificações — centro + preferências
 * ============================================================================ */

/**
 * Renderiza a vista de Notificações.
 *
 * @param string $telemovel  Telemóvel do artista.
 */
function rmbz_render_notifications_view( $telemovel ) {

    // Sub-aba: 'list' (centro) ou 'prefs' (preferências)
    $sub = ( isset( $_GET['ntab'] ) && $_GET['ntab'] === 'prefs' ) ? 'prefs' : 'list';

    // Mensagens
    $flash = '';
    if ( ! empty( $_GET['ok'] ) ) {
        if ( $_GET['ok'] === 'dismissed' ) $flash = 'Notificação dispensada.';
        if ( $_GET['ok'] === 'prefs' )     $flash = 'Preferências guardadas.';
    }
    ?>
    <div class="distro-dashboard rmbz-fullbleed">
        <div class="distro-header">
            <h1>🔔 Notificações</h1>
            <a href="?distro_action=dashboard" class="back-link">&larr; Voltar</a>
        </div>

        <?php if ( $flash ): ?>
            <div style="background:rgba(46,204,113,0.12); border:1px solid #2ecc71;
                        color:#2ecc71; border-radius:8px; padding:10px 14px;
                        font-size:13px; margin-bottom:16px;">
                ✓ <?php echo esc_html( $flash ); ?>
            </div>
        <?php endif; ?>

        <!-- Sub-abas -->
        <div style="display:flex; gap:8px; margin-bottom:22px;">
            <a href="?distro_action=notifications&ntab=list"
               style="padding:8px 16px; border-radius:20px; text-decoration:none;
                      font-size:13px; font-weight:700;
                      <?php echo $sub === 'list'
                          ? 'background:#f0b90b; color:#000;'
                          : 'background:var(--rmbz-bg-surface,#1a1a1a); color:#aaa; border:1px solid #333;'; ?>">
                📥 Centro
            </a>
            <a href="?distro_action=notifications&ntab=prefs"
               style="padding:8px 16px; border-radius:20px; text-decoration:none;
                      font-size:13px; font-weight:700;
                      <?php echo $sub === 'prefs'
                          ? 'background:#f0b90b; color:#000;'
                          : 'background:var(--rmbz-bg-surface,#1a1a1a); color:#aaa; border:1px solid #333;'; ?>">
                ⚙️ Preferências
            </a>
        </div>

        <?php
        if ( $sub === 'prefs' ) {
            rmbz_notif_render_prefs( $telemovel );
        } else {
            rmbz_notif_render_center( $telemovel );
        }
        ?>
    </div>
    <?php
}

/* ----------------------------------------------------------------------------
 * Centro de notificações — lista
 * -------------------------------------------------------------------------- */
function rmbz_notif_render_center( $telemovel ) {
    // [1.5.235] O centro de notificações do site mostra TODAS as
    // notificações activas (não usa watermark). O watermark é um
    // conceito do push da app — aqui o artista quer ver o histórico.
    $since = '2020-01-01 00:00:00';

    $result = function_exists( 'rmbz_api_notif_get_filtered' )
        ? rmbz_api_notif_get_filtered( $telemovel, $since, 50, 0 )
        : [ 'rows' => [], 'total' => 0 ];

    $rows = $result['rows'] ?? [];

    // Cores por severidade
    $sev = [
        'info'    => [ '#3b82f6', 'ℹ️' ],
        'success' => [ '#2ecc71', '✅' ],
        'warning' => [ '#f0b90b', '⚠️' ],
        'danger'  => [ '#e74c3c', '🚨' ],
    ];

    if ( empty( $rows ) ) {
        ?>
        <div style="background:var(--rmbz-bg-surface,#1a1a1a); border-radius:12px;
                    padding:48px 24px; text-align:center;">
            <div style="font-size:44px; margin-bottom:12px;">🔕</div>
            <h2 style="color:var(--rmbz-text-primary,#fff); font-size:16px; margin:0 0 6px;">
                Sem notificações
            </h2>
            <p style="color:var(--rmbz-text-faint,#888); font-size:13px; margin:0;">
                Quando houver novidades sobre os teus releases, levantamentos
                ou submissões, aparecem aqui.
            </p>
        </div>
        <?php
        return;
    }
    ?>
    <div style="display:flex; flex-direction:column; gap:10px;">
        <?php foreach ( $rows as $n ):
            $s     = $sev[ $n->severity ] ?? $sev['info'];
            $color = $s[0];
            $emoji = $s[1];
            $when  = ! empty( $n->created_at )
                ? date( 'd/m/Y · H:i', strtotime( $n->created_at ) ) : '';
        ?>
            <div style="display:flex; gap:14px;
                        background:var(--rmbz-bg-surface,#1a1a1a);
                        border:1px solid #2a2a2a; border-left:3px solid <?php echo $color; ?>;
                        border-radius:10px; padding:14px 16px;">
                <div style="font-size:20px; flex-shrink:0; line-height:1.4;">
                    <?php echo $emoji; ?>
                </div>
                <div style="flex:1; min-width:0;">
                    <strong style="color:var(--rmbz-text-primary,#fff);
                                   font-size:14px; display:block;">
                        <?php echo esc_html( $n->title ); ?>
                    </strong>
                    <?php if ( ! empty( $n->body ) ): ?>
                        <p style="color:var(--rmbz-text-faint,#aaa); font-size:12px;
                                  margin:4px 0 0; line-height:1.5;">
                            <?php echo esc_html( $n->body ); ?>
                        </p>
                    <?php endif; ?>
                    <div style="display:flex; align-items:center; gap:12px;
                                margin-top:8px; flex-wrap:wrap;">
                        <small style="color:var(--rmbz-text-faint,#666); font-size:11px;">
                            <?php echo esc_html( $when ); ?>
                        </small>
                        <?php if ( ! empty( $n->action_url ) ): ?>
                            <a href="<?php echo esc_url( $n->action_url ); ?>"
                               style="color:#f0b90b; font-size:11px; font-weight:700;
                                      text-decoration:none;">
                                <?php echo esc_html( $n->action_label ?: 'Ver mais' ); ?> &rarr;
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
                <!-- Dispensar -->
                <form method="post" style="flex-shrink:0;">
                    <input type="hidden" name="rmbz_notif_action" value="dismiss">
                    <input type="hidden" name="notif_id" value="<?php echo (int) $n->id; ?>">
                    <?php wp_nonce_field( 'rmbz_notif_dismiss' ); ?>
                    <button type="submit"
                            title="Dispensar"
                            style="background:none; border:none; cursor:pointer;
                                   color:var(--rmbz-text-faint,#666); font-size:16px;
                                   padding:2px 4px;">✕</button>
                </form>
            </div>
        <?php endforeach; ?>
    </div>
    <?php
}

/* ----------------------------------------------------------------------------
 * Preferências de notificações
 * -------------------------------------------------------------------------- */
function rmbz_notif_render_prefs( $telemovel ) {
    $prefs = function_exists( 'rmbz_notif_get_user_prefs' )
        ? rmbz_notif_get_user_prefs( $telemovel )
        : [];
    $cats = rmbz_notif_site_categories();
    ?>
    <form method="post">
        <input type="hidden" name="rmbz_notif_action" value="save_prefs">
        <?php wp_nonce_field( 'rmbz_notif_prefs' ); ?>

        <p style="color:var(--rmbz-text-faint,#888); font-size:13px;
                  margin:0 0 18px;">
            Escolhe que tipos de notificação queres receber. Desligar uma
            categoria silencia as notificações push desse tipo.
        </p>

        <div style="display:flex; flex-direction:column; gap:10px;">
            <?php foreach ( $cats as $key => $cat ):
                $enabled = (bool) ( $prefs[ $key ] ?? true );
            ?>
                <label style="display:flex; align-items:center; gap:14px;
                              background:var(--rmbz-bg-surface,#1a1a1a);
                              border:1px solid #2a2a2a; border-radius:12px;
                              padding:16px; cursor:pointer;">
                    <div style="width:42px; height:42px; border-radius:10px;
                                background:rgba(240,185,11,0.12); display:flex;
                                align-items:center; justify-content:center;
                                font-size:21px; flex-shrink:0;">
                        <?php echo $cat['icon']; ?>
                    </div>
                    <div style="flex:1; min-width:0;">
                        <strong style="color:var(--rmbz-text-primary,#fff);
                                       font-size:14px; display:block;">
                            <?php echo esc_html( $cat['label'] ); ?>
                        </strong>
                        <small style="color:var(--rmbz-text-faint,#888); font-size:12px;">
                            <?php echo esc_html( $cat['desc'] ); ?>
                        </small>
                    </div>
                    <!-- Toggle -->
                    <span style="position:relative; flex-shrink:0;">
                        <input type="checkbox" name="pref_<?php echo esc_attr( $key ); ?>"
                               <?php checked( $enabled ); ?>
                               style="position:absolute; opacity:0; width:0; height:0;"
                               onchange="this.closest('label').querySelector('.rmbz-tgl').style.background =
                                         this.checked ? '#2ecc71' : '#444';
                                         this.closest('label').querySelector('.rmbz-tgl-dot').style.transform =
                                         this.checked ? 'translateX(20px)' : 'translateX(0)';">
                        <span class="rmbz-tgl" style="display:block; width:44px; height:24px;
                              border-radius:12px; transition:background .15s;
                              background:<?php echo $enabled ? '#2ecc71' : '#444'; ?>;">
                            <span class="rmbz-tgl-dot" style="display:block; width:20px; height:20px;
                                  border-radius:50%; background:#fff; margin:2px;
                                  transition:transform .15s;
                                  transform:translateX(<?php echo $enabled ? '20px' : '0'; ?>);"></span>
                        </span>
                    </span>
                </label>
            <?php endforeach; ?>
        </div>

        <button type="submit"
                style="margin-top:20px; background:#f0b90b; color:#000;
                       border:none; border-radius:10px; padding:12px 24px;
                       font-size:14px; font-weight:700; cursor:pointer;">
            Guardar preferências
        </button>
    </form>
    <?php
}
