<?php
/**
 * FilecheckerMonitoring — Monitored directories and coverage statistics.
 *
 * Displays:
 *   • 4 stat-cards  (total, clean, modified, new files)
 *   • Monitored directories data-table (with add/remove)
 *   • 7-day scan activity bar chart
 *   • Monitoring scope settings card (inline save — no sticky footer needed)
 *
 * @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 FilecheckerMonitoring 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;

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

        $enabled      = $this->get_setting( 'filechecker_enabled',      true );
        $scan_core    = $this->get_setting( 'filechecker_scan_core',    true );
        $scan_plugins = $this->get_setting( 'filechecker_scan_plugins', true );
        $scan_themes  = $this->get_setting( 'filechecker_scan_themes',  true );
        $scan_uploads = $this->get_setting( 'filechecker_scan_uploads', false );
        $schedule     = $this->get_setting( 'filechecker_schedule',     'daily' );
        $extra_dirs   = (array) $this->get_setting( 'filechecker_extra_dirs', [] );

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

        // Build the monitored directories list (built-in + custom)
        $monitored = $this->build_dir_list( $scan_core, $scan_plugins, $scan_themes, $scan_uploads, $extra_dirs, $nonce );

        // 7-day scan activity chart
        $chart = $fi
            ? $fi->get_chart_data( 'last_checked_at', 'id', 'day', [], 7 )
            : [ 'labels' => [], 'data' => [] ];

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

            'header' => [
                'title'    => __( 'File Monitoring', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Configure monitored directories, scan scope and schedule.', 'ultraguard-security-suite' ),
                'badge'    => [
                    'text'       => $enabled ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ),
                    'badge_type' => $enabled ? 'success' : 'secondary',
                ],
                'actions' => [
                    $this->create_ajax_button( __( 'Quick Scan', 'ultraguard-security-suite' ),    'ultraguard_fc_start_quick_scan',  [], 'primary',   'dashicons-clock' ),
                    $this->create_ajax_button( __( 'Refresh Stats', 'ultraguard-security-suite' ), 'ultraguard_fc_refresh_monitoring', [], 'secondary', 'dashicons-update' ),
                ],
            ],

            'data' => [
                // Stat row
                [
                    'type'       => 'grid',
                    'columns'    => 12,
                    'gap'        => '16px',
                    'responsive' => true,
                    'items'      => [
                        [ 'span' => 3, 'responsive' => [ 'sm' => 12, 'md' => 6 ], 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Files',  'ultraguard-security-suite' ), 'value' => $total,    'format' => 'number', 'icon' => 'dashicons-media-document', 'class' => 'info'    ] ],
                        [ 'span' => 3, 'responsive' => [ 'sm' => 12, 'md' => 6 ], 'component' => [ 'type' => 'stat-card', 'title' => __( 'Clean Files',  'ultraguard-security-suite' ), 'value' => $clean,    'format' => 'number', 'icon' => 'dashicons-yes-alt',        'class' => 'success' ] ],
                        [ 'span' => 3, 'responsive' => [ 'sm' => 12, 'md' => 6 ], 'component' => [ 'type' => 'stat-card', 'title' => __( 'Modified',     'ultraguard-security-suite' ), 'value' => $modified, 'format' => 'number', 'icon' => 'dashicons-edit',           'class' => $modified > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 3, 'responsive' => [ 'sm' => 12, 'md' => 6 ], 'component' => [ 'type' => 'stat-card', 'title' => __( 'New Files',    'ultraguard-security-suite' ), 'value' => $added,    'format' => 'number', 'icon' => 'dashicons-plus-alt',       'class' => 'info'    ] ],
                    ],
                ],

                // Directories + chart
                [
                    'type'    => 'grid',
                    'columns' => 2,
                    'gap'     => '20px',
                    'items'   => [
                        [ 'component' => $this->directories_card( $monitored, $nonce ) ],
                        [ 'component' => $this->activity_chart( $chart ) ],
                    ],
                ],

                // Monitoring scope settings (inline save — own button in footer)
                $this->scope_card( $enabled, $scan_core, $scan_plugins, $scan_themes, $scan_uploads, $schedule, $nonce ),
            ],

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

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

    /**
     * Assemble the monitored-directories table rows.
     */
    private function build_dir_list(
        bool $scan_core, bool $scan_plugins, bool $scan_themes, bool $scan_uploads,
        array $extra, string $nonce
    ): array {
        $built = [];
        if ( $scan_core )    { $built[] = [ ABSPATH . 'wp-includes', 'WP Core (wp-includes)', false ]; }
        if ( $scan_core )    { $built[] = [ ABSPATH . 'wp-admin',    'WP Core (wp-admin)',    false ]; }
        if ( $scan_plugins ) { $built[] = [ WP_CONTENT_DIR . '/plugins', 'Plugins',           false ]; }
        if ( $scan_themes )  { $built[] = [ WP_CONTENT_DIR . '/themes',  'Themes',            false ]; }
        if ( $scan_uploads ) { $built[] = [ WP_CONTENT_DIR . '/uploads', 'Uploads',           false ]; }
        foreach ( $extra as $d ) {
            if ( $d ) { $built[] = [ (string) $d, (string) $d, true ]; }
        }

        return array_map( function( $d ) use ( $nonce ) {
            [ $path, $label, $removable ] = $d;
            $exists = is_dir( $path );
            return [
                'data-dir'   => esc_attr( $path ),
                'label'      => esc_html( $label ),
                'path'       => esc_html( $path ),
                'status'     => [
                    'content' => $exists ? __( 'OK', 'ultraguard-security-suite' ) : __( 'Missing', 'ultraguard-security-suite' ),
                    'class'   => $exists ? 'success' : 'danger',
                ],
                'type'       => [ 'content' => $removable ? __( 'Custom', 'ultraguard-security-suite' ) : __( 'Built-in', 'ultraguard-security-suite' ), 'class' => $removable ? 'info' : 'secondary' ],
                'actions'    => $removable
                    ? $this->row_actions( [
                        [
                            'type'         => 'button',
                            'text'         => __( 'Remove', 'ultraguard-security-suite' ),
                            'button_style' => 'danger',
                            'ajax'         => [
                                'action'  => 'ultraguard_fc_remove_directory',
                                'nonce'   => $nonce,
                                'confirm' => __( 'Remove this directory from monitoring?', 'ultraguard-security-suite' ),
                                'data'    => [ 'directory' => $path ],
                            ],
                        ],
                    ] )
                    : [ 'content' => '-' ],
            ];
        }, $built );
    }

    /**
     * Monitored directories card with add-directory action.
     */
    private function directories_card( array $rows, string $nonce ): array {
        return [
            'type'    => 'card',
            'id'      => 'fc-monitored-dirs-card',
            'title'   => __( 'Monitored Directories', 'ultraguard-security-suite' ),
            'icon'    => 'dashicons-portfolio',
            'actions' => [
                [
                    'type'         => 'button',
                    'text'         => __( 'Add Directory', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                    'icon'         => 'dashicons-plus-alt',
                    'ajax'         => [ 'action' => 'ultraguard_fc_add_directory', 'nonce' => $nonce, 'data' => [] ],
                ],
            ],
            'data'    => [
                [
                    'type'        => 'data-table',
                    'id'          => 'fc-dirs-table',
                    'columns'     => [
                        'label'   => [ 'title' => __( 'Directory', 'ultraguard-security-suite' ) ],
                        'path'    => [ 'title' => __( 'Path',      'ultraguard-security-suite' ) ],
                        'status'  => [ 'title' => __( 'Status',    'ultraguard-security-suite' ) ],
                        'type'    => [ 'title' => __( 'Type',      'ultraguard-security-suite' ) ],
                        'actions' => [ 'title' => __( 'Actions',   'ultraguard-security-suite' ) ],
                    ],
                    'data'        => $rows,
                    'empty_state' => [ 'title' => __( 'No directories configured.', 'ultraguard-security-suite' ) ],
                ],
            ],
        ];
    }

    /**
     * 7-day scan activity bar chart.
     */
    private function activity_chart( array $chart ): array {
        return [
            'type'  => 'card',
            'id'    => 'fc-activity-chart-card',
            'title' => __( 'Scan Activity — Last 7 Days', 'ultraguard-security-suite' ),
            'icon'  => 'dashicons-chart-line',
            'data'  => [
                [
                    'type'       => 'chart',
                    'chart_type' => 'bar',
                    'height'     => '240px',
                    'labels'     => $chart['labels'],
                    'datasets'   => [
                        [
                            'label'           => __( 'Files Checked', 'ultraguard-security-suite' ),
                            'data'            => $chart['data'],
                            'backgroundColor' => 'rgba(59,130,246,0.6)',
                            'borderColor'     => '#3b82f6',
                            'borderWidth'     => 1,
                        ],
                    ],
                    'security_theme' => true,
                ],
            ],
        ];
    }

    /**
     * Monitoring scope settings card with inline save button.
     */
    private function scope_card(
        bool $enabled, bool $core, bool $plugins, bool $themes, bool $uploads,
        string $schedule, string $nonce
    ): array {
        return [
            'type'   => 'card',
            'id'     => 'fc-scope-settings-card',
            'title'  => __( 'Monitoring Scope', 'ultraguard-security-suite' ),
            'icon'   => 'dashicons-admin-settings',
            'data'   => [
                [ 'type' => 'toggle', 'name' => 'filechecker_enabled',      'label' => __( 'Enable File Monitoring', 'ultraguard-security-suite' ), 'description' => __( 'Activate file integrity monitoring.', 'ultraguard-security-suite' ),          'default' => $enabled  ],
                [ 'type' => 'toggle', 'name' => 'filechecker_scan_core',    'label' => __( 'Monitor WP Core',        'ultraguard-security-suite' ), 'description' => __( 'wp-includes and wp-admin directories.', 'ultraguard-security-suite' ),         'default' => $core     ],
                [ 'type' => 'toggle', 'name' => 'filechecker_scan_plugins', 'label' => __( 'Monitor Plugins',        'ultraguard-security-suite' ), 'description' => __( 'All files in wp-content/plugins.',             'ultraguard-security-suite' ),  'default' => $plugins  ],
                [ 'type' => 'toggle', 'name' => 'filechecker_scan_themes',  'label' => __( 'Monitor Themes',         'ultraguard-security-suite' ), 'description' => __( 'All files in wp-content/themes.',              'ultraguard-security-suite' ),  'default' => $themes   ],
                [ 'type' => 'toggle', 'name' => 'filechecker_scan_uploads', 'label' => __( 'Monitor Uploads',        'ultraguard-security-suite' ), 'description' => __( 'Check uploads for unexpected PHP executables.', 'ultraguard-security-suite' ), 'default' => $uploads  ],
                [
                    'type'    => 'select',
                    'name'    => 'filechecker_schedule',
                    'label'   => __( 'Scan Schedule', 'ultraguard-security-suite' ),
                    'options' => [
                        'hourly'     => __( 'Hourly',     'ultraguard-security-suite' ),
                        'twicedaily' => __( 'Twice Daily','ultraguard-security-suite' ),
                        'daily'      => __( 'Daily',      'ultraguard-security-suite' ),
                        'weekly'     => __( 'Weekly',     'ultraguard-security-suite' ),
                    ],
                    'default' => $schedule,
                ],
            ],
            'footer' => [
                'type'      => 'button-group',
                'alignment' => 'right',
                'buttons'   => [
                    $this->create_ajax_button(
                        __( 'Save Monitoring Settings', 'ultraguard-security-suite' ),
                        'ultraguard_fc_save_monitoring_settings',
                        [],
                        'primary',
                        'dashicons-saved'
                    ),
                ],
            ],
        ];
    }
}
