<?php

namespace UltraguardPro\modules\ip_intelligence\ajax;

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

// phpcs:disable WordPress.Security.NonceVerification.Missing -- IP Intelligence AJAX handlers are registered through the shared protected AJAX framework.

use UltraguardPro\modules\core\AbstractAjaxHandler;
use UltraguardPro\modules\ip_intelligence\FeedSyncEngine;

class IpIntelligenceAjax extends AbstractAjaxHandler {

    protected const NONCE = 'ultraguard_admin_nonce';

    private ?FeedSyncEngine $engine = null;

    public function register(): void {
        $this->register_actions( [
            'ultraguard_ip_intel_sync_now'             => [ $this, 'handle_sync_now' ],
            'ultraguard_ip_intel_lookup_ip'            => [ $this, 'handle_lookup_ip' ],
            'ultraguard_ip_intel_get_feed'             => [ $this, 'handle_get_feed' ],
            'ultraguard_ip_intel_remove_entry'         => [ $this, 'handle_remove_entry' ],
            'ultraguard_ip_intel_add_manual'           => [ $this, 'handle_add_manual' ],
            'ultraguard_ip_intel_get_stats'            => [ $this, 'handle_get_stats' ],
            'ultraguard_save_ip_intelligence_settings' => [ $this, 'handle_save_settings' ],
        ] );
    }

    public function handle_sync_now(): void {
        $this->require_pro_feature( 'ip_intelligence', __( 'sync the IP intelligence feed', 'ultraguard-security-suite' ) );
        $this->send_success( $this->engine()->sync_all_feeds() );
    }

    public function handle_lookup_ip(): void {
        $this->require_pro_feature( 'ip_intelligence', __( 'look up live IP reputation', 'ultraguard-security-suite' ) );
        $ip      = sanitize_text_field( wp_unslash( $_POST['ip'] ?? '' ) );
        $api_key = trim( (string) $this->plugin->settings->get_option( 'ip_intelligence_abuseipdb_api_key', '' ) );
        $data    = $api_key ? $this->engine()->lookup_ip_abuse_score( $ip, $api_key ) : $this->engine()->check_ip_reputation( $ip );
        $this->send_success( [ 'lookup' => $data ] );
    }

    public function handle_get_feed(): void {
        $page  = max( 1, absint( $_POST['page'] ?? 1 ) );
        $table = $this->t( 'threat_feed' );
        $rows  = $table ? $table->paginate( $page, 50, [], 'updated_at', 'DESC' ) : [ 'items' => [], 'total' => 0 ];
        $this->send_success( (array) $rows );
    }

    public function handle_remove_entry(): void {
        $this->require_pro_feature( 'ip_intelligence', __( 'remove threat feed entries', 'ultraguard-security-suite' ) );
        $id    = absint( $_POST['id'] ?? 0 );
        $table = $this->t( 'threat_feed' );
        if ( ! $table || ! $table->delete( $id ) ) {
            $this->send_error( __( 'Unable to remove threat feed entry.', 'ultraguard-security-suite' ), 400, 'remove_failed' );
        }
        $this->send_success( [ 'message' => __( 'Entry removed.', 'ultraguard-security-suite' ) ] );
    }

    public function handle_add_manual(): void {
        $this->require_pro_feature( 'ip_intelligence', __( 'add manual IP intelligence entries', 'ultraguard-security-suite' ) );
        $table = $this->t( 'threat_feed' );
        $ip    = sanitize_text_field( wp_unslash( $_POST['ip_address'] ?? '' ) );
        if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
            $this->send_error( __( 'Invalid IP address.', 'ultraguard-security-suite' ), 400, 'invalid_ip' );
        }

        $ok = $table && method_exists( $table, 'upsert_feed_entry' ) && $table->upsert_feed_entry( [
            'ip_address'      => $ip,
            'ip_type'         => filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ? 'ipv6' : 'ipv4',
            'threat_category' => sanitize_key( wp_unslash( $_POST['threat_category'] ?? 'manual'  ) ),
            'confidence'      => absint( $_POST['confidence'] ?? 80 ),
            'source'          => 'manual',
            'country_code'    => sanitize_text_field( wp_unslash( $_POST['country_code'] ?? '' ) ),
            'is_active'       => 1,
            'expires_at'      => null,
            'last_seen_at'    => current_time( 'mysql', true ),
            'reports_count'   => 1,
        ] );

        if ( ! $ok ) {
            $this->send_error( __( 'Unable to add manual entry.', 'ultraguard-security-suite' ), 400, 'manual_failed' );
        }

        $this->send_success( [ 'message' => __( 'Manual entry added.', 'ultraguard-security-suite' ) ] );
    }

    public function handle_get_stats(): void {
        $this->send_success( $this->engine()->get_stats() );
    }

    public function handle_save_settings(): void {
        $this->require_pro_feature( 'ip_intelligence', __( 'save IP Intelligence settings', 'ultraguard-security-suite' ) );

        $data = $this->sanitize_fields( (array) wp_unslash( $_POST ), [
            'ip_intelligence_enabled'                  => [ 'type' => 'bool', 'default' => true ],
            'ip_intelligence_abuseipdb_api_key'        => [ 'type' => 'text', 'default' => '' ],
            'ip_intelligence_enable_spamhaus'          => [ 'type' => 'bool', 'default' => true ],
            'ip_intelligence_enable_ultraguard_network'=> [ 'type' => 'bool', 'default' => true ],
            'ip_intelligence_abuse_score_threshold'    => [ 'type' => 'int', 'default' => 75, 'min' => 0, 'max' => 100 ],
            'ip_intelligence_auto_block_action'        => [ 'type' => 'select', 'default' => 'block_and_log', 'options' => [ 'block_silently', 'block_and_log', 'challenge_captcha' ] ],
            'ip_intelligence_sync_interval_hours'      => [ 'type' => 'select', 'default' => '6', 'options' => [ '1', '3', '6', '12', '24' ] ],
            'ip_intelligence_cache_lookups'            => [ 'type' => 'bool', 'default' => true ],
            'ip_intelligence_cache_duration_hours'     => [ 'type' => 'int', 'default' => 24, 'min' => 1, 'max' => 168 ],
            'ip_intelligence_alert_on_high_confidence' => [ 'type' => 'bool', 'default' => true ],
            'ip_intelligence_block_tor'                => [ 'type' => 'bool', 'default' => false ],
            'ip_intelligence_block_vpn'                => [ 'type' => 'bool', 'default' => false ],
        ] );

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

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

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

// phpcs:enable
