<?php
/**
 * NotificationsDashboard — Notifications overview page.
 *
 * No Closures anywhere — all schema data uses string helpers.
 *
 * @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 NotificationsDashboard 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;
        $rules_t = $db ? $db->get_table( 'notification_rules' ) : null;

        $today       = gmdate( 'Y-m-d 00:00:00' );
        $month_start = gmdate( 'Y-m-01 00:00:00' );

        $summary      = $log_t ? $log_t->get_stats_summary() : [];
        $sent_today   = $log_t   ? $log_t->count( [ 'status' => 'sent', 'sent_at >=' => $today ] )       : 0;
        $sent_month   = $log_t   ? $log_t->count( [ 'status' => 'sent', 'sent_at >=' => $month_start ] ) : 0;
        $failed       = (int)( $summary['total_failed'] ?? 0 );
        $total_sent   = (int)( $summary['total_sent']   ?? 0 );
        $delivery_rate= (float)( $summary['delivery_rate'] ?? 100.0 );
        $active_rules = $rules_t ? $rules_t->count( [ 'is_active' => 1 ] ) : 0;
        $total_rules  = $rules_t ? $rules_t->count()                        : 0;

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

        // Recent sent items — built as plain arrays (no Closures)
        $recent_sent   = $log_t ? $log_t->get_by( [ 'status' => 'sent'   ], 5, 'sent_at', 'DESC' ) : [];
        $recent_failed = $log_t ? $log_t->get_by( [ 'status' => 'failed' ], 5, 'created_at', 'DESC' ) : [];

        $sent_items   = $this->build_sent_list_items( $recent_sent );
        $failed_items = $this->build_failed_list_items( $recent_failed );

        $nonce = $this->create_nonce( 'ultraguard_admin_nonce' );

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

            'header' => [
                'title'    => __( 'Notifications', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Monitor security alert delivery, manage rules and review notification history.', 'ultraguard-security-suite' ),
                'badge'    => [
                    'text'       => $delivery_rate . '% ' . __( 'Delivery Rate', 'ultraguard-security-suite' ),
                    'badge_type' => $delivery_rate >= 95 ? 'success' : ( $delivery_rate >= 80 ? 'warning' : 'danger' ),
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Refresh Stats',   'ultraguard-security-suite' ), 'ultraguard_notif_refresh_stats', [], 'secondary', 'dashicons-update'    ),
                    $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 Alert Rule',  'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=notifications-rules' ), 'primary', 'dashicons-plus-alt' ),
                ],
            ],

            'data' => [
                // Stats row
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Sent Today',      'ultraguard-security-suite' ), 'value' => $sent_today,    'format' => 'number',     'icon' => 'dashicons-email-alt',    'class' => 'info'    ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Sent This Month', 'ultraguard-security-suite' ), 'value' => $sent_month,    'format' => 'number',     'icon' => 'dashicons-calendar-alt', 'class' => 'info'    ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Failed',          'ultraguard-security-suite' ), 'value' => $failed,        'format' => 'number',     'icon' => 'dashicons-warning',      'class' => $failed > 0 ? 'danger' : 'success' ] ],
                        [ 'span' => 4, 'component' => [
                            'type'  => 'stat-card', 'title' => __( 'Active Rules', 'ultraguard-security-suite' ), 'value' => $active_rules, 'format' => 'number', 'icon' => 'dashicons-filter', 'class' => $active_rules > 0 ? 'success' : 'secondary',
                            'trend' => [ 'direction' => 'neutral', 'value' => $total_rules, 'text' => __( 'total', 'ultraguard-security-suite' ) ],
                        ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Sent',      'ultraguard-security-suite' ), 'value' => $total_sent,    'format' => 'number',     'icon' => 'dashicons-email',        'class' => 'info'    ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Delivery Rate',   'ultraguard-security-suite' ), 'value' => $delivery_rate, 'format' => 'percentage', 'icon' => 'dashicons-chart-bar',    'class' => $delivery_rate >= 95 ? 'success' : 'warning' ] ],
                    ],
                ],

                // Chart + Recent lists
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 8,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Notification Volume — Last 7 Days', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-line',
                                'data'  => [
                                    [
                                        'type'       => 'chart',
                                        'chart_type' => 'line',
                                        'height'     => '220px',
                                        'labels'     => $chart_sent['labels'],
                                        'datasets'   => [
                                            [ 'label' => __( 'Sent',   'ultraguard-security-suite' ), 'data' => $chart_sent['data'],   'borderColor' => '#22c55e', 'backgroundColor' => 'rgba(34,197,94,0.08)',  'tension' => 0.4, 'fill' => true ],
                                            [ 'label' => __( 'Failed', 'ultraguard-security-suite' ), 'data' => $chart_failed['data'], 'borderColor' => '#dc2626', 'backgroundColor' => 'rgba(220,38,38,0.08)',  'tension' => 0.4, 'fill' => true ],
                                        ],
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'    => 'grid',
                                'columns' => 1,
                                'gap'     => '16px',
                                'items'   => [
                                    [ 'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Recently Sent', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-email-alt',
                                        'data'  => [ [ 'type' => 'list', 'items' => $sent_items ] ],
                                    ] ],
                                    [ 'component' => [
                                        'type'    => 'card',
                                        'title'   => __( 'Failed Deliveries', 'ultraguard-security-suite' ),
                                        'icon'    => 'dashicons-warning',
                                        'data'    => [ [ 'type' => 'list', 'items' => $failed_items ] ],
                                        'footer'  => ! empty( $recent_failed )
                                            ? $this->create_ajax_button( __( 'Retry Failed', 'ultraguard-security-suite' ), 'ultraguard_notif_retry_failed', [], 'secondary', 'dashicons-update' )
                                            : null,
                                    ] ],
                                ],
                            ],
                        ],
                    ],
                ],

                // Quick navigation
                [
                    'type'  => 'card',
                    'title' => __( 'Quick Navigation', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-admin-links',
                    'data'  => [
                        [
                            'type'      => 'button-group',
                            'alignment' => 'center',
                            'buttons'   => [
                                $this->create_url_button( __( 'Alert Rules',  'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=notifications-rules' ), 'primary',   'dashicons-filter'         ),
                                $this->create_url_button( __( 'Channels',     'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=notifications-channels' ), 'secondary', 'dashicons-admin-links'    ),
                                $this->create_url_button( __( 'Log',          'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=notifications-log' ), 'secondary', 'dashicons-list-view'      ),
                                $this->create_url_button( __( 'Statistics',   'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=notifications-statistics' ), 'secondary', 'dashicons-chart-bar'      ),
                                $this->create_url_button( __( 'Settings',     'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=notifications-settings' ), 'secondary', 'dashicons-admin-settings' ),
                            ],
                        ],
                    ],
                ],
            ],

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

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

    /**
     * Build list items for the "Recently Sent" card without Closures.
     *
     * @param  array $rows
     * @return array
     */
    private function build_sent_list_items( array $rows ): array {
        if ( empty( $rows ) ) {
            return [ [ 'icon' => 'dashicons-email', 'text' => __( 'No notifications sent yet.', 'ultraguard-security-suite' ) ] ];
        }
        $items = [];
        foreach ( $rows as $r ) {
            $items[] = [
                'icon'  => 'dashicons-email-alt',
                'text'  => esc_html( ucwords( str_replace( '_', ' ', $r['event_type'] ?? '' ) ) ),
                'badge' => [
                    'text'       => esc_html( $this->format_time_ago( $r['sent_at'] ?? '' ) ),
                    'badge_type' => 'success',
                ],
            ];
        }
        return $items;
    }

    /**
     * Build list items for the "Failed Deliveries" card without Closures.
     *
     * @param  array $rows
     * @return array
     */
    private function build_failed_list_items( array $rows ): array {
        if ( empty( $rows ) ) {
            return [ [ 'icon' => 'dashicons-yes-alt', 'text' => __( 'No failed deliveries.', 'ultraguard-security-suite' ) ] ];
        }
        $items = [];
        foreach ( $rows as $r ) {
            $items[] = [
                'icon'  => 'dashicons-warning',
                'text'  => esc_html( ( $r['event_type'] ?? '' ) . ' → ' . ( $r['recipient'] ?? '' ) ),
                'badge' => [
                    'text'       => esc_html( ucfirst( $r['channel'] ?? 'email' ) ),
                    'badge_type' => 'danger',
                ],
            ];
        }
        return $items;
    }
}
