<?php
/**
 * FilecheckerHistory — Scan session history and file record audit log.
 *
 * @package UltraguardPro\modules\filechecker\pages
 * @since   6.5.0
 */

namespace UltraguardPro\modules\filechecker\pages;

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

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

class FilecheckerHistory 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();
        $fi   = $db ? $db->get_table( 'file_integrity' ) : null;
        $sess = $db ? $db->get_table( 'scan_sessions' )  : null;

        $stats   = $sess ? $sess->get_scan_statistics() : [];
        $total_s = (int)    ( $stats['total_scans']         ?? 0 );
        $total_f = (int)    ( $stats['total_files_scanned'] ?? 0 );
        $total_c = (int)    ( $stats['total_changes_found'] ?? 0 );
        $last    = (string) ( $stats['last_scan_at']        ?? '' );

        // 30-day scan activity
        $chart_all = $fi
            ? $fi->get_chart_data( 'last_checked_at', 'id', 'day', [],                          30 )
            : [ 'labels' => [], 'data' => [] ];
        $chart_mod = $fi
            ? $fi->get_chart_data( 'last_checked_at', 'id', 'day', [ 'status' => 'modified' ], 30 )
            : [ 'labels' => [], 'data' => [] ];

        // FIX 1: declare $nonce BEFORE both closures that reference it.
        $nonce = $this->create_nonce();

        // ── Scan sessions ──────────────────────────────────────────────────────
        $sessions     = $sess ? $sess->get_recent_completed( 50 ) : [];
        $session_rows = array_map( function( $s ) use ( $nonce ) {
            $sid = (int) ( $s['id'] ?? 0 );
            $dur = $this->calc_duration( $s['started_at'] ?? '', $s['completed_at'] ?? '' );

            $view_modal = [
                'id'      => 'fc-view-sess-' . $sid,
                /* translators: %d: integer */
                'title'   => sprintf( __( 'Scan Session #%d', 'ultraguard-security-suite' ), $sid ),
                'size'    => 'medium',
                'content' => $this->modal_content( [
                    [ 'type' => 'text', 'name' => 'vss_type',  'label' => __( 'Scan Type',     'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $s['scan_type'] ?? 'full' ) ),                                                                                      'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_sts',   'label' => __( 'Status',         'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $s['status'] ?? '' ) ),                                                                                             'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_files', 'label' => __( 'Files Scanned',  'ultraguard-security-suite' ), 'value' => number_format_i18n( (int) ( $s['files_scanned']  ?? 0 ) ),                                                                             'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_chgs',  'label' => __( 'Changes Found',  'ultraguard-security-suite' ), 'value' => number_format_i18n( (int) ( $s['changes_found']  ?? 0 ) ),                                                                             'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_add',   'label' => __( 'Added Files',    'ultraguard-security-suite' ), 'value' => number_format_i18n( (int) ( $s['added_files']    ?? 0 ) ),                                                                             'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_mod',   'label' => __( 'Modified Files', 'ultraguard-security-suite' ), 'value' => number_format_i18n( (int) ( $s['modified_files'] ?? 0 ) ),                                                                             'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_sus',   'label' => __( 'Suspicious',     'ultraguard-security-suite' ), 'value' => number_format_i18n( (int) ( $s['suspicious']      ?? 0 ) ),                                                                             'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_start', 'label' => __( 'Started',        'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $s['started_at']   ?? '' ) ),                                                                       'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_end',   'label' => __( 'Completed',      'ultraguard-security-suite' ), 'value' => $s['completed_at'] ? esc_html( $this->format_date_time( $s['completed_at'] ) ) : '—',                                                  'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_dur',   'label' => __( 'Duration',       'ultraguard-security-suite' ), 'value' => esc_html( $dur ),                                                                                                                       'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vss_err',   'label' => __( 'Error Message',  'ultraguard-security-suite' ), 'value' => esc_html( $s['error_message'] ?? '—' ),                                                                                                 'readonly' => true ],
                ] ),
            ];

            return [
                'id'              => 'fc-sess-row-' . $sid,
                'id'             => 'ug-fc-session-row-' . $sid,
                'data-session-id' => $sid,
                'scan_type'       => [ 'content' => ucfirst( $s['scan_type'] ?? 'full' ), 'class' => $s['scan_type'] === 'quick' ? 'info' : 'secondary' ],
                'started_at'      => esc_html( $this->format_date_time( $s['started_at'] ?? '' ) ),
                'duration'        => $dur,
                'files_scanned'   => number_format_i18n( (int) ( $s['files_scanned'] ?? 0 ) ),
                'changes_found'   => [
                    'content' => number_format_i18n( (int) ( $s['changes_found'] ?? 0 ) ),
                    'class'   => (int) ( $s['changes_found'] ?? 0 ) > 0 ? 'warning' : 'success',
                ],
                'status' => [
                    'content' => ucfirst( $s['status'] ?? 'completed' ),
                    'class'   => match ( $s['status'] ?? 'completed' ) {
                        'completed' => 'success',
                        'failed'    => 'danger',
                        'cancelled' => 'secondary',
                        default     => 'info',
                    },
                ],
                'actions' => $this->row_actions( [
                    [
                        'type'         => 'button',
                        'text'         => '',
                        'icon'         => 'dashicons-visibility',
                        'button_style' => 'secondary',
                        'title'        => __( 'View session details', 'ultraguard-security-suite' ),
                        'modal'        => $view_modal,
                    ],
                    [
                        'type'         => 'button',
                        'text'         => '',
                        'icon'         => 'dashicons-trash',
                        'button_style' => 'danger',
                        'title'        => __( 'Delete session record', 'ultraguard-security-suite' ),
                        'ajax'         => [
                            'action'  => 'ultraguard_fc_delete_session',
                            'nonce'   => $nonce,
                            'data'    => [ 'session_id' => $sid ],
                            'confirm' => __( 'Delete this scan session record?', 'ultraguard-security-suite' ),
                        ],
                    ],
                ] ),
            ];
        }, $sessions );

        // ── File records ───────────────────────────────────────────────────────
        $records   = $fi ? $fi->get_by( [], 500, 'last_checked_at', 'DESC' ) : [];
        $file_rows = array_map( function( $row ) use ( $nonce ) {
            $id     = (int) ( $row['id'] ?? 0 );
            $status = $row['status'] ?? 'clean';

            $view_modal = [
                'id'      => 'fc-view-rec-' . $id,
                /* translators: %s: string */
                'title'   => sprintf( __( 'File Record: %s', 'ultraguard-security-suite' ), esc_html( basename( $row['file_path'] ?? '' ) ) ),
                'size'    => 'medium',
                'content' => $this->modal_content( [
                    [ 'type' => 'text', 'name' => 'vfr_path', 'label' => __( 'File Path',    'ultraguard-security-suite' ), 'value' => esc_html( $row['file_path']    ?? '' ),                                                                                          'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_sts',  'label' => __( 'Status',        'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $status ) ),                                                                                                  'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_chg',  'label' => __( 'Change Type',   'ultraguard-security-suite' ), 'value' => esc_html( ucwords( str_replace( '_', ' ', $row['change_type'] ?? '—' ) ) ),                                                     'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_hash', 'label' => __( 'File Hash',     'ultraguard-security-suite' ), 'value' => esc_html( $row['file_hash']    ?? '—' ),                                                                                         'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_prev', 'label' => __( 'Previous Hash', 'ultraguard-security-suite' ), 'value' => esc_html( $row['previous_hash'] ?? '—' ),                                                                                        'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_size', 'label' => __( 'File Size',     'ultraguard-security-suite' ), 'value' => ! empty( $row['file_size'] ) ? esc_html( size_format( (int) $row['file_size'] ) ) : '—',                                        'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_type', 'label' => __( 'File Type',     'ultraguard-security-suite' ), 'value' => esc_html( $row['file_type']    ?? '—' ),                                                                                         'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_core', 'label' => __( 'Origin',         'ultraguard-security-suite' ), 'value' => ! empty( $row['is_core_file'] ) ? __( 'Core', 'ultraguard-security-suite' ) : __( 'Plugin/Theme', 'ultraguard-security-suite' ),                     'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_appr', 'label' => __( 'Approved',       'ultraguard-security-suite' ), 'value' => ! empty( $row['is_approved'] )  ? __( 'Yes',  'ultraguard-security-suite' ) : __( 'No', 'ultraguard-security-suite' ),                               'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfr_dt',   'label' => __( 'Last Checked',  'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $row['last_checked_at'] ?? '' ) ),                                                            'readonly' => true ],
                ] ),
            ];

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

            if ( in_array( $status, [ 'modified', 'added', 'suspicious' ], true ) ) {
                $btns[] = [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-yes',
                    'button_style' => 'secondary',
                    'title'        => __( 'Approve change', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action' => 'ultraguard_fc_approve_change',
                        'nonce'  => $nonce,
                        'data'   => [ 'file_id' => $id ],
                    ],
                ];
            }

            $btns[] = [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-trash',
                'button_style' => 'danger',
                'title'        => __( 'Delete record', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_fc_delete_file_record',
                    'nonce'   => $nonce,
                    'data'    => [ 'file_id' => $id ],
                    'confirm' => __( 'Delete this file integrity record?', 'ultraguard-security-suite' ),
                ],
            ];

            // FIX 2: properly closed return array, with 'actions' included.
            return [
                'id'            => 'ug-fc-record-row-' . $id,
                'data-record-id' => $id,
                'file_path'      => esc_html( $row['file_path']  ?? '' ),
                'status'         => [
                    'content' => ucfirst( $status ),
                    'class'   => match ( $status ) {
                        'suspicious', 'quarantined' => 'danger',
                        'modified'                  => 'warning',
                        'added'                     => 'info',
                        'clean'                     => 'success',
                        default                     => 'secondary',
                    },
                ],
                'change_type'  => esc_html( ucwords( str_replace( '_', ' ', $row['change_type'] ?? '—' ) ) ),
                'file_hash'    => esc_html( substr( $row['file_hash'] ?? '', 0, 12 ) . '…' ),
                'file_size'    => ! empty( $row['file_size'] ) ? esc_html( size_format( (int) $row['file_size'] ) ) : '—',
                'origin'       => [
                    'content' => ! empty( $row['is_core_file'] ) ? __( 'Core', 'ultraguard-security-suite' ) : __( 'Plugin/Theme', 'ultraguard-security-suite' ),
                    'class'   => ! empty( $row['is_core_file'] ) ? 'info' : 'secondary',
                ],
                'last_checked' => esc_html( $this->format_date_time( $row['last_checked_at'] ?? '' ) ),
                'actions'      => $this->row_actions( $btns ),
            ];
        }, $records ); // FIX 3: closure properly terminated here.

        // FIX 4: apply_filters() is the method's return, NOT inside a closure.
        return apply_filters( 'ultraguard_filechecker_history_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-filechecker-history',
            'page_slug' => 'filechecker-history',
            'class'     => 'ultraguard-filechecker-history-page',

            'header' => [
                'title'    => __( 'Scan History', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Audit trail of all scan sessions and file integrity checks.', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %d: number */
                    'text'       => sprintf( _n( '%d scan', '%d scans', $total_s, 'ultraguard-security-suite' ), $total_s ),
                    'badge_type' => 'info',
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Export CSV',    'ultraguard-security-suite' ), 'ultraguard_fc_export_history', [], 'secondary', 'dashicons-download' ),
                    $this->create_ajax_button( __( 'Prune Old',     'ultraguard-security-suite' ), 'ultraguard_fc_prune_sessions', [], 'secondary', 'dashicons-update',
                        __( 'Remove scan sessions older than 90 days?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Clear History', 'ultraguard-security-suite' ), 'ultraguard_fc_clear_history',  [], 'danger',    'dashicons-trash',
                        __( 'Delete ALL file integrity records? This cannot be undone.', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => [
                // Stat row
                [
                    'type'       => 'grid',
                    'columns'    => 12,
                    'gap'        => '16px',
                    'responsive' => true,
                    'items'      => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Scans',   'ultraguard-security-suite' ), 'value' => $total_s, 'format' => 'number', 'icon' => 'dashicons-backup',        'class' => 'info'      ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Files Scanned', 'ultraguard-security-suite' ), 'value' => $total_f, 'format' => 'number', 'icon' => 'dashicons-media-document', 'class' => 'secondary' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Changes Found', 'ultraguard-security-suite' ), 'value' => $total_c, 'format' => 'number', 'icon' => 'dashicons-warning',        'class' => $total_c > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Last Scan',     'ultraguard-security-suite' ), 'value' => $last ? $this->format_time_ago( $last ) : __( 'Never', 'ultraguard-security-suite' ), 'format' => 'text', 'icon' => 'dashicons-clock', 'class' => 'info' ] ],
                    ],
                ],

                // Activity chart
                [
                    'type'  => 'card',
                    'id'    => 'fc-activity-chart',
                    'title' => __( 'Scan Activity — Last 30 Days', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-chart-line',
                    'data'  => [ [
                        'type'       => 'chart',
                        'chart_type' => 'line',
                        'height'     => '260px',
                        'labels'     => $chart_all['labels'],
                        'datasets'   => [
                            [
                                'label'           => __( 'Files Checked', 'ultraguard-security-suite' ),
                                'data'            => $chart_all['data'],
                                'borderColor'     => '#3b82f6',
                                'backgroundColor' => 'rgba(59,130,246,0.1)',
                                'tension'         => 0.4,
                                'fill'            => true,
                            ],
                            [
                                'label'           => __( 'Changes Detected', 'ultraguard-security-suite' ),
                                'data'            => $chart_mod['data'],
                                'borderColor'     => '#f59e0b',
                                'backgroundColor' => 'rgba(245,158,11,0.1)',
                                'tension'         => 0.4,
                                'fill'            => true,
                            ],
                        ],
                        'security_theme' => true,
                    ] ],
                ],

                // Scan sessions table — FIX 5: 'actions' column added.
                [
                    'type'        => 'data-table',
                    'id'          => 'fc-sessions-table',
                    'title'       => __( 'Scan Sessions', 'ultraguard-security-suite' ),
                    'columns'     => [
                        'scan_type'     => [ 'title' => __( 'Type',          'ultraguard-security-suite' ) ],
                        'started_at'    => [ 'title' => __( 'Started',       'ultraguard-security-suite' ), 'sortable' => true ],
                        'duration'      => [ 'title' => __( 'Duration',      'ultraguard-security-suite' ) ],
                        'files_scanned' => [ 'title' => __( 'Files Scanned', 'ultraguard-security-suite' ) ],
                        'changes_found' => [ 'title' => __( 'Changes Found', 'ultraguard-security-suite' ) ],
                        'status'        => [ 'title' => __( 'Status',        'ultraguard-security-suite' ) ],
                        'actions'       => [ 'title' => __( 'Actions',       'ultraguard-security-suite' ), 'width' => '90px' ],
                    ],
                    'data'        => $session_rows,
                    'pagination'  => [ 'enabled' => true, 'page_size' => 15 ],
                    'empty_state' => [
                        'title'       => __( 'No scan sessions found', 'ultraguard-security-suite' ),
                        'description' => __( 'Run a file integrity check to populate this list.', 'ultraguard-security-suite' ),
                    ],
                ],

                // Full file record table — FIX 6: 'actions' column added.
                [
                    'type'               => 'data-table',
                    'id'                 => 'fc-history-table',
                    'title'              => __( 'Complete File Record', 'ultraguard-security-suite' ),
                    'columns'            => [
                        'file_path'    => [ 'title' => __( 'File Path',    'ultraguard-security-suite' ), 'sortable' => true ],
                        'status'       => [ 'title' => __( 'Status',       'ultraguard-security-suite' ) ],
                        'change_type'  => [ 'title' => __( 'Change Type',  'ultraguard-security-suite' ) ],
                        'file_hash'    => [ 'title' => __( 'Hash',         'ultraguard-security-suite' ) ],
                        'file_size'    => [ 'title' => __( 'Size',         'ultraguard-security-suite' ) ],
                        'origin'       => [ 'title' => __( 'Origin',       'ultraguard-security-suite' ) ],
                        'last_checked' => [ 'title' => __( 'Last Checked', 'ultraguard-security-suite' ), 'sortable' => true ],
                        'actions'      => [ 'title' => __( 'Actions',      'ultraguard-security-suite' ), 'width' => '110px' ],
                    ],
                    'data'               => $file_rows,
                    'searchable'         => true,
                    'search_placeholder' => __( 'Search file paths…', 'ultraguard-security-suite' ),
                    'pagination'         => [ 'enabled' => true, 'page_size' => 25 ],
                    'empty_state'        => [
                        'title'       => __( 'No file records', 'ultraguard-security-suite' ),
                        'description' => __( 'Run a file integrity check to populate this log.', 'ultraguard-security-suite' ),
                    ],
                ],
            ],

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

    // ── Private helpers ────────────────────────────────────────────────────────

    /**
     * Calculate a human-readable duration between two datetime strings.
     */
    private function calc_duration( string $started, string $completed ): string {
        if ( ! $started || ! $completed ) { return '—'; }
        $diff = strtotime( $completed ) - strtotime( $started );
        if ( $diff < 0 )  { return '—'; }
        if ( $diff < 60 ) { return sprintf( '%ds', $diff ); }
        $min = (int) floor( $diff / 60 );
        $sec = $diff % 60;
        return $sec > 0
            ? sprintf( '%dm %ds', $min, $sec )
            : sprintf( '%dm', $min );
    }
}
