<?php
/**
 * NotificationsLog — Notification history and delivery log subpage.
 *
 * Standalone file required by PSR-4 autoloader:
 *   UltraguardPro\modules\notifications\pages\NotificationsLog
 *   → includes/modules/notifications/pages/class-notifications-log.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 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 ────────────────────────────────────────────────────────

    private function build_log_rows( array $rows ): array {
        $data  = [];
        $nonce = $this->create_nonce();

        foreach ( $rows as $r ) {
            $id      = (int) ( $r['id'] ?? 0 );
            $status  = $r['status']  ?? 'sent';
            $channel = $r['channel'] ?? 'email';

            $view_modal = [
                'id'      => 'notif-log-view-' . $id,
                /* translators: %d: integer */
                'title'   => sprintf( __( 'Log Entry #%d', 'ultraguard-security-suite' ), $id ),
                'size'    => 'medium',
                'content' => $this->modal_content( [
                    [ 'type' => 'text',     'name' => 'vl_type',    'label' => __( 'Event Type', 'ultraguard-security-suite' ), 'value' => esc_html( ucwords( str_replace( '_', ' ', $r['event_type'] ?? '' ) ) ), 'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vl_ch',      'label' => __( 'Channel',    'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( str_replace( '_', ' ', $channel ) ) ),               'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vl_recip',   'label' => __( 'Recipient',  'ultraguard-security-suite' ), 'value' => esc_html( $r['recipient']     ?? '' ),                                  'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vl_status',  'label' => __( 'Status',     'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $status ) ),                                          'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vl_sent',    'label' => __( 'Sent At',    'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $r['sent_at'] ?? $r['created_at'] ?? '' ) ), 'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vl_subj',    'label' => __( 'Subject',    'ultraguard-security-suite' ), 'value' => esc_html( $r['subject']       ?? '' ),                                  'readonly' => true ],
                    [ 'type' => 'textarea', 'name' => 'vl_msg',     'label' => __( 'Message',    'ultraguard-security-suite' ), 'value' => esc_html( $r['message']       ?? '' ), 'rows' => 5,                     'readonly' => true ],
                    [ 'type' => 'textarea', 'name' => 'vl_err',     'label' => __( 'Error',      'ultraguard-security-suite' ), 'value' => esc_html( $r['error_message'] ?? '—' ), 'rows' => 2,                    'readonly' => true ],
                ] ),
            ];

            $data[] = [
                'id'          => 'ug-notif-log-row-' . $id,
                'data-log-id' => $id,
                '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'] ?? '' ) ),
                'actions' => $this->row_actions( [
                    [
                        'type'         => 'button',
                        'text'         => '',
                        'icon'         => 'dashicons-visibility',
                        'button_style' => 'secondary',
                        'title'        => __( 'View full details', 'ultraguard-security-suite' ),
                        'modal'        => $view_modal,
                    ],
                    [
                        'type'         => 'button',
                        'text'         => '',
                        'icon'         => 'dashicons-trash',
                        'button_style' => 'danger',
                        'title'        => __( 'Delete log entry', 'ultraguard-security-suite' ),
                        'ajax'         => [
                            'action'  => 'ultraguard_notif_delete_log_entry',
                            'nonce'   => $nonce,
                            'data'    => [ 'log_id' => $id ],
                            'confirm' => __( 'Delete this notification log entry?', 'ultraguard-security-suite' ),
                        ],
                    ],
                ] ),
            ];
        }
        return $data;
    }

    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 ],
                'actions'    => [ 'title' => __( 'Actions',   'ultraguard-security-suite' ), 'width' => '90px' ],
            ],
            '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' ) ],
        ];
    }
}
