<?php
/**
 * FilecheckerChanges — File change review and triage subpage.
 *
 * Provides:
 *   • 3 stat-cards   (modified, added, suspicious)
 *   • Tabbed data-table (All / Modified / Added / Suspicious)
 *   • Approve and Quarantine row actions
 *   • Bulk approve / quarantine-all header actions
 *
 * No Closures in schema — all HTML built via string helpers.
 *
 * @package UltraguardPro\modules\filechecker\pages
 * @since   6.5.0
 */

namespace UltraguardPro\modules\filechecker\pages;

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

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

class FilecheckerChanges 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;

        $modified   = $fi ? $fi->count( [ 'status' => 'modified' ] )   : 0;
        $added      = $fi ? $fi->count( [ 'status' => 'added' ] )       : 0;
        $suspicious = $fi ? $fi->count( [ 'status' => 'suspicious' ] )  : 0;
        $total      = $modified + $added + $suspicious;

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

        return apply_filters( 'ultraguard_filechecker_changes_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-filechecker-changes',
            'page_slug' => 'filechecker-changes',
            'class'     => 'ultraguard-filechecker-changes-page',

            'header' => [
                'title'    => __( 'File Changes', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Review, approve or quarantine detected file modifications, additions and suspicious files.', 'ultraguard-security-suite' ),
                'badge'    => [
                    /* translators: %d: number */
                    'text'       => sprintf( _n( '%d Change', '%d Changes', $total, 'ultraguard-security-suite' ), $total ),
                    'badge_type' => $total > 0 ? 'warning' : 'success',
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Refresh', 'ultraguard-security-suite' ), 'ultraguard_fc_refresh_changes', [], 'secondary', 'dashicons-update' ),
                    $this->create_ajax_button( __( 'Approve All', 'ultraguard-security-suite' ), 'ultraguard_fc_approve_all_changes', [], 'secondary', 'dashicons-yes',
                        __( 'Mark all current changes as approved?', 'ultraguard-security-suite' ) ),
                    $this->create_ajax_button( __( 'Quarantine Suspicious', 'ultraguard-security-suite' ), 'ultraguard_fc_quarantine_all', [], 'danger', 'dashicons-shield',
                        __( 'Quarantine all suspicious files? This will move them to the quarantine directory.', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => [
                // ── Contextual Pro nudge (free users only) ────────
                ...( UpgradeManager::should_show_nudge()
                    ? [ UpgradeManager::inline_hint( 'file_integrity_scan', __( 'File integrity scanning detects every modification, addition, and deletion on your server.', 'ultraguard-security-suite' ) ) ]
                    : [] ),


                // Stat row
                [
                    'type'       => 'grid',
                    'columns'    => 12,
                    'gap'        => '16px',
                    'responsive' => true,
                    'items'      => [
                        [
                            'span'      => 4,
                            'responsive'=> [ 'sm' => 12, 'md' => 4 ],
                            'component' => [
                                'type'  => 'stat-card',
                                'title' => __( 'Modified Files', 'ultraguard-security-suite' ),
                                'value' => $modified,
                                'format'=> 'number',
                                'icon'  => 'dashicons-edit',
                                'class' => $modified > 0 ? 'warning' : 'success',
                            ],
                        ],
                        [
                            'span'      => 4,
                            'responsive'=> [ 'sm' => 12, 'md' => 4 ],
                            'component' => [
                                'type'  => 'stat-card',
                                'title' => __( 'New Files Added', 'ultraguard-security-suite' ),
                                'value' => $added,
                                'format'=> 'number',
                                'icon'  => 'dashicons-plus-alt',
                                'class' => $added > 0 ? 'info' : 'success',
                            ],
                        ],
                        [
                            'span'      => 4,
                            'responsive'=> [ 'sm' => 12, 'md' => 4 ],
                            'component' => [
                                'type'  => 'stat-card',
                                'title' => __( 'Suspicious Files', 'ultraguard-security-suite' ),
                                'value' => $suspicious,
                                'format'=> 'number',
                                'icon'  => 'dashicons-shield-alt',
                                'class' => $suspicious > 0 ? 'danger' : 'success',
                            ],
                        ],
                    ],
                ],

                // Tabbed tables
                [
                    'type' => 'tabs',
                    'id'   => 'fc-changes-tabs',
                    'tabs' => [
                        [
                            'id'    => 'all-changes',
                            'title' => __( 'All Changes', 'ultraguard-security-suite' ) . ' (' . $total . ')',
                            'icon'  => 'dashicons-list-view',
                            'data'  => [ $this->changes_table( $fi, null, $nonce ) ],
                        ],
                        [
                            'id'    => 'modified',
                            'title' => __( 'Modified', 'ultraguard-security-suite' ) . ' (' . $modified . ')',
                            'icon'  => 'dashicons-edit',
                            'data'  => [ $this->changes_table( $fi, 'modified', $nonce ) ],
                        ],
                        [
                            'id'    => 'added',
                            'title' => __( 'Added', 'ultraguard-security-suite' ) . ' (' . $added . ')',
                            'icon'  => 'dashicons-plus-alt',
                            'data'  => [ $this->changes_table( $fi, 'added', $nonce ) ],
                        ],
                        [
                            'id'    => 'suspicious',
                            'title' => __( 'Suspicious', 'ultraguard-security-suite' ) . ' (' . $suspicious . ')',
                            'icon'  => 'dashicons-warning',
                            'data'  => [ $this->changes_table( $fi, 'suspicious', $nonce ) ],
                        ],
                    ],
                ],
            ],

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

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

    /**
     * Build a data-table array for one change-type tab.
     *
     * @param  mixed       $fi             FileIntegrityTable|null
     * @param  string|null $status_filter  Filter or null for all changes.
     * @param  string      $nonce
     * @return array
     */
    private function changes_table( $fi, ?string $status_filter, string $nonce ): array {
        $conds = $status_filter
            ? [ 'status' => $status_filter ]
            : [ 'status IN' => [ 'modified', 'added', 'suspicious' ] ];

        $rows = $fi ? $fi->get_by( $conds, 300, 'last_checked_at', 'DESC' ) : [];

        $data = array_map( function( $row ) use ( $nonce ) {
            $id     = (int) ( $row['id']     ?? 0 );
            $status = (string) ( $row['status'] ?? 'clean' );

            $view_modal = [
                'id'      => 'fc-view-change-' . $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' => 'vfc_path',  'label' => __( 'File Path',      'ultraguard-security-suite' ), 'value' => esc_html( $row['file_path']   ?? '' ),                               'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfc_sts',   'label' => __( 'Status',          'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $status ) ),                                      'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfc_chg',   'label' => __( 'Change Type',     'ultraguard-security-suite' ), 'value' => esc_html( ucwords( str_replace( '_', ' ', $row['change_type'] ?? '—' ) ) ), 'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfc_hash',  'label' => __( 'Current Hash',    'ultraguard-security-suite' ), 'value' => esc_html( $row['file_hash']    ?? '—' ),                             'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfc_prev',  'label' => __( 'Previous Hash',   'ultraguard-security-suite' ), 'value' => esc_html( $row['previous_hash'] ?? '—' ),                            'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfc_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' => 'vfc_type',  'label' => __( 'File Type',       'ultraguard-security-suite' ), 'value' => esc_html( $row['file_type']   ?? '—' ),                             'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfc_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' => 'vfc_appr',  'label' => __( 'Approved',        'ultraguard-security-suite' ), 'value' => ! empty( $row['is_approved'] ) ? __( 'Yes', 'ultraguard-security-suite' ) : __( 'No', 'ultraguard-security-suite' ), 'readonly' => true ],
                    [ 'type' => 'text', 'name' => 'vfc_dt',    'label' => __( 'Last Checked',    'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $row['last_checked_at'] ?? '' ) ), 'readonly' => true ],
                ] ),
            ];

            return [
                'id'           => 'fc-change-row-' . $id,
                'id'          => 'ug-fc-row-' . $id,
                'data-file-id' => $id,
                'file_path'    => esc_html( $row['file_path']   ?? '' ),
                'status'       => [
                    'content' => ucfirst( $status ),
                    'class'   => match ( $status ) {
                        'suspicious' => 'danger',
                        'modified'   => 'warning',
                        'added'      => 'info',
                        default      => 'secondary',
                    },
                ],
                'change_type'  => esc_html( ucwords( str_replace( '_', ' ', $row['change_type'] ?? '—' ) ) ),
                'file_size'    => ! empty( $row['file_size'] )
                    ? esc_html( size_format( (int) $row['file_size'] ) ) : '—',
                'is_core'      => [
                    'content' => ! empty( $row['is_core_file'] )
                        ? __( 'Core', 'ultraguard-security-suite' ) : __( 'Plugin/Theme', 'ultraguard-security-suite' ),
                    'class'   => ! empty( $row['is_core_file'] ) ? 'info' : 'secondary',
                ],
                'detected'     => esc_html( $this->format_date_time( $row['last_checked_at'] ?? '' ) ),
                'actions'      => $this->row_actions( [
                    [
                        'type'         => 'button',
                        'text'         => '',
                        'icon'         => 'dashicons-visibility',
                        'button_style' => 'secondary',
                        'title'        => __( 'View details', 'ultraguard-security-suite' ),
                        'modal'        => $view_modal,
                    ],
                    [
                        '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 ],
                        ],
                    ],
                    [
                        'type'         => 'button',
                        'text'         => '',
                        'icon'         => 'dashicons-lock',
                        'button_style' => 'danger',
                        'title'        => __( 'Quarantine file', 'ultraguard-security-suite' ),
                        'ajax'         => [
                            'action'  => 'ultraguard_fc_quarantine_file',
                            'nonce'   => $nonce,
                            'data'    => [ 'file_id' => $id ],
                            'confirm' => __( 'Move this file to quarantine?', 'ultraguard-security-suite' ),
                        ],
                    ],
                ] ),
            ];
        }, $rows );

        $table_id = 'fc-changes-table' . ( $status_filter ? '-' . $status_filter : '-all' );
        $label    = $status_filter
            /* translators: %s: string */
            ? sprintf( __( '%s Files', 'ultraguard-security-suite' ), ucfirst( $status_filter ) )
            : __( 'All Changed Files', 'ultraguard-security-suite' );

        return [
            'type'               => 'data-table',
            'id'                 => $table_id,
            'title'              => $label,
            '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_size'   => [ 'title' => __( 'Size',        'ultraguard-security-suite' ) ],
                'is_core'     => [ 'title' => __( 'Origin',      'ultraguard-security-suite' ) ],
                'detected'    => [ 'title' => __( 'Detected',    'ultraguard-security-suite' ), 'sortable' => true ],
                'actions'     => [ 'title' => __( 'Actions',     'ultraguard-security-suite' ), 'width' => '120px' ],
            ],
            'data'               => $data,
            'searchable'         => true,
            'search_placeholder' => __( 'Search file paths…', 'ultraguard-security-suite' ),
            'pagination'         => [ 'enabled' => true, 'page_size' => 25 ],
            'empty_state'        => [
                'title'       => $status_filter
                    /* translators: %s: string */
                    ? sprintf( __( 'No %s files found.', 'ultraguard-security-suite' ), $status_filter )
                    : __( 'No file changes detected.', 'ultraguard-security-suite' ),
                'description' => __( 'All monitored files are clean.', 'ultraguard-security-suite' ),
            ],
        ];
    }
}
