<?php

namespace UltraguardPro\modules\traffic_monitor\ajax;

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

use UltraguardPro\modules\core\AbstractAjaxHandler;
use UltraguardPro\modules\traffic_monitor\TrafficCaptureEngine;
use UltraguardPro\core\DatabaseCrud;

class TrafficMonitorAjax extends AbstractAjaxHandler {

    protected const NONCE = 'ultraguard_admin_nonce';

    private ?TrafficCaptureEngine $engine = null;

    public function register(): void {
        $this->register_actions( [
            'ultraguard_traffic_get_logs'                  => [ $this, 'handle_get_logs' ],
            'ultraguard_traffic_block_ip'                  => [ $this, 'handle_block_ip' ],
            'ultraguard_traffic_whitelist_ip'              => [ $this, 'handle_whitelist_ip' ],
            'ultraguard_traffic_get_stats'                 => [ $this, 'handle_get_stats' ],
            'ultraguard_traffic_clear_logs'                => [ $this, 'handle_clear_logs' ],
            'ultraguard_traffic_export'                    => [ $this, 'handle_export' ],
            'ultraguard_save_traffic_monitor_settings'     => [ $this, 'handle_save_settings' ],
        ] );
    }

    public function handle_get_logs(): void {
        $filters = [
            'page'         => absint( $_POST['page'] ?? 1 ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'ip'           => sanitize_text_field( wp_unslash( $_POST['ip'] ?? '' ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'threat'       => sanitize_key( wp_unslash( $_POST['threat'] ?? ''  ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'date_from'    => sanitize_text_field( wp_unslash( $_POST['date_from'] ?? '' ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'date_to'      => sanitize_text_field( wp_unslash( $_POST['date_to'] ?? '' ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'blocked_only' => ! empty( $_POST['blocked_only'] ), // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- nonce verified centrally; boolean presence check only.
            'orderby'      => sanitize_key( wp_unslash( $_POST['orderby'] ?? 'created_at'  ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'order'        => sanitize_key( wp_unslash( $_POST['order'] ?? 'DESC'  ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
        ];

        $this->send_success( $this->engine()->get_live_traffic( $filters, absint( $_POST['limit'] ?? 50 ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
    }

    public function handle_block_ip(): void {
        $ip = sanitize_text_field( wp_unslash( $_POST['ip'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
        do_action( 'ultraguard_pro/traffic_monitor/block_ip', $ip, 'Blocked from traffic monitor', 'high' );
        $this->send_success( [ 'message' => __( 'IP blocked.', 'ultraguard-security-suite' ) ] );
    }

    public function handle_whitelist_ip(): void {
        $ip = sanitize_text_field( wp_unslash( $_POST['ip'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
        do_action( 'ultraguard_pro/traffic_monitor/whitelist_ip', $ip, 'Whitelisted from traffic monitor' );
        $this->send_success( [ 'message' => __( 'IP whitelisted.', 'ultraguard-security-suite' ) ] );
    }

    public function handle_get_stats(): void {
        $this->send_success( $this->engine()->get_traffic_stats( absint( $_POST['hours'] ?? 24 ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
    }

    public function handle_clear_logs(): void {
        DatabaseCrud::delete_all( 'ultraguard_traffic_logs' );
        $this->send_success( [ 'message' => __( 'Traffic logs cleared.', 'ultraguard-security-suite' ) ] );
    }

    public function handle_export(): void {
        // Export is a Pro-only feature
        if ( ! \UltraguardPro\support\LicenseInfo::instance()->isPro() ) {
            $this->require_pro_feature( 'traffic_history', __( 'export traffic logs', 'ultraguard-security-suite' ) );
            return;
        }

        $data = $this->engine()->get_live_traffic( [
            'page'         => 1,
            'ip'           => sanitize_text_field( wp_unslash( $_POST['ip'] ?? '' ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'threat'       => sanitize_key( wp_unslash( $_POST['threat'] ?? ''  ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'date_from'    => sanitize_text_field( wp_unslash( $_POST['date_from'] ?? '' ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'date_to'      => sanitize_text_field( wp_unslash( $_POST['date_to'] ?? '' ) ), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'blocked_only' => ! empty( $_POST['blocked_only'] ), // phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- nonce verified centrally; boolean presence check only.
        ], 5000 );

        $csv = "time,ip,country,method,uri,threat,response_code,blocked\n";
        foreach ( $data['rows'] as $row ) {
            $csv .= '"' . implode( '","', array_map( 'str_replace', array_fill( 0, 8, '"'), array_fill( 0, 8, '""' ), [
                $row['created_at'] ?? '',
                $row['ip_address'] ?? '',
                trim( ( $row['ip_country'] ?? '' ) . ' ' . ( $row['ip_country_name'] ?? '' ) ),
                $row['request_method'] ?? '',
                $row['request_uri'] ?? '',
                $row['threat_type'] ?? '',
                $row['response_code'] ?? '',
                $row['was_blocked'] ?? 0,
            ] ) ) . "\"\n";
        }

        $data_url = 'data:text/csv;charset=utf-8,' . rawurlencode( $csv );
        $this->send_success( [
            'message'  => __( 'Traffic export ready.', 'ultraguard-security-suite' ),
            'download' => [
                'url'      => $data_url,
                'filename' => 'traffic-monitor-export-' . gmdate( 'Y-m-d-His' ) . '.csv',
            ],
        ] );
    }

    public function handle_save_settings(): void {
        $data = $this->sanitize_fields( (array) wp_unslash( $_POST ), [ // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by AbstractAjaxHandler/AjaxManager registration pipeline.
            'traffic_monitor_enabled'              => [ 'type' => 'bool', 'default' => true ],
            'traffic_monitor_retention_days'       => [ 'type' => 'int', 'default' => 7, 'min' => 1, 'max' => 90 ],
            '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, 'min' => 1, 'max' => 100 ],
            'traffic_monitor_auto_block_types'     => [ 'type' => 'array', 'default' => [ 'sqli', 'xss', 'scanner', 'brute_force' ], 'options' => [ 'brute_force', 'sqli', 'xss', 'scanner', 'spam', 'clean' ] ],
            'traffic_monitor_ignore_user_agents'   => [ 'type' => 'textarea', 'default' => '' ],
            'traffic_monitor_ignore_uri_patterns'  => [ 'type' => 'textarea', 'default' => '' ],
        ] );

        $ok = $this->plugin->settings->save_module_settings( 'traffic_monitor', $data );
        if ( ! $ok ) {
            $this->send_error( __( 'Failed to save traffic monitor settings.', 'ultraguard-security-suite' ), 500, 'save_failed' );
        }

        $this->send_success( [ 'message' => __( 'Traffic monitor settings saved.', 'ultraguard-security-suite' ) ] );
    }

    private function engine(): TrafficCaptureEngine {
        if ( null === $this->engine ) {
            $this->engine = new TrafficCaptureEngine( $this->plugin );
        }

        return $this->engine;
    }
}
