<?php
/**
 * NotificationsLog — Notification history and delivery log subpage.
 * No Closures in schema — status/channel badges use string methods.
 *
 * @package UltraguardPro\modules\notifications\pages
 * @since   6.5.0
 */

namespace UltraguardPro\modules\notifications\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;

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

class NotificationsLog extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $db    = $this->plugin->modules->get_db_tables();
        $log_t = $db ? $db->get_table( 'notification_log' ) : null;

        $total   = $log_t ? $log_t->count()                            : 0;
        $sent    = $log_t ? $log_t->count( [ 'status' => 'sent'    ] ) : 0;
        $failed  = $log_t ? $log_t->count( [ 'status' => 'failed'  ] ) : 0;
        $queued  = $log_t ? $log_t->count( [ 'status' => 'queued'  ] ) : 0;

        $rows = $log_t ? $log_t->get_by( [], 200, 'created_at', 'DESC' ) : [];
        $all_data    = $this->build_log_rows( $rows );
        $sent_data   = array_values( array_filter( $all_data,   fn( $r ) => ( $r['status']['content'] ?? '' ) === 'Sent' ) );
        $failed_data = array_values( array_filter( $all_data,   fn( $r ) => ( $r['status']['content'] ?? '' ) === 'Failed' ) );

        return apply_filters( 'ultraguard_notifications_log_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-notifications-log',
            'page_slug' => 'notifications-log',
            'class'     => 'ultraguard-notifications-log-page',

            'header' => [
                'title'    => __( 'Notification Log', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Full delivery history for all security alert notifications.', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %d: number */
                    'text'       => sprintf( _n( '%d Entry', '%d Entries', $total, 'ultraguard-security-suite' ), $total ),
                    'badge_type' => 'info',
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Export CSV',  'ultraguard-security-suite' ), 'ultraguard_notif_export_log',    [], 'secondary', 'dashicons-download' ),
                    $this->create_ajax_button( __( 'Retry Failed','ultraguard-security-suite' ), 'ultraguard_notif_retry_failed',  [], 'secondary', 'dashicons-update'   ),
                    $this->create_ajax_button( __( 'Clear Log',   'ultraguard-security-suite' ), 'ultraguard_notif_clear_log',     [], 'danger',    'dashicons-trash',
                        __( 'Clear all notification log entries? This cannot be undone.', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => [
                [
                    'type'    => 'grid', 'columns' => 12, 'gap' => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total',   'ultraguard-security-suite' ), 'value' => $total,  'format' => 'number', 'icon' => 'dashicons-list-view', 'class' => 'info'    ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Sent',    'ultraguard-security-suite' ), 'value' => $sent,   'format' => 'number', 'icon' => 'dashicons-yes-alt',   'class' => 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Failed',  'ultraguard-security-suite' ), 'value' => $failed, 'format' => 'number', 'icon' => 'dashicons-no-alt',    'class' => $failed  > 0 ? 'danger'  : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Queued',  'ultraguard-security-suite' ), 'value' => $queued, 'format' => 'number', 'icon' => 'dashicons-clock',     'class' => $queued  > 0 ? 'warning' : 'success' ] ],
                    ],
                ],

                [
                    'type' => 'tabs',
                    'id'   => 'notifications-log-tabs',
                    'tabs' => [
                        [
                            'id'    => 'all',
                            'title' => __( 'All', 'ultraguard-security-suite' ) . ' (' . $total . ')',
                            'icon'  => 'dashicons-list-view',
                            'data'  => [ $this->build_log_table( $all_data, 'notifications-log-all' ) ],
                        ],
                        [
                            'id'    => 'sent',
                            'title' => __( 'Sent', 'ultraguard-security-suite' ) . ' (' . $sent . ')',
                            'icon'  => 'dashicons-yes-alt',
                            'data'  => [ $this->build_log_table( $sent_data, 'notifications-log-sent' ) ],
                        ],
                        [
                            'id'    => 'failed',
                            'title' => __( 'Failed', 'ultraguard-security-suite' ) . ' (' . $failed . ')',
                            'icon'  => 'dashicons-no-alt',
                            'data'  => [ $this->build_log_table( $failed_data, 'notifications-log-failed' ) ],
                        ],
                    ],
                ],
            ],

            'form' => [ 'enable' => false ],
        ], $context );
    }

    // ── Private helpers ────────────────────────────────────────────────────────

    /**
     * Build log table row data — no Closures.
     *
     * @param  array $rows
     * @return array
     */
    private function build_log_rows( array $rows ): array {
        $data = [];
        foreach ( $rows as $r ) {
            $status  = $r['status']  ?? 'sent';
            $channel = $r['channel'] ?? 'email';

            $data[] = [
                'id'            => 'ug-notif-log-row-' . (int) ( $r['id'] ?? 0 ),
                'data-log-id'   => (int) ( $r['id'] ?? 0 ),
                'event_type'    => esc_html( ucwords( str_replace( '_', ' ', $r['event_type'] ?? '' ) ) ),
                'channel'       => [ 'content' => ucfirst( str_replace( '_', ' ', $channel ) ), 'class' => 'info' ],
                'recipient'     => esc_html( $r['recipient'] ?? '' ),
                'subject'       => esc_html( substr( $r['subject'] ?? '', 0, 60 ) ),
                'status'        => [
                    'content' => ucfirst( $status ),
                    'class'   => match ( $status ) {
                        'sent'    => 'success',
                        'failed'  => 'danger',
                        'queued'  => 'warning',
                        default   => 'secondary',
                    },
                ],
                'error'         => esc_html( substr( $r['error_message'] ?? '', 0, 80 ) ),
                'sent_at'       => esc_html( $this->format_date_time( $r['sent_at'] ?? $r['created_at'] ?? '' ) ),
            ];
        }
        return $data;
    }

    /**
     * Build a data-table schema for one log tab.
     *
     * @param  array  $data
     * @param  string $id
     * @return array
     */
    private function build_log_table( array $data, string $id ): array {
        return [
            'type'               => 'data-table',
            'id'                 => $id,
            'columns'            => [
                'event_type' => [ 'title' => __( 'Event',     'ultraguard-security-suite' ), 'sortable' => true ],
                'channel'    => [ 'title' => __( 'Channel',   'ultraguard-security-suite' ) ],
                'recipient'  => [ 'title' => __( 'Recipient', 'ultraguard-security-suite' ) ],
                'subject'    => [ 'title' => __( 'Subject',   'ultraguard-security-suite' ) ],
                'status'     => [ 'title' => __( 'Status',    'ultraguard-security-suite' ) ],
                'error'      => [ 'title' => __( 'Error',     'ultraguard-security-suite' ) ],
                'sent_at'    => [ 'title' => __( 'Sent At',   'ultraguard-security-suite' ), 'sortable' => true ],
            ],
            'data'               => $data,
            'searchable'         => true,
            'search_placeholder' => __( 'Search log…', 'ultraguard-security-suite' ),
            'bulk_actions'       => [
                'retry'  => __( 'Retry Selected',  'ultraguard-security-suite' ),
                'delete' => __( 'Delete Selected', 'ultraguard-security-suite' ),
            ],
            'pagination'         => [ 'enabled' => true, 'page_size' => 25 ],
            'empty_state'        => [ 'title' => __( 'No notification log entries.', 'ultraguard-security-suite' ) ],
        ];
    }
}


// =============================================================================

/**
 * NotificationsStatistics — Notification analytics subpage.
 *
 * @package UltraguardPro\modules\notifications\pages
 * @since   6.5.0
 */
class NotificationsStatistics extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $db    = $this->plugin->modules->get_db_tables();
        $log_t = $db ? $db->get_table( 'notification_log' ) : null;

        $summary  = $log_t ? $log_t->get_stats_summary() : [];
        $sent     = (int)   ( $summary['total_sent']   ?? 0 );
        $failed   = (int)   ( $summary['total_failed'] ?? 0 );
        $rate     = (float) ( $summary['delivery_rate']?? 100.0 );

        $trend_30  = $log_t ? $log_t->get_chart_data( 'created_at', 'id', 'day', [], 30 ) : [ 'labels' => [], 'data' => [] ];
        $sent_7d   = $log_t ? $log_t->get_chart_data( 'sent_at', 'id', 'day', [ 'status' => 'sent'   ], 7 ) : [ 'labels' => [], 'data' => [] ];
        $failed_7d = $log_t ? $log_t->get_chart_data( 'created_at', 'id', 'day', [ 'status' => 'failed' ], 7 ) : [ 'labels' => [], 'data' => [] ];

        $channel_labels = [ 'Email', 'Slack', 'Webhook', 'Admin Notice' ];
        $channel_keys   = [ 'email', 'slack', 'webhook', 'admin_notice' ];
        $channel_counts = array_map( fn( $k ) => $log_t ? $log_t->count( [ 'channel' => $k ] ) : 0, $channel_keys );

        $event_keys    = [ 'request_blocked', 'rate_limit_exceeded', 'malware_detected', 'file_modified', 'ip_locked_out', 'admin_login' ];
        $event_labels  = array_map( fn( $k ) => ucwords( str_replace( '_', ' ', $k ) ), $event_keys );
        $event_counts  = array_map( fn( $k ) => $log_t ? $log_t->count( [ 'event_type' => $k ] ) : 0, $event_keys );

        return apply_filters( 'ultraguard_notifications_statistics_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-notifications-statistics',
            'page_slug' => 'notifications-statistics',
            'class'     => 'ultraguard-notifications-statistics-page',

            'header' => [
                'title'    => __( 'Notification Statistics', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Analytics on notification delivery, channels and event types.', 'ultraguard-security-suite' ),
                'badge'    => [
                    'text'       => $rate . '% ' . __( 'delivery rate', 'ultraguard-security-suite' ),
                    'badge_type' => $rate >= 95 ? 'success' : ( $rate >= 80 ? 'warning' : 'danger' ),
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Refresh',    'ultraguard-security-suite' ), 'ultraguard_notif_refresh_stats', [], 'secondary', 'dashicons-update'   ),
                    $this->create_ajax_button( __( 'Export Log', 'ultraguard-security-suite' ), 'ultraguard_notif_export_log',    [], 'secondary', 'dashicons-download' ),
                ],
            ],

            'data' => [
                // Stat row
                [
                    'type'    => 'grid', 'columns' => 12, 'gap' => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Sent',    'ultraguard-security-suite' ), 'value' => $sent,   'format' => 'number',     'icon' => 'dashicons-yes-alt', 'class' => 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Failed',  'ultraguard-security-suite' ), 'value' => $failed, 'format' => 'number',     'icon' => 'dashicons-no-alt',  'class' => $failed > 0 ? 'danger' : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Sent (24h)',    'ultraguard-security-suite' ), 'value' => (int)($summary['total_sent_24h'] ?? 0), 'format' => 'number', 'icon' => 'dashicons-clock',   'class' => 'info' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Delivery Rate', 'ultraguard-security-suite' ), 'value' => $rate,   'format' => 'percentage', 'icon' => 'dashicons-chart-bar','class' => $rate >= 95 ? 'success' : 'warning' ] ],
                    ],
                ],

                // 30-day volume trend
                [
                    'type'  => 'card',
                    'title' => __( 'Notification Volume — Last 30 Days', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-chart-line',
                    'data'  => [ [
                        'type'       => 'chart',
                        'chart_type' => 'line',
                        'height'     => '240px',
                        'labels'     => $sent_7d['labels'],
                        'datasets'   => [
                            [ 'label' => __( 'Sent',   'ultraguard-security-suite' ), 'data' => $sent_7d['data'],   'borderColor' => '#22c55e', 'backgroundColor' => 'rgba(34,197,94,0.1)',  'tension' => 0.4, 'fill' => true ],
                            [ 'label' => __( 'Failed', 'ultraguard-security-suite' ), 'data' => $failed_7d['data'], 'borderColor' => '#dc2626', 'backgroundColor' => 'rgba(220,38,38,0.1)',  'tension' => 0.4, 'fill' => true ],
                        ],
                        'security_theme' => true,
                    ] ],
                ],

                // Channel / Status / Event type charts
                [
                    'type'    => 'grid', 'columns' => 12, 'gap' => '20px',
                    'items'   => [
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Breakdown by Channel', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-pie',
                                'data'  => [ [
                                    'type'       => 'chart',
                                    'chart_type' => 'doughnut',
                                    'height'     => '220px',
                                    'labels'     => $channel_labels,
                                    'datasets'   => [ [
                                        'data'            => $channel_counts,
                                        'backgroundColor' => [ '#3b82f6', '#f59e0b', '#8b5cf6', '#22c55e' ],
                                    ] ],
                                    'security_theme' => true,
                                ] ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Delivery Status', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-bar',
                                'data'  => [ [
                                    'type'       => 'chart',
                                    'chart_type' => 'pie',
                                    'height'     => '220px',
                                    'labels'     => [ __( 'Sent', 'ultraguard-security-suite' ), __( 'Failed', 'ultraguard-security-suite' ) ],
                                    'datasets'   => [ [
                                        'data'            => [ $sent, $failed ],
                                        'backgroundColor' => [ '#22c55e', '#dc2626' ],
                                    ] ],
                                    'security_theme' => true,
                                ] ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Top Event Types', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-filter',
                                'data'  => [ [
                                    'type'       => 'chart',
                                    'chart_type' => 'bar',
                                    'height'     => '220px',
                                    'labels'     => $event_labels,
                                    'datasets'   => [ [
                                        'label'           => __( 'Notifications', 'ultraguard-security-suite' ),
                                        'data'            => $event_counts,
                                        'backgroundColor' => 'rgba(59,130,246,0.7)',
                                        'borderColor'     => '#3b82f6',
                                    ] ],
                                    'security_theme' => true,
                                ] ],
                            ],
                        ],
                    ],
                ],
            ],

            'form' => [ 'enable' => false ],
        ], $context );
    }
}


// =============================================================================

/**
 * NotificationsSettings — Notification configuration settings page.
 * Implements mandatory form + sticky footer pattern.
 *
 * @package UltraguardPro\modules\notifications\pages
 * @since   6.5.0
 */
class NotificationsSettings extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $s     = fn( string $k, $d = '' ) => $this->get_setting( $k, $d );
        $nonce = $this->create_nonce( 'ultraguard_admin_nonce' );

        $email_on   = (bool) $s( 'notifications_email_enabled',   true  );
        $webhook_on = (bool) $s( 'notifications_webhook_enabled', false );
        $slack_on   = (bool) $s( 'notifications_slack_enabled',   false );
        $any_on     = $email_on || $webhook_on || $slack_on;

        return apply_filters( 'ultraguard_notifications_settings_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-notifications-settings',
            'page_slug' => 'notifications-settings',
            'class'     => 'ultraguard-notifications-settings-page',

            'header' => [
                'title'    => __( 'Notification Settings', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Configure email, webhook and Slack delivery channels, throttling and log retention.', 'ultraguard-security-suite' ),
                'badge'    => [
                    'text'       => $any_on ? __( 'Channels Active', 'ultraguard-security-suite' ) : __( 'All Channels Off', 'ultraguard-security-suite' ),
                    'badge_type' => $any_on ? 'success' : 'secondary',
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Send Test Email',  'ultraguard-security-suite' ), 'ultraguard_notif_send_test', [ 'channel' => 'email',   'recipient' => get_option( 'admin_email' ) ], 'secondary', 'dashicons-email-alt'  ),
                    $this->create_ajax_button( __( 'Test Webhook',     'ultraguard-security-suite' ), 'ultraguard_notif_send_test', [ 'channel' => 'webhook', 'recipient' => $s( 'notifications_webhook_url', '' ) ], 'secondary', 'dashicons-admin-links' ),
                    $this->create_ajax_button( __( 'Test Slack',       'ultraguard-security-suite' ), 'ultraguard_notif_send_test', [ 'channel' => 'slack',   'recipient' => $s( 'notifications_slack_webhook', '' ) ], 'secondary', 'dashicons-format-chat' ),
                ],
            ],

            'data' => [
                [
                    'type'       => 'grid',
                    'columns'    => 12,
                    'gap'        => '20px',
                    'responsive' => true,
                    'items'      => [

                        // General enable
                        [
                            'span'      => 12,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Global Settings', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-bell',
                                'data'  => [
                                    [ 'type' => 'toggle', 'name' => 'notifications_enabled',        'label' => __( 'Enable Notifications',       'ultraguard-security-suite' ), 'description' => __( 'Master switch — turn off to silence all notifications.', 'ultraguard-security-suite' ), 'default' => (bool) $s( 'notifications_enabled', true ) ],
                                    [ 'type' => 'toggle', 'name' => 'notifications_notify_on_login', 'label' => __( 'Notify on Admin Login',      'ultraguard-security-suite' ), 'description' => __( 'Send an info-level notification when an admin logs in.', 'ultraguard-security-suite' ), 'default' => (bool) $s( 'notifications_notify_on_login', false ) ],
                                ],
                            ],
                        ],

                        // Email settings
                        [
                            'span'      => 6,
                            'responsive'=> [ 'md' => 12, 'lg' => 6 ],
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Email Notifications', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-email',
                                'badge' => [ 'text' => $email_on ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ), 'badge_type' => $email_on ? 'success' : 'secondary' ],
                                'data'  => [
                                    [ 'type' => 'toggle', 'name' => 'notifications_email_enabled', 'label' => __( 'Enable Email Alerts',         'ultraguard-security-suite' ), 'default' => $email_on ],
                                    [ 'type' => 'text',   'name' => 'notifications_from_email',    'label' => __( 'From Email Address',          'ultraguard-security-suite' ), 'placeholder' => 'no-reply@' . preg_replace( '/^www\./i', '', (string) wp_parse_url( home_url(), PHP_URL_HOST ) ), 'description' => __( 'Notification emails should use a same-domain sender address.', 'ultraguard-security-suite' ), 'default' => $s( 'notifications_from_email' ) ],
                                    [ 'type' => 'text',   'name' => 'notifications_from_name',     'label' => __( 'From Display Name',           'ultraguard-security-suite' ), 'placeholder' => get_bloginfo( 'name' ), 'description' => __( 'Display name shown in email clients for notification emails.', 'ultraguard-security-suite' ), 'default' => $s( 'notifications_from_name'  ) ],
                                    [ 'type' => 'text',   'name' => 'notifications_admin_email',   'label' => __( 'Default Alert Recipient',     'ultraguard-security-suite' ), 'placeholder' => get_option( 'admin_email' ),                 'description' => __( 'Default recipient when a rule has no specific recipient.', 'ultraguard-security-suite' ), 'default' => $s( 'notifications_admin_email' ) ],
                                ],
                            ],
                        ],

                        // Webhook / Slack settings
                        [
                            'span'      => 6,
                            'responsive'=> [ 'md' => 12, 'lg' => 6 ],
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Webhook & Slack', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-admin-links',
                                'data'  => [
                                    [ 'type' => 'toggle', 'name' => 'notifications_webhook_enabled', 'label' => __( 'Enable Webhook Delivery',     'ultraguard-security-suite' ), 'default' => $webhook_on ],
                                    [ 'type' => 'text',   'name' => 'notifications_webhook_url',     'label' => __( 'Default Webhook URL',         'ultraguard-security-suite' ), 'placeholder' => 'https://your-endpoint.com/hook', 'default' => $s( 'notifications_webhook_url' ) ],
                                    [
                                        'type'    => 'select',
                                        'name'    => 'notifications_webhook_format',
                                        'label'   => __( 'Payload Format', 'ultraguard-security-suite' ),
                                        'options' => [ 'json' => 'JSON', 'slack' => 'Slack (Block Kit)', 'form' => 'Form Encoded' ],
                                        'default' => $s( 'notifications_webhook_format', 'json' ),
                                    ],
                                    [ 'type' => 'text',   'name' => 'notifications_webhook_secret',  'label' => __( 'Webhook Signing Secret',      'ultraguard-security-suite' ), 'placeholder' => __( 'Optional HMAC-SHA256 key', 'ultraguard-security-suite' ), 'description' => __( 'Adds X-UltraGuard-Signature header to all webhook POSTs.', 'ultraguard-security-suite' ), 'default' => $s( 'notifications_webhook_secret' ) ],
                                    [ 'type' => 'toggle', 'name' => 'notifications_slack_enabled',   'label' => __( 'Enable Slack Integration',    'ultraguard-security-suite' ), 'default' => $slack_on ],
                                    [ 'type' => 'text',   'name' => 'notifications_slack_webhook',   'label' => __( 'Slack Incoming Webhook URL',  'ultraguard-security-suite' ), 'placeholder' => 'https://hooks.slack.com/services/…', 'default' => $s( 'notifications_slack_webhook' ) ],
                                ],
                            ],
                        ],

                        // Throttling
                        [
                            'span'      => 6,
                            'responsive'=> [ 'md' => 12, 'lg' => 6 ],
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Throttling & Digest', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-clock',
                                'data'  => [
                                    [ 'type' => 'toggle', 'name' => 'notifications_digest_mode',      'label' => __( 'Digest Mode',               'ultraguard-security-suite' ), 'description' => __( 'Bundle non-critical notifications into periodic summaries.', 'ultraguard-security-suite' ), 'default' => (bool) $s( 'notifications_digest_mode', false ) ],
                                    [
                                        'type'    => 'select',
                                        'name'    => 'notifications_digest_frequency',
                                        'label'   => __( 'Digest Frequency', 'ultraguard-security-suite' ),
                                        'options' => [ 'hourly' => __( 'Hourly', 'ultraguard-security-suite' ), 'twicedaily' => __( 'Twice Daily', 'ultraguard-security-suite' ), 'daily' => __( 'Daily', 'ultraguard-security-suite' ), 'weekly' => __( 'Weekly', 'ultraguard-security-suite' ) ],
                                        'default' => $s( 'notifications_digest_frequency', 'daily' ),
                                    ],
                                    [ 'type' => 'number', 'name' => 'notifications_global_cooldown',  'label' => __( 'Global Cooldown (minutes)',  'ultraguard-security-suite' ), 'min' => 0, 'max' => 1440, 'description' => __( 'Minimum gap between same-type alerts (0 = off).', 'ultraguard-security-suite' ), 'default' => (int) $s( 'notifications_global_cooldown', 60 ) ],
                                    [ 'type' => 'number', 'name' => 'notifications_max_per_hour',     'label' => __( 'Max Alerts / Hour',         'ultraguard-security-suite' ), 'min' => 1, 'max' => 1000, 'description' => __( 'Rate limit — excess alerts are silently dropped.', 'ultraguard-security-suite' ), 'default' => (int) $s( 'notifications_max_per_hour', 50 ) ],
                                    $this->create_ajax_button( __( 'Send Digest Now', 'ultraguard-security-suite' ), 'ultraguard_notif_send_digest_now', [], 'secondary', 'dashicons-email' ),
                                ],
                            ],
                        ],

                        // Log & retention
                        [
                            'span'      => 6,
                            'responsive'=> [ 'md' => 12, 'lg' => 6 ],
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Log & Retention', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-list-view',
                                'data'  => [
                                    [ 'type' => 'toggle', 'name' => 'notifications_log_enabled',   'label' => __( 'Enable Notification Log',   'ultraguard-security-suite' ), 'description' => __( 'Store a record of every notification sent or failed.', 'ultraguard-security-suite' ), 'default' => (bool) $s( 'notifications_log_enabled',  true  ) ],
                                    [ 'type' => 'number', 'name' => 'notifications_log_retention', 'label' => __( 'Log Retention (days)',       'ultraguard-security-suite' ), 'min' => 1, 'max' => 365, 'description' => __( 'Automatically remove entries older than N days.', 'ultraguard-security-suite' ), 'default' => (int) $s( 'notifications_log_retention', 90   ) ],
                                    [ 'type' => 'toggle', 'name' => 'notifications_retry_failed',  'label' => __( 'Auto-Retry Failed (10 min)', 'ultraguard-security-suite' ), 'description' => __( 'Automatically retry failed notifications once after 10 minutes.', 'ultraguard-security-suite' ), 'default' => (bool) $s( 'notifications_retry_failed', true  ) ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],

            // ── Sticky footer ──────────────────────────────────────────────────
            'form' => [
                'enable'     => true,
                'id'         => 'notifications-settings-form',
                'ajax'       => true,
                'action'     => 'ultraguard_notif_save_settings',
                'nonce'      => $nonce,
                'submit'     => [
                    'text'         => __( 'Save Notification Settings', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                ],
            ],
        ], $context );
    }
}
