<?php
/**
 * NotificationsStatistics — Notification analytics subpage.
 *
 * Standalone file required by PSR-4 autoloader:
 *   UltraguardPro\modules\notifications\pages\NotificationsStatistics
 *   → includes/modules/notifications/pages/class-notifications-statistics.php
 *
 * @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 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 );

        $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' ] ],
                    ],
                ],

                // 7-day volume trend
                [
                    'type'  => 'card',
                    'title' => __( 'Notification Volume — Last 7 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 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 );
    }
}
