<?php
/**
 * NotificationsRules — Alert rules management subpage.
 *
 * All severity/channel badge logic uses string methods — no Closures.
 *
 * @package UltraguardPro\modules\notifications\pages
 * @since   6.5.0
 */

namespace UltraguardPro\modules\notifications\pages;

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

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

class NotificationsRules 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();
        $rules_t = $db ? $db->get_table( 'notification_rules' ) : null;

        $total  = $rules_t ? $rules_t->count()                       : 0;
        $active = $rules_t ? $rules_t->count( [ 'is_active' => 1 ] ) : 0;
        $nonce  = $this->create_nonce( 'ultraguard_admin_nonce' );

        $rows = $rules_t ? $rules_t->get_by( [], 200, 'name', 'ASC' ) : [];
        $data = $this->build_rules_table_data( $rows );

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

            'header' => [
                'title'    => __( 'Alert Rules', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Configure which security events trigger notifications and how they are delivered.', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %d: integer */
                    'text'       => sprintf( __( '%d Active Rule(s)', 'ultraguard-security-suite' ), $active ),
                    'badge_type' => $active > 0 ? '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_url_button(  __( 'Add Rule', 'ultraguard-security-suite' ), '#rule-form', 'primary', 'dashicons-plus-alt' ),
                ],
            ],

            'data' => [
                // ── Contextual Pro nudge (free users only) ────────
                ...( UpgradeManager::should_show_nudge()
                    ? [ UpgradeManager::inline_hint( 'notification_rules', __( 'Custom rules let you choose exactly which events trigger a notification and where it goes.', 'ultraguard-security-suite' ) ) ]
                    : [] ),


                // Stats
                [
                    'type'    => 'grid', 'columns' => 12, 'gap' => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Rules',  'ultraguard-security-suite' ), 'value' => $total,          'format' => 'number', 'icon' => 'dashicons-filter',         'class' => 'info'      ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Active Rules', 'ultraguard-security-suite' ), 'value' => $active,         'format' => 'number', 'icon' => 'dashicons-yes-alt',        'class' => 'success'   ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Paused Rules', 'ultraguard-security-suite' ), 'value' => $total - $active,'format' => 'number', 'icon' => 'dashicons-controls-pause', 'class' => 'secondary' ] ],
                    ],
                ],

                // Rules table
                [
                    'type'               => 'data-table',
                    'id'                 => 'notifications-rules-table',
                    'columns'            => [
                        'name'               => [ 'title' => __( 'Rule Name',    'ultraguard-security-suite' ), 'sortable' => true ],
                        'event_type'         => [ 'title' => __( 'Event',        'ultraguard-security-suite' ), 'sortable' => true ],
                        'severity_threshold' => [ 'title' => __( 'Min Severity', 'ultraguard-security-suite' ) ],
                        'channel'            => [ 'title' => __( 'Channel',      'ultraguard-security-suite' ) ],
                        'recipient'          => [ 'title' => __( 'Recipient',    'ultraguard-security-suite' ) ],
                        'cooldown'           => [ 'title' => __( 'Cooldown',     'ultraguard-security-suite' ) ],
                        'triggers'           => [ 'title' => __( 'Triggers',     'ultraguard-security-suite' ), 'sortable' => true ],
                        'last_fired'         => [ 'title' => __( 'Last Fired',   'ultraguard-security-suite' ) ],
                        'status'             => [ 'title' => __( 'Status',       'ultraguard-security-suite' ) ],
                        'actions'            => [ 'title' => __( 'Actions',      'ultraguard-security-suite' ), 'width' => '150px' ],
                    ],
                    'data'               => $data,
                    'searchable'         => true,
                    'search_placeholder' => __( 'Search rules…', 'ultraguard-security-suite' ),
                    'bulk_actions'       => [
                        'bulk_toggle' => __( 'Toggle Active',   'ultraguard-security-suite' ),
                        'bulk_delete' => __( 'Delete Selected', 'ultraguard-security-suite' ),
                    ],
                    'pagination'         => [ 'enabled' => true, 'page_size' => 20 ],
                    'empty_state'        => [
                        'title'       => __( 'No alert rules configured', 'ultraguard-security-suite' ),
                        'description' => __( 'Use the form below to create your first notification rule.', 'ultraguard-security-suite' ),
                    ],
                ],

                // Add / Edit rule form
                [
                    'type'  => 'card',
                    'id'    => 'rule-form',
                    'title' => __( 'Add / Edit Alert Rule', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-plus-alt',
                    'data'  => [
                        [ 'type' => 'text',   'name' => 'name',               'label' => __( 'Rule Name',            'ultraguard-security-suite' ), 'required' => true, 'placeholder' => __( 'e.g. Email me on malware detection', 'ultraguard-security-suite' ) ],
                        [
                            'type'    => 'select',
                            'name'    => 'event_type',
                            'label'   => __( 'Event Type', 'ultraguard-security-suite' ),
                            'options' => $this->get_event_type_options(),
                        ],
                        [
                            'type'    => 'select',
                            'name'    => 'severity_threshold',
                            'label'   => __( 'Minimum Severity', 'ultraguard-security-suite' ),
                            'options' => [
                                'info'     => __( 'Info (everything)',    'ultraguard-security-suite' ),
                                'low'      => __( 'Low',                  'ultraguard-security-suite' ),
                                'medium'   => __( 'Medium',               'ultraguard-security-suite' ),
                                'high'     => __( 'High',                 'ultraguard-security-suite' ),
                                'critical' => __( 'Critical (urgent only)','ultraguard-security-suite' ),
                            ],
                            'default' => 'medium',
                        ],
                        [
                            'type'    => 'select',
                            'name'    => 'channel',
                            'label'   => __( 'Notification Channel', 'ultraguard-security-suite' ),
                            'options' => [
                                'email'        => __( 'Email',          'ultraguard-security-suite' ),
                                'admin_notice' => __( 'Admin Notice',   'ultraguard-security-suite' ),
                                'webhook'      => __( 'Webhook',        'ultraguard-security-suite' ),
                                'slack'        => __( 'Slack',          'ultraguard-security-suite' ),
                            ],
                            'default' => 'email',
                        ],
                        [ 'type' => 'text',     'name' => 'recipient',        'label' => __( 'Recipient',              'ultraguard-security-suite' ), 'placeholder' => get_option( 'admin_email' ), 'description' => __( 'Email address, Slack webhook URL, or HTTP endpoint URL.', 'ultraguard-security-suite' ) ],
                        [ 'type' => 'text',     'name' => 'subject_template', 'label' => __( 'Subject Template',       'ultraguard-security-suite' ), 'placeholder' => '[{site_name}] Security Alert: {event_type}', 'description' => __( 'Supports {placeholders}: {event_type}, {severity}, {ip}, {time}, {site_name}, {site_url}, {count}, {username}.', 'ultraguard-security-suite' ) ],
                        [ 'type' => 'textarea', 'name' => 'message_template', 'label' => __( 'Message Template',       'ultraguard-security-suite' ), 'rows' => 6, 'placeholder' => "Security event detected on {site_name}.\n\nEvent: {event_type}\nSeverity: {severity}\nIP: {ip}\nTime: {time}" ],
                        [ 'type' => 'text',     'name' => 'webhook_secret',   'label' => __( 'Webhook HMAC Secret',    'ultraguard-security-suite' ), 'description' => __( 'Optional: sign webhook payloads with HMAC-SHA256.', 'ultraguard-security-suite' ), 'placeholder' => __( 'Leave blank to disable signing', 'ultraguard-security-suite' ) ],
                        [ 'type' => 'number',   'name' => 'cooldown_minutes', 'label' => __( 'Cooldown (minutes)',     'ultraguard-security-suite' ), 'min' => 0, 'max' => 1440, 'default' => 60, 'description' => __( 'Minimum time between repeated alerts of this type.', 'ultraguard-security-suite' ) ],
                        [ 'type' => 'toggle',   'name' => 'is_active',        'label' => __( 'Enable Rule',            'ultraguard-security-suite' ), 'default' => true ],
                    ],
                    'footer' => [
                        'type'      => 'button-group',
                        'alignment' => 'right',
                        'buttons'   => [
                            $this->create_ajax_button( __( 'Test Rule', 'ultraguard-security-suite' ), 'ultraguard_notif_test_rule', [], 'secondary', 'dashicons-email-alt' ),
                            $this->create_ajax_button( __( 'Save Rule', 'ultraguard-security-suite' ), 'ultraguard_notif_save_rule', [], 'primary',   'dashicons-saved'     ),
                        ],
                    ],
                ],
            ],

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

    // ── Private helpers — no Closures ──────────────────────────────────────────

    /**
     * Build the rules data-table rows without Closures.
     *
     * @param  array $rows
     * @return array
     */
    private function build_rules_table_data( array $rows ): array {
        $data          = [];
        $nonce         = $this->create_nonce();
        $event_opts    = $this->get_event_type_options();
        $sev_opts      = [
            'info'     => __( 'Info (everything)',     'ultraguard-security-suite' ),
            'low'      => __( 'Low',                   'ultraguard-security-suite' ),
            'medium'   => __( 'Medium',                'ultraguard-security-suite' ),
            'high'     => __( 'High',                  'ultraguard-security-suite' ),
            'critical' => __( 'Critical (urgent only)','ultraguard-security-suite' ),
        ];
        $channel_opts  = [
            'email'        => __( 'Email',        'ultraguard-security-suite' ),
            'admin_notice' => __( 'Admin Notice', 'ultraguard-security-suite' ),
            'webhook'      => __( 'Webhook',      'ultraguard-security-suite' ),
            'slack'        => __( 'Slack',        'ultraguard-security-suite' ),
        ];

        foreach ( $rows as $r ) {
            $id       = (int) ( $r['id'] ?? 0 );
            $severity = $r['severity_threshold'] ?? 'medium';
            $channel  = $r['channel']            ?? 'email';
            $active   = ! empty( $r['is_active'] );

            // ── View modal ─────────────────────────────────────────────────────
            $view_modal = [
                'id'      => 'notif-rule-view-' . $id,
                /* translators: %s: string */
                'title'   => sprintf( __( 'Rule: %s', 'ultraguard-security-suite' ), esc_html( $r['name'] ?? '' ) ),
                'size'    => 'medium',
                'content' => $this->modal_content( [
                    [ 'type' => 'text',     'name' => 'vrn',  'label' => __( 'Rule Name',        'ultraguard-security-suite' ), 'value' => esc_html( $r['name']               ?? '' ),                                    'readonly' => true ],
                    [ 'type' => 'select',   'name' => 'vret', 'label' => __( 'Event Type',        'ultraguard-security-suite' ), 'value' => esc_attr( $r['event_type']         ?? '*' ),     'options' => $event_opts,   'readonly' => true ],
                    [ 'type' => 'select',   'name' => 'vrst', 'label' => __( 'Min Severity',      'ultraguard-security-suite' ), 'value' => esc_attr( $severity ),              'options' => $sev_opts,                   'readonly' => true ],
                    [ 'type' => 'select',   'name' => 'vrch', 'label' => __( 'Channel',           'ultraguard-security-suite' ), 'value' => esc_attr( $channel ),               'options' => $channel_opts,               'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vrrc', 'label' => __( 'Recipient',         'ultraguard-security-suite' ), 'value' => esc_html( $r['recipient']           ?? '' ),                                    'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vrcd', 'label' => __( 'Cooldown (min)',    'ultraguard-security-suite' ), 'value' => (string) (int) ( $r['cooldown_minutes'] ?? 60 ),                               'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vrtc', 'label' => __( 'Total Triggers',   'ultraguard-security-suite' ), 'value' => number_format_i18n( (int) ( $r['trigger_count'] ?? 0 ) ),                       'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vrlf', 'label' => __( 'Last Fired',       'ultraguard-security-suite' ), 'value' => $r['last_triggered_at'] ? esc_html( $this->format_time_ago( $r['last_triggered_at'] ) ) : __( 'Never', 'ultraguard-security-suite' ), 'readonly' => true ],
                    [ 'type' => 'textarea', 'name' => 'vrst', 'label' => __( 'Subject Template', 'ultraguard-security-suite' ), 'value' => esc_html( $r['subject_template']    ?? '' ), 'rows' => 2,                      'readonly' => true ],
                    [ 'type' => 'textarea', 'name' => 'vrmt', 'label' => __( 'Message Template', 'ultraguard-security-suite' ), 'value' => esc_html( $r['message_template']   ?? '' ), 'rows' => 4,                      'readonly' => true ],
                ] ),
            ];

            // ── Edit modal ─────────────────────────────────────────────────────
            $edit_modal = [
                'id'      => 'notif-rule-edit-' . $id,
                /* translators: %s: string */
                'title'   => sprintf( __( 'Edit Rule: %s', 'ultraguard-security-suite' ), esc_html( $r['name'] ?? '' ) ),
                'size'    => 'medium',
                'content' => $this->modal_content( [
                    [ 'type' => 'text',     'name' => 'name',               'label' => __( 'Rule Name',           'ultraguard-security-suite' ), 'value' => esc_html( $r['name']             ?? '' ), 'required' => true ],
                    [ 'type' => 'select',   'name' => 'event_type',         'label' => __( 'Event Type',           'ultraguard-security-suite' ), 'value' => esc_attr( $r['event_type']       ?? '*' ),     'options' => $event_opts ],
                    [ 'type' => 'select',   'name' => 'severity_threshold', 'label' => __( 'Minimum Severity',    'ultraguard-security-suite' ), 'value' => esc_attr( $severity ),             'options' => $sev_opts ],
                    [ 'type' => 'select',   'name' => 'channel',            'label' => __( 'Channel',             'ultraguard-security-suite' ), 'value' => esc_attr( $channel ),              'options' => $channel_opts ],
                    [ 'type' => 'text',     'name' => 'recipient',          'label' => __( 'Recipient',           'ultraguard-security-suite' ), 'value' => esc_html( $r['recipient']          ?? '' ) ],
                    [ 'type' => 'text',     'name' => 'subject_template',   'label' => __( 'Subject Template',    'ultraguard-security-suite' ), 'value' => esc_html( $r['subject_template']   ?? '' ) ],
                    [ 'type' => 'number',   'name' => 'cooldown_minutes',   'label' => __( 'Cooldown (minutes)',  'ultraguard-security-suite' ), 'value' => (string) (int) ( $r['cooldown_minutes'] ?? 60 ), 'min' => 0, 'max' => 1440 ],
                    [ 'type' => 'toggle',   'name' => 'is_active',          'label' => __( 'Enable Rule',         'ultraguard-security-suite' ), 'value' => $active ? '1' : '0' ],
                ] ),
                'footer' => $this->modal_footer_save( 'ultraguard_notif_save_rule', [ 'rule_id' => $id ] ),
            ];

            $data[] = [
                'id'                 => 'ug-notif-rule-row-' . $id,
                'data-rule-id'       => $id,
                'name'               => esc_html( $r['name']       ?? '' ),
                'event_type'         => esc_html( ucwords( str_replace( '_', ' ', $r['event_type'] ?? '' ) ) ),
                'severity_threshold' => [
                    'content' => ucfirst( $severity ),
                    'class'   => $this->severity_badge_class( $severity ),
                ],
                'channel'    => [ 'content' => ucfirst( $channel ), 'class' => 'info' ],
                'recipient'  => esc_html( substr( $r['recipient'] ?? '', 0, 40 ) . ( strlen( $r['recipient'] ?? '' ) > 40 ? '…' : '' ) ),
                'cooldown'   => ( (int) ( $r['cooldown_minutes'] ?? 60 ) ) . __( ' min', 'ultraguard-security-suite' ),
                'triggers'   => number_format_i18n( (int) ( $r['trigger_count'] ?? 0 ) ),
                'last_fired' => $r['last_triggered_at']
                    ? esc_html( $this->format_time_ago( $r['last_triggered_at'] ) )
                    : __( 'Never', 'ultraguard-security-suite' ),
                'status' => [
                    'content' => $active ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Paused', 'ultraguard-security-suite' ),
                    'class'   => $active ? 'success' : 'secondary',
                ],
                'actions' => $this->row_actions( [
                    [ 'type' => 'button', 'text' => '', 'icon' => 'dashicons-visibility',       'button_style' => 'secondary', 'title' => __( 'View details',  'ultraguard-security-suite' ), 'modal' => $view_modal ],
                    [ 'type' => 'button', 'text' => '', 'icon' => 'dashicons-edit',             'button_style' => 'primary',   'title' => __( 'Edit rule',     'ultraguard-security-suite' ), 'modal' => $edit_modal ],
                    [ 'type' => 'button', 'text' => '', 'icon' => 'dashicons-email-alt',        'button_style' => 'secondary', 'title' => __( 'Send test',     'ultraguard-security-suite' ),
                      'ajax' => [ 'action' => 'ultraguard_notif_test_rule', 'nonce' => $nonce, 'data' => [ 'rule_id' => $id ] ] ],
                    [ 'type' => 'button', 'text' => '', 'icon' => $active ? 'dashicons-controls-pause' : 'dashicons-controls-play', 'button_style' => $active ? 'warning' : 'success',
                      'title' => $active ? __( 'Pause rule', 'ultraguard-security-suite' ) : __( 'Enable rule', 'ultraguard-security-suite' ),
                      'ajax' => [ 'action' => 'ultraguard_notif_toggle_rule', 'nonce' => $nonce, 'data' => [ 'rule_id' => $id ] ] ],
                    [ 'type' => 'button', 'text' => '', 'icon' => 'dashicons-trash', 'button_style' => 'danger', 'title' => __( 'Delete rule', 'ultraguard-security-suite' ),
                      /* translators: %s: string */
                      'ajax' => [ 'action' => 'ultraguard_notif_delete_rule', 'nonce' => $nonce, 'data' => [ 'rule_id' => $id ], 'confirm' => sprintf( __( 'Delete rule "%s"?', 'ultraguard-security-suite' ), esc_js( $r['name'] ?? '' ) ) ] ],
                ] ),
            ];
        }
        return $data;
    }

    /**
     * Map severity level to a badge CSS class string.
     *
     * @param  string $severity
     * @return string
     */
    private function severity_badge_class( string $severity ): string {
        return match ( $severity ) {
            'critical', 'high' => 'danger',
            'medium'           => 'warning',
            'low'              => 'info',
            default            => 'secondary',
        };
    }

    /**
     * Return the event type select options array.
     *
     * @return array<string,string>
     */
    private function get_event_type_options(): array {
        return apply_filters( 'ultraguard_notification_event_types', [
            '*'                   => __( '* Any Event',                  'ultraguard-security-suite' ),
            'request_blocked'     => __( 'Request Blocked (Firewall)',    'ultraguard-security-suite' ),
            'rate_limit_exceeded' => __( 'Brute Force / Rate Limit',     'ultraguard-security-suite' ),
            'malware_detected'    => __( 'Malware Detected (Antivirus)', 'ultraguard-security-suite' ),
            'file_modified'       => __( 'File Modified (File Checker)', 'ultraguard-security-suite' ),
            'ip_locked_out'       => __( 'IP Locked Out',                'ultraguard-security-suite' ),
            'admin_login'         => __( 'Admin Login',                  'ultraguard-security-suite' ),
            'vulnerability_found' => __( 'Vulnerability Found',          'ultraguard-security-suite' ),
            'scan_completed'      => __( 'Scan Completed',               'ultraguard-security-suite' ),
        ] );
    }
}
