<?php

namespace UltraguardPro\modules\woo_security\ajax;

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

use UltraguardPro\modules\core\AbstractAjaxHandler;
use UltraguardPro\modules\woo_security\SkimmerDetectionEngine;

class WooSecurityAjax extends AbstractAjaxHandler {

    protected const NONCE = 'ultraguard_admin_nonce';

    private ?SkimmerDetectionEngine $engine = null;

    public function register(): void {
        $this->register_actions( [
            'ultraguard_woo_run_skimmer_scan'      => [ $this, 'handle_run_skimmer_scan' ],
            'ultraguard_woo_get_scan_results'      => [ $this, 'handle_get_scan_results' ],
            'ultraguard_woo_get_checkout_csp'      => [ $this, 'handle_get_checkout_csp' ],
            'ultraguard_woo_get_stats'             => [ $this, 'handle_get_stats' ],
            'ultraguard_save_woo_security_settings'=> [ $this, 'handle_save_settings' ],
        ] );
    }

    public function handle_run_skimmer_scan(): void {
        $this->require_pro_feature( 'woo_security', __( 'run a WooCommerce skimmer scan', 'ultraguard-security-suite' ) );
        $results = $this->engine()->scan_for_skimmers();
        $results['message'] = __( 'WooCommerce skimmer scan complete.', 'ultraguard-security-suite' );
        $this->send_success( $results );
    }

    public function handle_get_scan_results(): void {
        $table   = $this->t( 'skimmer_scan_results' );
        $results = $table && method_exists( $table, 'get_recent' ) ? $table->get_recent( max( 1, min( 200, absint( $_POST['limit'] ?? 50 ) ) ) ) : []; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Ajax action registered through the shared protected handler stack.
        $this->send_success( [ 'results' => $results ] );
    }

    public function handle_get_checkout_csp(): void {
        $module = $this->plugin->modules->get( 'woo_security' );
        $csp    = $module && method_exists( $module, 'build_checkout_csp' ) ? $module->build_checkout_csp() : '';
        $this->send_success( [ 'csp' => $csp ] );
    }

    public function handle_get_stats(): void {
        $table    = $this->t( 'skimmer_scan_results' );
        $records  = $table && method_exists( $table, 'get_recent' ) ? $table->get_recent( 500 ) : [];
        $threats  = count( $records );
        $last     = ! empty( $records[0]['created_at'] ) ? $records[0]['created_at'] : '';
        $this->send_success( [
            'bot_orders_blocked' => \UltraguardPro\modules\woo_security\WooSecurityModule::get_bot_orders_blocked_count(),
            'scan_threats_found' => $threats,
            'last_scan_time'     => $last,
        ] );
    }

    public function handle_save_settings(): void {
        $this->require_pro_feature( 'woo_security', __( 'save WooCommerce Security settings', 'ultraguard-security-suite' ) );

        $data = $this->sanitize_fields( (array) wp_unslash( $_POST ), [ // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Ajax action registered through the shared protected handler stack.
            'woo_security_enabled'                 => [ 'type' => 'bool', 'default' => true ],
            'woo_security_skimmer_detection'       => [ 'type' => 'bool', 'default' => true ],
            'woo_security_strict_csp'              => [ 'type' => 'bool', 'default' => true ],
            'woo_security_allowed_script_domains'  => [ 'type' => 'textarea', 'default' => '' ],
            'woo_security_checkout_honeypot'       => [ 'type' => 'bool', 'default' => true ],
            'woo_security_block_honeypot_order'    => [ 'type' => 'bool', 'default' => true ],
            'woo_security_secure_headers'          => [ 'type' => 'bool', 'default' => true ],
            'woo_security_alert_on_skimmer'        => [ 'type' => 'bool', 'default' => true ],
            'woo_security_block_suspicious_orders' => [ 'type' => 'bool', 'default' => false ],
        ] );

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

        $module = $this->plugin->modules->get( 'woo_security' );
        if ( $module && method_exists( $module, 'maybe_setup_schedule' ) ) {
            $module->maybe_setup_schedule();
        }

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

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

        return $this->engine;
    }
}
