<?php

namespace UltraguardPro\modules\traffic_monitor;

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

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\AbstractModule;

class TrafficMonitorModule extends AbstractModule {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->plugin->settings->register_module_prefix( 'traffic_monitor_', 'traffic_monitor' );
    }

    public function get_id(): string {
        return 'traffic_monitor';
    }

    protected function requires_pro(): bool {
        return false;
    }

    public function boot(): void {
        $_db_tables = $this->plugin->modules->get_db_tables();
        if ( $_db_tables ) {
            $_db_tables->register_schema( new schema\TrafficMonitorSchema() );
        }

        if ( method_exists( $this->plugin->settings, 'register_settings_schema' ) ) {
            $this->plugin->settings->register_settings_schema( 'traffic_monitor', 'traffic_monitor_', [
                'traffic_monitor_enabled'              => [ 'type' => 'bool', 'default' => true ],
                'traffic_monitor_retention_days'       => [ 'type' => 'int', 'default' => 7 ],
                'traffic_monitor_ignore_logged_in'     => [ 'type' => 'bool', 'default' => true ],
                'traffic_monitor_skip_localhost'       => [ 'type' => 'bool', 'default' => true ],
                'traffic_monitor_auto_block_enabled'   => [ 'type' => 'bool', 'default' => false ],
                'traffic_monitor_auto_block_threshold' => [ 'type' => 'int', 'default' => 5 ],
                'traffic_monitor_auto_block_types'     => [ 'type' => 'array', 'default' => [ 'sqli', 'xss', 'scanner', 'brute_force' ] ],
                'traffic_monitor_ignore_user_agents'   => [ 'type' => 'textarea', 'default' => '' ],
                'traffic_monitor_ignore_uri_patterns'  => [ 'type' => 'textarea', 'default' => '' ],
            ] );
        }

        ( new ajax\TrafficMonitorAjax( $this->plugin ) )->register();

        add_action( 'init', [ $this, 'maybe_log_request' ], 1 );
        add_action( 'ultraguard_traffic_log_insert', [ $this, 'insert_traffic_log' ], 10, 1 );
        add_action( 'ultraguard_register_admin_pages', [ $this, 'register_pages' ], 65, 1 );
        ( new TrafficMonitorDashboardContributor( $this->plugin ) )->register();
        add_action( 'wp_loaded', [ $this, 'maybe_setup_schedule' ] );
        add_action( 'ultraguard_traffic_monitor_prune', [ $this, 'run_prune' ] );
        add_action( 'ultraguard_after_enqueue_assets', [ $this, 'enqueue_assets' ] );

        do_action( 'ultraguard_pro/traffic_monitor/booted', $this );
    }

    public function maybe_log_request(): void {
        ( new TrafficCaptureEngine( $this->plugin ) )->maybe_log_request();
    }

    public function insert_traffic_log( array $payload ): void {
        ( new TrafficCaptureEngine( $this->plugin ) )->insert_log( $payload );
    }

    public function register_pages( $admin ): void {
        $admin->register_page( [
            'id'              => 'traffic-monitor',
            'page_title'      => __( 'Live Traffic Monitor', 'ultraguard-security-suite' ),
            'menu_title'      => __( 'Traffic Monitor', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ new pages\TrafficMonitorDashboard( $this->plugin ), 'get_scheme' ],
            'parent_id'       => '',
            'priority'        => 65,
            'group'           => 'Monitoring',
            'icon'            => 'dashicons-chart-area',
        ] );

        $admin->register_page( [
            'id'              => 'traffic-monitor-settings',
            'page_title'      => __( 'Traffic Monitor Settings', 'ultraguard-security-suite' ),
            'menu_title'      => __( 'Settings', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ new pages\TrafficMonitorSettings( $this->plugin ), 'get_scheme' ],
            'parent_id'       => 'traffic-monitor',
            'priority'        => 66,
            'group'           => 'Monitoring',
            'icon'            => 'dashicons-admin-settings',
        ] );
    }

    public function maybe_setup_schedule(): void {
        if ( ! wp_next_scheduled( 'ultraguard_traffic_monitor_prune' ) ) {
            wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'ultraguard_traffic_monitor_prune' );
        }
    }

    public function run_prune(): void {
        ( new TrafficCaptureEngine( $this->plugin ) )->prune_old_logs();
    }

    public function enqueue_assets(): void {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin screen detection.
        $ug_page = sanitize_key( wp_unslash( $_GET['ug_page'] ?? ''  ) );
        if ( ! in_array( $ug_page, [ 'traffic-monitor', 'traffic-monitor-settings' ], true ) ) {
            return;
        }

        $module_url = plugin_dir_url( __FILE__ );
        $version    = defined( 'ULTRAGUARD_PRO_VERSION' ) ? ULTRAGUARD_PRO_VERSION : '1.0.0';

        wp_enqueue_style( 'ultraguard-traffic-monitor-page', $module_url . 'assets/css/traffic-monitor-page.css', [ 'admin-base', 'admin-components' ], $version );
        wp_enqueue_script( 'ultraguard-traffic-monitor-page', $module_url . 'assets/js/traffic-monitor-page.js', [ 'jquery', 'ultraguard-core', 'ultraguard-managers' ], $version, true );

        wp_localize_script( 'ultraguard-traffic-monitor-page', 'ultraguardTrafficMonitor', [
            'nonce'         => wp_create_nonce( 'ultraguard_admin_nonce' ),
            'ajaxUrl'       => self_admin_url( 'admin-ajax.php' ),
            'refreshEvery'  => 10000,
            'i18n'          => [
                'blocked'     => __( 'IP blocked.', 'ultraguard-security-suite' ),
                'whitelisted' => __( 'IP whitelisted.', 'ultraguard-security-suite' ),
            ],
        ] );
    }

}
