<?php
/**
 * DeactivationAjax - AJAX handlers for the deactivation questionnaire.
 *
 * Registered wp_ajax_ actions:
 *   ultraguard_deactivation_submit   - save questionnaire response + optional data wipe
 *   ultraguard_deactivation_skip     - skip questionnaire, just deactivate
 *
 * Data removal levels (passed as remove_data param):
 *   none    - deactivate only, keep all data
 *   soft    - remove settings + transients, keep DB tables
 *   full    - remove everything (settings, tables, uploads, options)
 *
 * @package UltraguardPro\modules\onboarding\ajax
 */

namespace UltraguardPro\modules\onboarding\ajax;

use UltraguardPro\Plugin;
use UltraguardPro\modules\onboarding\OnboardingModule;
use UltraguardPro\support\AjaxResponseBuilder;

if ( ! defined( 'ABSPATH' ) ) { exit; }
// phpcs:disable WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended -- AJAX handlers verify permissions and nonce inside their submit/skip flows.

class DeactivationAjax {

    private Plugin $plugin;

    public function __construct( Plugin $plugin ) {
        $this->plugin = $plugin;
    }

    public function register(): void {
        add_action( 'wp_ajax_ultraguard_deactivation_submit', [ $this, 'handle_submit' ] );
        add_action( 'wp_ajax_ultraguard_deactivation_skip',   [ $this, 'handle_skip'   ] );
    }

    // -------------------------------------------------------------------------

    /**
     * Save the questionnaire and optionally wipe data before deactivating.
     */
    public function handle_submit(): void {
        $this->verify();

        $reason      = sanitize_text_field( wp_unslash( $_POST['reason']      ?? 'no_reason' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by $this->verify() above.
        $details     = sanitize_textarea_field( wp_unslash( $_POST['details'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by $this->verify() above.
        $remove_data = sanitize_key( wp_unslash( $_POST['remove_data']        ?? 'none' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by $this->verify() above.

        // Persist the reason for product analytics.
        update_option( 'ultraguard_deactivation_reason', [
            'reason'     => $reason,
            'details'    => $details,
            'removed'    => $remove_data,
            'deactivated_at' => current_time( 'mysql', true ),
            'wp_version' => get_bloginfo( 'version' ),
            'site_url'   => get_site_url(),
        ] );

        do_action( 'ultraguard_pro/deactivation/questionnaire_submitted', $reason, $details );

        $cleanup_summary = \UltraguardPro\ultraguard_pro_cleanup_data( $remove_data );
        \UltraguardPro\ultraguard_pro_set_cleanup_mode( $remove_data );
        $removed_summary = $this->flatten_cleanup_summary( $cleanup_summary );

        AjaxResponseBuilder::make()
            ->success( __( 'Thank you for your feedback. Deactivating now...', 'ultraguard-security-suite' ) )
            ->addData( 'removed', $removed_summary )
            ->addData( 'redirect', $this->deactivation_url() )
            ->addNotification( __( 'Thank you for your feedback. Deactivating now...', 'ultraguard-security-suite' ), 'success' )
            ->addRedirect( $this->deactivation_url(), 400 )
            ->send();
    }

    /**
     * Skip questionnaire - just return the deactivation URL.
     */
    public function handle_skip(): void {
        $this->verify();

        \UltraguardPro\ultraguard_pro_set_cleanup_mode( 'none' );
        \UltraguardPro\ultraguard_pro_cleanup_runtime();

        AjaxResponseBuilder::make()
            ->success( __( 'Deactivating...', 'ultraguard-security-suite' ) )
            ->addData( 'redirect', $this->deactivation_url() )
            ->addNotification( __( 'Deactivating...', 'ultraguard-security-suite' ), 'info' )
            ->addRedirect( $this->deactivation_url(), 250 )
            ->send();
    }

    private function flatten_cleanup_summary( array $summary ): array {
        $flattened = [];

        foreach ( $summary as $items ) {
            if ( ! is_array( $items ) ) {
                continue;
            }

            foreach ( $items as $item ) {
                if ( is_string( $item ) && '' !== $item ) {
                    $flattened[] = $item;
                }
            }
        }

        return array_values( array_unique( $flattened ) );
    }

    // -------------------------------------------------------------------------

    private function deactivation_url(): string {
        $basename = defined( 'ULTRAGUARD_PRO_BASENAME' ) ? ULTRAGUARD_PRO_BASENAME : 'ultraguard-security-suite/ultraguard-security-suite.php';

        return add_query_arg(
            [
                'action'   => 'deactivate',
                'plugin'   => $basename,
                '_wpnonce' => wp_create_nonce( 'deactivate-plugin_' . $basename ),
            ],
            admin_url( 'plugins.php' )
        );
    }

    private function verify(): void {
        if ( ! check_ajax_referer( OnboardingModule::NONCE_ACTION, 'nonce', false ) ) {
            AjaxResponseBuilder::make()
                ->nonceError( __( 'Security check failed.', 'ultraguard-security-suite' ) )
                ->send( 403 );
        }
        if ( ! current_user_can( 'activate_plugins' ) ) {
            AjaxResponseBuilder::make()
                ->permissionError( __( 'Permission denied.', 'ultraguard-security-suite' ) )
                ->send( 403 );
        }
    }
}
