<?php

namespace UltraguardPro\modules\ip_intelligence;

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

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

class IpIntelligenceModule extends AbstractModule {

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

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

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

    protected function allow_preview_mode(): bool {
        return true;
    }

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

        if ( method_exists( $this->plugin->settings, 'register_settings_schema' ) ) {
            $this->plugin->settings->register_settings_schema( 'ip_intelligence', 'ip_intelligence_', [
                '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 ],
                '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 ],
                '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 ],
            ] );
        }

        ( new ajax\IpIntelligenceAjax( $this->plugin ) )->register();
        add_action( 'ultraguard_register_admin_pages', [ $this, 'register_pages' ], 12, 1 );
        ( new IpIntelligenceDashboardContributor( $this->plugin ) )->register();
        add_action( 'ultraguard_after_enqueue_assets', [ $this, 'enqueue_assets' ] );

        if ( ! $this->is_preview_mode() ) {
            add_action( 'init', [ $this, 'maybe_check_request_ip' ], 2 );
            add_action( 'ultraguard_ip_intel_sync_feed', [ $this, 'sync_feed' ] );
            add_action( 'ultraguard_ip_intel_refresh_ip', [ $this, 'refresh_ip_lookup' ], 10, 1 );
            add_action( 'wp_loaded', [ $this, 'maybe_setup_schedule' ] );
            add_action( 'ultraguard_pro/firewall/ip_blocked', [ $this, 'learn_from_block' ], 10, 3 );
            ( new IpIntelligenceNotifications( $this->plugin ) )->register();
        }

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

    public function maybe_check_request_ip(): void {
        if ( ! $this->option( 'ip_intelligence_enabled', true ) ) { return; }
        ( new FeedSyncEngine( $this->plugin ) )->maybe_check_request_ip();
    }

    public function register_pages( $admin ): void {
        $admin->register_page( [
            'id'              => 'ip-intelligence',
            'page_title'      => __( 'IP Intelligence', 'ultraguard-security-suite' ),
            'menu_title'      => __( 'IP Intelligence', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ new pages\IpIntelligenceDashboard( $this->plugin ), 'get_scheme' ],
            'parent_id'       => '',
            'priority'        => 12,
            'group'           => 'Protection',
            'icon'            => 'dashicons-shield-alt',
        ] );

        $admin->register_page( [
            'id'              => 'ip-intelligence-settings',
            'page_title'      => __( 'IP Intelligence Settings', 'ultraguard-security-suite' ),
            'menu_title'      => __( 'Settings', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ new pages\IpIntelligenceSettings( $this->plugin ), 'get_scheme' ],
            'parent_id'       => 'ip-intelligence',
            'priority'        => 13,
            'group'           => 'Protection',
            'icon'            => 'dashicons-admin-settings',
        ] );
    }

    public function maybe_setup_schedule(): void {
        $hours = max( 1, (int) $this->option( 'ip_intelligence_sync_interval_hours', '6' ) );
        if ( ! wp_next_scheduled( 'ultraguard_ip_intel_sync_feed' ) ) {
            wp_schedule_event( time() + HOUR_IN_SECONDS, 'hourly', 'ultraguard_ip_intel_sync_feed' );
        }
        update_option( 'ip_intelligence_sync_interval_runtime', $hours, false );
    }

    public function sync_feed(): void {
        $runtime = max( 1, (int) get_option( 'ip_intelligence_sync_interval_runtime', 6 ) );
        $hour    = (int) gmdate( 'G' );
        if ( $runtime > 1 && ( $hour % $runtime ) !== 0 ) {
            return;
        }
        ( new FeedSyncEngine( $this->plugin ) )->sync_all_feeds();
        ( new FeedSyncEngine( $this->plugin ) )->prune_expired();
    }

    public function refresh_ip_lookup( string $ip ): void {
        if ( ! $this->option( 'ip_intelligence_enabled', true ) ) {
            return;
        }

        $ip = sanitize_text_field( $ip );
        if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
            return;
        }

        $api_key = trim( (string) $this->option( 'ip_intelligence_abuseipdb_api_key', '' ) );
        if ( '' === $api_key ) {
            return;
        }

        ( new FeedSyncEngine( $this->plugin ) )->lookup_ip_abuse_score( $ip, $api_key );
    }

    public function learn_from_block( string $ip, string $source = '', string $reason = '' ): void {
        if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
            return;
        }
        $table = $this->plugin->modules->get_db_tables()->get_table( 'threat_feed' );
        if ( $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' => 'manual',
                'confidence'      => 80,
                'source'          => 'manual',
                'country_code'    => '',
                'is_active'       => 1,
                'expires_at'      => null,
                'last_seen_at'    => current_time( 'mysql', true ),
                'reports_count'   => 1,
            ] );
        }
    }

    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, [ 'ip-intelligence', 'ip-intelligence-settings' ], true ) ) {
            return;
        }

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

        wp_enqueue_style( 'ultraguard-ip-intelligence-page', $module_url . 'assets/css/ip-intelligence-page.css', [ 'admin-base', 'admin-components' ], $version );
        wp_enqueue_script( 'ultraguard-ip-intelligence-page', $module_url . 'assets/js/ip-intelligence-page.js', [ 'jquery', 'ultraguard-core', 'ultraguard-managers' ], $version, true );
        wp_localize_script( 'ultraguard-ip-intelligence-page', 'ultraguardIpIntelligence', [
            'nonce'   => wp_create_nonce( 'ultraguard_admin_nonce' ),
            'ajaxUrl' => self_admin_url( 'admin-ajax.php' ),
        ] );
    }
}
