<?php

namespace UltraguardPro\modules\upgrade_manager\ajax;

if ( ! defined( 'ABSPATH' ) ) { exit; }
// phpcs:disable WordPress.Security.NonceVerification.Missing,WordPress.Security.NonceVerification.Recommended -- Requests are routed through the shared protected AJAX layer.

use UltraguardPro\modules\core\AbstractAjaxHandler;
use UltraguardPro\support\LicenseInfo;
use UltraguardPro\support\UpgradeManager;

class UpgradeManagerAjax extends AbstractAjaxHandler {

    protected const NONCE = 'ultraguard_admin_nonce';

    public function register(): void {
        $this->register_actions( [
            'ultraguard_upgrade_manager_activate_license' => [
                'handler' => [ $this, 'handle_activate_license' ],
                'cap'     => '',
            ],
            'ultraguard_upgrade_manager_refresh_status'   => [
                'handler' => [ $this, 'handle_refresh_status' ],
                'cap'     => '',
            ],
            'ultraguard_upgrade_manager_deactivate'       => [
                'handler' => [ $this, 'handle_deactivate_license' ],
                'cap'     => '',
            ],
            'ultraguard_save_upgrade_manager_settings'    => [
                'handler' => [ $this, 'handle_save_settings' ],
                'cap'     => '',
            ],
        ] );
    }

    private function verify_upgrade_permissions(): void {
        $this->verify_nonce_only();

        if ( \UltraguardPro\ultraguard_current_user_can_manage() ) {
            return;
        }

        $this->send_error( __( 'Insufficient permissions.', 'ultraguard-security-suite' ), 403, 'permission_denied' );
    }

    public function handle_activate_license(): void {
        $this->verify_upgrade_permissions();

        $license_key = sanitize_text_field( wp_unslash( $_POST['license_key'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Permission helper validates nonce/capability before reading request data.
        $email       = sanitize_email( wp_unslash( $_POST['license_email'] ?? '' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Permission helper validates nonce/capability before reading request data.

        if ( '' === $license_key ) {
            $this->send_error( __( 'Enter your license key to activate Pro.', 'ultraguard-security-suite' ), 400, 'missing_license_key' );
        }

        $license = LicenseInfo::make()
            ->withKey( $license_key )
            ->withEmail( $email )
            ->activate();

        if ( $license->failed() ) {
            $error = $license->getError();
            $this->send_error(
                $error ? $error->get_error_message() : __( 'License activation failed.', 'ultraguard-security-suite' ),
                400,
                $error ? (string) $error->get_error_code() : 'activation_failed'
            );
        }

        $status = LicenseInfo::make()->force( true )->getStatus();

        $this->send_success( [
            'message'  => __( 'License activated successfully. Paid features are now available.', 'ultraguard-security-suite' ),
            'status'   => $status,
            'redirect' => self_admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=upgrade-manager-paid' ),
        ] );
    }

    public function handle_refresh_status(): void {
        $this->verify_upgrade_permissions();

        $stored_key   = (string) get_option( LicenseInfo::OPTION_KEY, '' );
        $stored_email = (string) get_option( LicenseInfo::OPTION_EMAIL, '' );
        $license      = LicenseInfo::make()
            ->withKey( $stored_key )
            ->withEmail( $stored_email )
            ->force( true )
            ->heartbeat();

        if ( $license->failed() ) {
            $error = $license->getError();
            $this->send_error(
                $error ? $error->get_error_message() : __( 'Unable to sync this site with the license server.', 'ultraguard-security-suite' ),
                400,
                $error ? (string) $error->get_error_code() : 'sync_failed'
            );
        }

        if ( '' !== $stored_key ) {
            $license->validate();

            if ( $license->failed() ) {
                $error = $license->getError();
                $this->send_error(
                    $error ? $error->get_error_message() : __( 'Unable to refresh license status.', 'ultraguard-security-suite' ),
                    400,
                    $error ? (string) $error->get_error_code() : 'refresh_failed'
                );
            }
        }

        $status = LicenseInfo::make()->force( true )->getStatus();

        $this->send_success( [
            'message' => __( 'License status refreshed and server registration synced.', 'ultraguard-security-suite' ),
            'status'  => $status,
        ] );
    }

    public function handle_deactivate_license(): void {
        $this->verify_upgrade_permissions();

        $stored_key = (string) get_option( LicenseInfo::OPTION_KEY, '' );
        if ( '' === $stored_key ) {
            $this->send_error( __( 'No active license was found to deactivate.', 'ultraguard-security-suite' ), 400, 'missing_license' );
        }

        $license = LicenseInfo::make()
            ->withKey( $stored_key )
            ->withEmail( (string) get_option( LicenseInfo::OPTION_EMAIL, '' ) )
            ->deactivate();

        if ( $license->failed() ) {
            $error = $license->getError();
            $this->send_error(
                $error ? $error->get_error_message() : __( 'Unable to deactivate the license.', 'ultraguard-security-suite' ),
                400,
                $error ? (string) $error->get_error_code() : 'deactivate_failed'
            );
        }

        $this->send_success( [
            'message'  => __( 'License deactivated. UltraGuard is now on the Free plan.', 'ultraguard-security-suite' ),
            'redirect' => self_admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=upgrade-manager-free' ),
        ] );
    }

    public function handle_save_settings(): void {
        $this->verify_upgrade_permissions();

        $data = $this->sanitize_fields( (array) wp_unslash( $_POST ), [ // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Permission helper validates nonce/capability before reading request data.
            'upgrade_manager_show_inline_nudges'   => [ 'type' => 'bool', 'default' => true ],
            'upgrade_manager_external_upgrade_url' => [ 'type' => 'url', 'default' => UpgradeManager::EXTERNAL_UPGRADE_URL ],
            'upgrade_manager_billing_portal_url'   => [ 'type' => 'url', 'default' => '' ],
            'upgrade_manager_support_url'          => [ 'type' => 'url', 'default' => 'https://ultraguard.net/contact' ],
        ] );

        if ( ! $this->plugin->settings->save_module_settings( 'upgrade_manager', $data ) ) {
            $this->send_error( __( 'Failed to save license manager settings.', 'ultraguard-security-suite' ), 500, 'save_failed' );
        }

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