<?php
/**
 * HtaccessSecurityEvents — Security events log subpage.
 *
 * @package UltraguardPro\modules\htaccess\pages
 */

namespace UltraguardPro\modules\htaccess\pages;

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

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

class HtaccessSecurityEvents extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
    }

    public function get_scheme( $context ): array {
        $db    = $this->plugin->modules->get_db_tables();
        $logs  = $db ? $db->get_table( 'security_logs' ) : null;
        $total = $logs ? $logs->count() : 0;
        $today = gmdate( 'Y-m-d 00:00:00' );

        $rows = $logs ? $logs->get_by( [], 200, 'created_at', 'DESC' ) : [];
        $data = array_map( function( $r ) {
            $id     = (int) ( $r['id'] ?? 0 );
            $status = $r['status'] ?? 'open';
            $sev    = $r['severity'] ?? 'info';
            $ip     = esc_html( $r['ip_address'] ?? '' );

            $sev_class = ( $sev === 'critical' || $sev === 'high' ) ? 'danger'
                       : ( $sev === 'medium' ? 'warning' : ( $sev === 'low' ? 'info' : 'secondary' ) );
            $sts_class = $status === 'ignored' ? 'secondary' : ( $status === 'resolved' ? 'success' : 'warning' );

            $view_modal = [
                'id'      => 'htse-view-' . $id,
                /* translators: %d: integer */
                'title'   => sprintf( __( 'Security Event #%d', 'ultraguard-security-suite' ), $id ),
                'size'    => 'medium',
                'content' => $this->modal_content( [
                    [ 'type' => 'text',     'name' => 'vse_type', 'label' => __( 'Event Type',  'ultraguard-security-suite' ), 'value' => esc_html( ucwords( str_replace( '_', ' ', $r['event_type'] ?? '' ) ) ), 'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vse_sev',  'label' => __( 'Severity',    'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $sev ) ),                                              'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vse_ip',   'label' => __( 'IP Address',  'ultraguard-security-suite' ), 'value' => $ip,                                                                      'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vse_sts',  'label' => __( 'Status',      'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $status ) ),                                           'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vse_dt',   'label' => __( 'Time',        'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),            'readonly' => true ],
                    [ 'type' => 'textarea', 'name' => 'vse_msg',  'label' => __( 'Message',     'ultraguard-security-suite' ), 'value' => esc_html( $r['message'] ?? '' ), 'rows' => 5,                             'readonly' => true ],
                ] ),
            ];

            $btns = [
                [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-visibility',
                    'button_style' => 'secondary',
                    'title'        => __( 'View full details', 'ultraguard-security-suite' ),
                    'modal'        => $view_modal,
                ],
            ];

            if ( $status === 'open' ) {
                $btns[] = [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-hidden',
                    'button_style' => 'secondary',
                    'title'        => __( 'Mark as ignored', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_ignore_security_event',
                        'data'    => [ 'event_id' => $id ],
                        'confirm' => __( 'Mark this event as ignored?', 'ultraguard-security-suite' ),
                    ],
                ];
            }

            if ( $ip ) {
                $btns[] = [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-yes-alt',
                    'button_style' => 'warning',
                    'title'        => __( 'Whitelist IP', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_whitelist_ip_from_event',
                        'data'    => [ 'ip_address' => $ip ],
                        /* translators: %s: string */
                        'confirm' => sprintf( __( 'Add %s to the firewall whitelist?', 'ultraguard-security-suite' ), $ip ),
                    ],
                ];
            }

            $btns[] = [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-trash',
                'button_style' => 'danger',
                'title'        => __( 'Delete event', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_delete_security_event',
                    'data'    => [ 'event_id' => $id ],
                    'confirm' => __( 'Delete this security event log entry?', 'ultraguard-security-suite' ),
                ],
            ];

            return [
                'id'           => 'ug-htaccess-event-row-' . $id,
                'data-event-id' => $id,
                'event_type'    => esc_html( ucwords( str_replace( '_', ' ', $r['event_type'] ?? '' ) ) ),
                'severity'      => [ 'content' => ucfirst( $sev ), 'class' => $sev_class ],
                'ip_address'    => $ip,
                'message'       => esc_html( substr( $r['message'] ?? '', 0, 80 ) ),
                'status'        => [ 'content' => ucfirst( $status ), 'class' => $sts_class ],
                'created_at'    => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),
                'actions'       => $this->row_actions( $btns ),
            ];
        }, $rows );

        $chart = $logs ? $logs->get_chart_data( 'created_at', 'id', 'day', [], 7 ) : [ 'labels' => [], 'data' => [] ];

        return apply_filters( 'ultraguard_htaccess_security_events_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-htaccess-security-events',
            'page_slug' => 'htaccess-security-events',
            'class'     => 'ultraguard-htaccess-security-events-page',

            'header' => [
                'title'    => __( 'Security Events', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Monitor and manage .htaccess security incidents and access violations', 'ultraguard-security-suite' ),
                /* translators: %d: number */
                'badge'    => [ 'text' => sprintf( _n( '%d Event', '%d Events', $total, 'ultraguard-security-suite' ), $total ), 'badge_type' => $total > 0 ? 'warning' : 'success' ],
                'actions'  => [
                    $this->create_ajax_button( __( 'Refresh',       'ultraguard-security-suite' ), 'ultraguard_refresh_security_logs', [], 'secondary', 'dashicons-update'   ),
                    $this->create_ajax_button( __( 'Export Events', 'ultraguard-security-suite' ), 'ultraguard_export_security_logs',  [], 'secondary', 'dashicons-download' ),
                    $this->create_ajax_button( __( 'Clear Logs',    'ultraguard-security-suite' ), 'ultraguard_clear_security_logs',   [], 'danger',    'dashicons-trash',   __( 'Clear all security event logs? This cannot be undone.', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => [
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Events',  'ultraguard-security-suite' ), 'value' => $total, 'format' => 'number', 'icon' => 'dashicons-flag',       'class' => $total > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Events Today',  'ultraguard-security-suite' ), 'value' => $logs ? $logs->count( [ 'created_at >=' => $today ] ) : 0, 'format' => 'number', 'icon' => 'dashicons-clock', 'class' => 'info' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Open Issues',   'ultraguard-security-suite' ), 'value' => $logs ? $logs->count( [ 'status' => 'open' ] ) : 0, 'format' => 'number', 'icon' => 'dashicons-warning', 'class' => 'danger' ] ],
                    ],
                ],

                [
                    'type'  => 'card',
                    'title' => __( 'Event Activity (Last 7 Days)', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-chart-line',
                    'data'  => [ [ 'type' => 'chart', 'chart_type' => 'bar', 'height' => '200px', 'labels' => $chart['labels'], 'datasets' => [ [ 'label' => __( 'Events', 'ultraguard-security-suite' ), 'data' => $chart['data'], 'backgroundColor' => 'rgba(239,68,68,0.6)', 'borderColor' => '#ef4444' ] ], 'security_theme' => true ] ],
                ],

                [
                    'type'         => 'data-table',
                    'id'           => 'htaccess-security-events-table',
                    'columns'      => [
                        'event_type' => [ 'title' => __( 'Event Type', 'ultraguard-security-suite' ), 'sortable' => true ],
                        'severity'   => [ 'title' => __( 'Severity',   'ultraguard-security-suite' ) ],
                        'ip_address' => [ 'title' => __( 'IP Address', 'ultraguard-security-suite' ), 'sortable' => true ],
                        'message'    => [ 'title' => __( 'Message',    'ultraguard-security-suite' ) ],
                        'status'     => [ 'title' => __( 'Status',     'ultraguard-security-suite' ) ],
                        'created_at' => [ 'title' => __( 'Time',       'ultraguard-security-suite' ), 'sortable' => true ],
                        'actions'    => [ 'title' => __( 'Actions',    'ultraguard-security-suite' ), 'width' => '130px' ],
                    ],
                    'data'         => $data,
                    'searchable'   => true,
                    'bulk_actions' => [
                        'ignore'       => __( 'Ignore Selected',      'ultraguard-security-suite' ),
                        'whitelist_ip' => __( 'Whitelist IP',          'ultraguard-security-suite' ),
                        'export'       => __( 'Export Selected',       'ultraguard-security-suite' ),
                    ],
                    'pagination'   => [ 'enabled' => true, 'page_size' => 25 ],
                    'empty_state'  => [ 'title' => __( 'No security events', 'ultraguard-security-suite' ), 'description' => __( 'No security events have been recorded yet.', 'ultraguard-security-suite' ) ],
                ],
            ],

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