<?php
/**
 * NotificationsChannels — Saved delivery channel management subpage.
 *
 * Allows admins to create named, reusable delivery destinations
 * (e.g. "DevOps Slack", "CTO Email") separate from individual rules.
 *
 * @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 NotificationsChannels 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();
        $ch_t  = $db ? $db->get_table( 'notification_channels' ) : null;

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

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

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

            'header' => [
                'title'    => __( 'Delivery Channels', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Create and manage reusable named delivery destinations for alert rules.', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %d: integer */
                    'text'       => sprintf( __( '%d Active Channel(s)', 'ultraguard-security-suite' ), $active ),
                    'badge_type' => $active > 0 ? 'success' : 'secondary',
                ],
                'actions' => [
                    $this->create_url_button( __( 'Add Channel', 'ultraguard-security-suite' ), '#channel-form', 'primary', 'dashicons-plus-alt' ),
                ],
            ],

            'data' => [
                // ── Contextual Pro nudge (free users only) ────────
                ...( UpgradeManager::should_show_nudge()
                    ? [ UpgradeManager::inline_hint( 'notification_channels', __( 'Save reusable Slack, webhook, and email destinations used across all your rules.', 'ultraguard-security-suite' ) ) ]
                    : [] ),


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

                // Channels table
                [
                    'type'               => 'data-table',
                    'id'                 => 'notifications-channels-table',
                    'columns'            => [
                        'name'        => [ 'title' => __( 'Name',        'ultraguard-security-suite' ), 'sortable' => true ],
                        'type'        => [ 'title' => __( 'Type',        'ultraguard-security-suite' ) ],
                        'address'     => [ 'title' => __( 'Address',     'ultraguard-security-suite' ) ],
                        'last_tested' => [ 'title' => __( 'Last Tested', 'ultraguard-security-suite' ) ],
                        'test_status' => [ 'title' => __( 'Test Result', 'ultraguard-security-suite' ) ],
                        'status'      => [ 'title' => __( 'Status',      'ultraguard-security-suite' ) ],
                        'actions'     => [ 'title' => __( 'Actions',     'ultraguard-security-suite' ), 'width' => '110px' ],
                    ],
                    'data'               => $data,
                    'searchable'         => true,
                    'search_placeholder' => __( 'Search channels…', 'ultraguard-security-suite' ),
                    'pagination'         => [ 'enabled' => true, 'page_size' => 20 ],
                    'empty_state'        => [
                        'title'       => __( 'No delivery channels configured', 'ultraguard-security-suite' ),
                        'description' => __( 'Add channels below to create reusable delivery destinations.', 'ultraguard-security-suite' ),
                    ],
                ],

                // Add channel form
                [
                    'type'  => 'card',
                    'id'    => 'channel-form',
                    'title' => __( 'Add Delivery Channel', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-plus-alt',
                    'data'  => [
                        [ 'type' => 'text',   'name' => 'name',           'label' => __( 'Channel Name',        'ultraguard-security-suite' ), 'required' => true, 'placeholder' => __( 'e.g. DevOps Slack, CTO Email', 'ultraguard-security-suite' ) ],
                        [
                            'type'    => 'select',
                            'name'    => 'channel_type',
                            'label'   => __( 'Channel Type', 'ultraguard-security-suite' ),
                            'options' => [
                                'email'        => __( 'Email',          'ultraguard-security-suite' ),
                                'slack'        => __( 'Slack Webhook',  'ultraguard-security-suite' ),
                                'webhook'      => __( 'Generic Webhook','ultraguard-security-suite' ),
                                'admin_notice' => __( 'Admin Notice',   'ultraguard-security-suite' ),
                            ],
                        ],
                        [ 'type' => 'text', 'name' => 'address',        'label' => __( 'Address / URL',         'ultraguard-security-suite' ), 'required' => true, 'placeholder' => __( 'Email address or webhook URL', 'ultraguard-security-suite' ) ],
                        [ 'type' => 'text', 'name' => 'webhook_secret',  'label' => __( 'HMAC Signing Secret',  'ultraguard-security-suite' ), 'placeholder' => __( 'Optional — for signed webhook payloads', 'ultraguard-security-suite' ) ],
                        [ 'type' => 'toggle', 'name' => 'is_active',    'label' => __( 'Enable Channel',        'ultraguard-security-suite' ), 'default' => true ],
                    ],
                    'footer' => [
                        'type'      => 'button-group',
                        'alignment' => 'right',
                        'buttons'   => [
                            $this->create_ajax_button( __( 'Save Channel', 'ultraguard-security-suite' ), 'ultraguard_notif_save_channel', [], 'primary', 'dashicons-saved' ),
                        ],
                    ],
                ],

                // Info card
                [
                    'type'  => 'card',
                    'title' => __( 'About Delivery Channels', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-info',
                    'data'  => [
                        [
                            'type'       => 'alert-box',
                            'alert_type' => 'info',
                            'icon'       => 'dashicons-info',
                            'message'    => __( 'Channels are saved delivery destinations that can be shared across multiple alert rules. For example, create a "DevOps Slack" channel once and reference it from as many rules as you need. Use the Test button to verify a channel is working before assigning it to rules.', 'ultraguard-security-suite' ),
                        ],
                    ],
                ],
            ],

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

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

    /**
     * Build channels data-table rows.
     *
     * @param  array $rows
     * @return array
     */
    private function build_channels_table_data( array $rows ): array {
        $data         = [];
        $nonce        = $this->create_nonce();
        $channel_opts = [
            'email'        => __( 'Email',          'ultraguard-security-suite' ),
            'slack'        => __( 'Slack Webhook',  'ultraguard-security-suite' ),
            'webhook'      => __( 'Generic Webhook','ultraguard-security-suite' ),
            'admin_notice' => __( 'Admin Notice',   'ultraguard-security-suite' ),
        ];

        foreach ( $rows as $r ) {
            $id          = (int) ( $r['id'] ?? 0 );
            $active      = ! empty( $r['is_active'] );
            $ch_type     = $r['channel_type'] ?? 'email';
            $test_status = $r['test_status']  ?? null;

            $view_modal = [
                'id'      => 'notif-ch-view-' . $id,
                /* translators: %s: string */
                'title'   => sprintf( __( 'Channel: %s', 'ultraguard-security-suite' ), esc_html( $r['name'] ?? '' ) ),
                'size'    => 'small',
                'content' => $this->modal_content( [
                    [ 'type' => 'text', 'name' => 'vch_name',  'label' => __( 'Name',        'ultraguard-security-suite' ), 'value' => esc_html( $r['name']    ?? '' ),                                                   'readonly' => true ],
                    [ 'type' => 'select', 'name' => 'vch_type','label' => __( 'Type',        'ultraguard-security-suite' ), 'value' => esc_attr( $ch_type ),       'options' => $channel_opts,                            'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vch_addr',  'label' => __( 'Address',     'ultraguard-security-suite' ), 'value' => esc_html( $r['address'] ?? '' ),                                                    'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vch_ts',    'label' => __( 'Last Tested', 'ultraguard-security-suite' ), 'value' => $r['last_tested_at'] ? esc_html( $this->format_time_ago( $r['last_tested_at'] ) ) : __( 'Never', 'ultraguard-security-suite' ), 'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vch_tr',    'label' => __( 'Test Result', 'ultraguard-security-suite' ), 'value' => $test_status ? ucfirst( $test_status ) : __( '—', 'ultraguard-security-suite' ),              'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vch_sts',   'label' => __( 'Status',      'ultraguard-security-suite' ), 'value' => $active ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Inactive', 'ultraguard-security-suite' ),   'readonly' => true ],
                ] ),
            ];

            $edit_modal = [
                'id'      => 'notif-ch-edit-' . $id,
                /* translators: %s: string */
                'title'   => sprintf( __( 'Edit Channel: %s', 'ultraguard-security-suite' ), esc_html( $r['name'] ?? '' ) ),
                'size'    => 'small',
                'content' => $this->modal_content( [
                    [ 'type' => 'text',   'name' => 'name',         'label' => __( 'Channel Name',    'ultraguard-security-suite' ), 'value' => esc_html( $r['name']    ?? '' ), 'required' => true ],
                    [ 'type' => 'select', 'name' => 'channel_type', 'label' => __( 'Channel Type',    'ultraguard-security-suite' ), 'value' => esc_attr( $ch_type ),            'options' => $channel_opts ],
                    [ 'type' => 'text',   'name' => 'address',      'label' => __( 'Address / URL',   'ultraguard-security-suite' ), 'value' => esc_html( $r['address'] ?? '' ), 'required' => true, 'placeholder' => __( 'Email address or webhook URL', 'ultraguard-security-suite' ) ],
                    [ 'type' => 'toggle', 'name' => 'is_active',    'label' => __( 'Enable Channel',  'ultraguard-security-suite' ), 'value' => $active ? '1' : '0' ],
                ] ),
                'footer' => $this->modal_footer_save( 'ultraguard_notif_save_channel', [ 'channel_id' => $id ] ),
            ];

            $data[] = [
                'id'              => 'ug-notif-channel-row-' . $id,
                'data-channel-id' => $id,
                'name'            => esc_html( $r['name'] ?? '' ),
                'type'            => [
                    'content' => ucfirst( str_replace( '_', ' ', $ch_type ) ),
                    'class'   => match ( $ch_type ) {
                        'slack'        => 'warning',
                        'webhook'      => 'info',
                        'admin_notice' => 'secondary',
                        default        => 'info',
                    },
                ],
                'address'     => esc_html( substr( $r['address'] ?? '', 0, 50 ) . ( strlen( $r['address'] ?? '' ) > 50 ? '…' : '' ) ),
                'last_tested' => $r['last_tested_at']
                    ? esc_html( $this->format_time_ago( $r['last_tested_at'] ) )
                    : __( 'Never', 'ultraguard-security-suite' ),
                'test_status' => $test_status ? [
                    'content' => $test_status === 'ok' ? __( 'OK', 'ultraguard-security-suite' ) : __( 'Failed', 'ultraguard-security-suite' ),
                    'class'   => $test_status === 'ok' ? 'success' : 'danger',
                ] : [ 'content' => '—', 'class' => 'secondary' ],
                'status'  => [
                    'content' => $active ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Inactive', '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 channel',   '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_channel', 'nonce' => $nonce, 'data' => [ 'channel_id' => $id ] ] ],
                    [ 'type' => 'button', 'text' => '', 'icon' => 'dashicons-trash',      'button_style' => 'danger',    'title' => __( 'Delete channel', 'ultraguard-security-suite' ),
                      /* translators: %s: string */
                      'ajax' => [ 'action' => 'ultraguard_notif_delete_channel', 'nonce' => $nonce, 'data' => [ 'channel_id' => $id ], 'confirm' => sprintf( __( 'Delete channel "%s"?', 'ultraguard-security-suite' ), esc_js( $r['name'] ?? '' ) ) ] ],
                ] ),
            ];
        }
        return $data;
    }
}

