<?php
/**
 * AuditLogPage — Audit Log viewer page.
 *
 * @package UltraguardPro\modules\audit_log\pages
 */

namespace UltraguardPro\modules\audit_log\pages;

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

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

class AuditLogPage extends BasePage {

    protected string $ajax_nonce_action = 'ultraguard_admin_nonce';

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

    public function get_scheme( $context ): array {
        $is_pro         = \UltraguardPro\support\LicenseInfo::instance()->isPro();
        $retention_days = $is_pro ? 90 : 7;

        $db    = $this->plugin->modules->get_db_tables();
        $table = $db ? $db->get_table( 'audit_logs' ) : null;

        $today  = gmdate( 'Y-m-d 00:00:00' );
        $total  = $table ? $table->count() : 0;
        $today_count  = $table ? $table->count( [ 'created_at >=' => $today ] ) : 0;
        $escalations  = $table ? $table->count( [ 'action' => 'privilege_escalation' ] ) : 0;
        $login_fails  = $table ? $table->count( [ 'action' => 'login_failed' ] ) : 0;

        // ── Chart data ────────────────────────────────────────────────────────
        // Activity trend over last 30 days
        $activity_trend = $table
            ? $table->get_chart_data( 'created_at', 'id', 'day', [], 30 )
            : [ 'labels' => [], 'data' => [] ];

        // Critical events only — privilege escalations, login failures, deletions
        $critical_trend = $table
            ? $table->get_chart_data( 'created_at', 'id', 'day',
                [ 'action' => [ 'privilege_escalation', 'login_failed', 'plugin_deleted', 'user_deleted', 'file_editor_accessed' ] ], 30 )
            : [ 'labels' => [], 'data' => [] ];

        // Events broken down by action type (top 5 to keep labels readable)
        $action_type_chart = $table
            ? $table->get_pie_chart_data( 'action', 'id', 'COUNT', [], 5 )
            : [ 'labels' => [], 'data' => [], 'colors' => [] ];

        // Hourly distribution for today
        $hourly_today = $table
            ? $table->get_chart_data( 'created_at', 'id', 'hour', [ 'created_at >=' => $today ], 24 )
            : [ 'labels' => [], 'data' => [] ];

        // Recent entries for initial display
        $rows = $table ? $table->get_by( [], 100, 'created_at', 'DESC' ) : [];

        $data = array_map( function( $r ) {
            $uid  = (int) ( $r['user_id'] ?? 0 );
            $user = $uid ? get_userdata( $uid ) : null;
            $old  = $r['old_values'] ? json_decode( $r['old_values'], true ) : null;
            $new  = $r['new_values'] ? json_decode( $r['new_values'], true ) : null;

            $action      = $r['action'] ?? '';
            $is_critical = in_array( $action, [ 'privilege_escalation', 'login_failed', 'plugin_deleted', 'user_deleted', 'critical_option_updated', 'file_editor_accessed' ], true );

            return [
                'id'           => 'ug-audit-log-row-' . (int) ( $r['id'] ?? 0 ),
                'data-log-id'  => (int) ( $r['id'] ?? 0 ),
                'action'       => [
                    'content' => esc_html( $action ),
                    'class'   => $is_critical ? 'danger' : 'secondary',
                ],
                'entity'       => esc_html( ( $r['entity_type'] ?? '' ) . ( $r['entity_id'] ? ' #' . $r['entity_id'] : '' ) ),
                'user'         => esc_html( $user ? $user->display_name : ( $uid ? 'User #' . $uid : __( 'System', 'ultraguard-security-suite' ) ) ),
                'ip_address'   => esc_html( $r['ip_address'] ?? '—' ),
                'changes'      => $old || $new
                    ? esc_html( $this->format_change( $old, $new ) )
                    : '—',
                'created_at'   => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),
            ];
        }, $rows );

        return apply_filters( 'ultraguard_audit_log_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-audit-log',
            'page_slug' => 'audit-log',
            'class'     => 'ultraguard-audit-log-page',

            'header' => [
                'title'    => __( 'Audit Log', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Complete record of admin actions, security events, and site changes.', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %d: number */
                    'text'       => sprintf( _n( '%d event today', '%d events today', $today_count, 'ultraguard-security-suite' ), $today_count ),
                    'badge_type' => $escalations > 0 ? 'danger' : ( $today_count > 0 ? 'warning' : 'success' ),
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Refresh',      'ultraguard-security-suite' ), 'ultraguard_audit_filter',  [], 'secondary', 'dashicons-update'   ),
                    $this->create_ajax_button( __( 'Export CSV',   'ultraguard-security-suite' ), 'ultraguard_audit_export',  [], 'secondary', 'dashicons-download' ),
                    $this->create_ajax_button( __( 'Clear Old (30d)', 'ultraguard-security-suite' ), 'ultraguard_audit_clear',   [ 'older_than_days' => 30 ], 'secondary', 'dashicons-trash',
                        __( 'Clear audit log entries older than 30 days?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Clear All',    'ultraguard-security-suite' ), 'ultraguard_audit_clear',   [ 'older_than_days' => 0 ], 'danger', 'dashicons-trash',
                        __( 'Clear the entire audit log? This cannot be undone.', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => array_values( array_filter( [
                // Retention warning for free users (shown first)
                $is_pro ? [] : $this->pro_retention_hint(
                    sprintf(
                        /* translators: %1$d = days, %2$s = cutoff date */
                        __( 'Your audit log shows the last %1$d days only. Events older than %2$s are automatically removed on the free plan. Upgrade to Pro to keep 90 days of complete history.', 'ultraguard-security-suite' ),
                        $retention_days,
                        gmdate( 'M j, Y', strtotime( '-' . $retention_days . ' days' ) )
                    ),
                    'audit_log_retention'
                ),

                // Stats
                [
                    'type'    => 'grid', 'columns' => 12, 'gap' => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Events',       'ultraguard-security-suite' ), 'value' => $total,       'format' => 'number', 'icon' => 'dashicons-list-view',    'class' => 'info'    ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Events Today',       'ultraguard-security-suite' ), 'value' => $today_count, 'format' => 'number', 'icon' => 'dashicons-clock',        'class' => 'warning' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Privilege Escalations', 'ultraguard-security-suite' ), 'value' => $escalations, 'format' => 'number', 'icon' => 'dashicons-admin-users', 'class' => $escalations > 0 ? 'danger' : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Login Failures',     'ultraguard-security-suite' ), 'value' => $login_fails, 'format' => 'number', 'icon' => 'dashicons-dismiss',      'class' => $login_fails > 0 ? 'warning' : 'success' ] ],
                    ],
                ],

                // ── Charts: Activity trend (line) + Action types (doughnut) ──
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 8,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Activity — Last 30 Days', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-line',
                                'data'  => empty( $activity_trend['data'] ) ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No activity recorded in the last 30 days.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'line',
                                        'height'         => '240px',
                                        'labels'         => $activity_trend['labels'],
                                        'datasets'       => [
                                            [
                                                'label'           => __( 'All Events', 'ultraguard-security-suite' ),
                                                'data'            => $activity_trend['data'],
                                                'borderColor'     => '#3b82f6',
                                                'backgroundColor' => 'rgba(59,130,246,0.10)',
                                                'fill'            => true,
                                                'tension'         => 0.4,
                                                'pointRadius'     => 3,
                                            ],
                                            [
                                                'label'           => __( 'Critical Events', 'ultraguard-security-suite' ),
                                                'data'            => $critical_trend['data'],
                                                'borderColor'     => '#ef4444',
                                                'backgroundColor' => 'rgba(239,68,68,0.08)',
                                                'fill'            => false,
                                                'tension'         => 0.4,
                                                'pointRadius'     => 3,
                                                'borderDash'      => [ 4, 3 ],
                                            ],
                                        ],
                                        'x_axis_title'   => __( 'Date', 'ultraguard-security-suite' ),
                                        'y_axis_title'   => __( 'Events', 'ultraguard-security-suite' ),
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Events by Action Type', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-pie',
                                'data'  => empty( $action_type_chart['data'] ) ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No events recorded yet.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'doughnut',
                                        'height'         => '240px',
                                        'labels'         => $action_type_chart['labels'],
                                        'datasets'       => [
                                            [
                                                'data'            => $action_type_chart['data'],
                                                'backgroundColor' => $action_type_chart['colors'],
                                                'borderWidth'     => 2,
                                            ],
                                        ],
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],

                // ── Today's hourly activity bar chart ─────────────────────────
                ! empty( $hourly_today['data'] ) ? [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 12,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( "Today's Hourly Activity", 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-clock',
                                'data'  => [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'bar',
                                        'height'         => '180px',
                                        'labels'         => $hourly_today['labels'],
                                        'datasets'       => [
                                            [
                                                'label'           => __( 'Events', 'ultraguard-security-suite' ),
                                                'data'            => $hourly_today['data'],
                                                'backgroundColor' => 'rgba(59,130,246,0.65)',
                                                'borderColor'     => '#3b82f6',
                                                'borderWidth'     => 1,
                                            ],
                                        ],
                                        'x_axis_title'   => __( 'Hour', 'ultraguard-security-suite' ),
                                        'y_axis_title'   => __( 'Count', 'ultraguard-security-suite' ),
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ] : [],

                // Filter bar + table
                [
                    'type'               => 'data-table',
                    'id'                 => 'audit-log-table',
                    'columns'            => [
                        'action'     => [ 'title' => __( 'Action',      'ultraguard-security-suite' ), 'sortable' => true ],
                        'entity'     => [ 'title' => __( 'Entity',      'ultraguard-security-suite' ) ],
                        'user'       => [ 'title' => __( 'User',        'ultraguard-security-suite' ) ],
                        'ip_address' => [ 'title' => __( 'IP Address',  'ultraguard-security-suite' ) ],
                        'changes'    => [ 'title' => __( 'Changes',     'ultraguard-security-suite' ) ],
                        'created_at' => [ 'title' => __( 'Time',        'ultraguard-security-suite' ), 'sortable' => true ],
                    ],
                    'data'               => $data,
                    'searchable'         => true,
                    'search_placeholder' => __( 'Search actions, entities, users…', 'ultraguard-security-suite' ),
                    'pagination'         => [ 'enabled' => true, 'page_size' => 50 ],
                    'empty_state'        => [
                        'title'       => __( 'No audit log entries', 'ultraguard-security-suite' ),
                        'description' => __( 'Events will appear here as admin actions, logins, and site changes are recorded.', 'ultraguard-security-suite' ),
                    ],
                ],
            ] ) ),

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

    // ─────────────────────────────────────────────────────────────────────────

    private function format_change( ?array $old, ?array $new ): string {
        if ( ! $old && ! $new ) { return ''; }
        if ( ! $old && $new )   { return '+' . $this->flatten( $new ); }
        if ( $old && ! $new )   { return '-' . $this->flatten( $old ); }

        $parts = [];
        $keys  = array_unique( array_merge( array_keys( $old ), array_keys( $new ) ) );
        foreach ( $keys as $k ) {
            $o = $old[ $k ] ?? null;
            $n = $new[ $k ] ?? null;
            if ( $o !== $n ) {
                $parts[] = $k . ': ' . $this->safe_scalar( $o ) . ' → ' . $this->safe_scalar( $n );
            }
        }
        return implode( '; ', array_slice( $parts, 0, 3 ) );
    }

    private function flatten( array $arr ): string {
        $out = [];
        foreach ( $arr as $k => $v ) {
            $out[] = $k . '=' . $this->safe_scalar( $v );
        }
        return implode( ', ', array_slice( $out, 0, 3 ) );
    }

    private function safe_scalar( $v ): string {
        if ( is_array( $v ) )   { return '[…]'; }
        if ( is_bool( $v ) )    { return $v ? 'true' : 'false'; }
        if ( is_null( $v ) )    { return 'null'; }
        $str = (string) $v;
        return strlen( $str ) > 40 ? substr( $str, 0, 40 ) . '…' : $str;
    }
}
