<?php

declare(strict_types=1);

namespace WPUltimateSecurity\UltimateSecurity\Modules\Maintenance;

use WP_REST_Response;
use WPUltimateSecurity\UltimateSecurity\Modules\Base\AbstractModule;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\StringHelper;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\CryptoHelper;

class DeactivationUrl extends AbstractModule
{
    public const MODULE_ID = 'maintenance.deactivation_url';

    protected const VERSION = '2.0.0';

    /**
     * Get unique module identifier.
     */
    public static function getId(): string
    {
        return self::MODULE_ID;
    }

    /**
     * Get human-readable module name.
     */
    public static function getName(): string
    {
        return __('Deactivation URL', 'ultimate-security');
    }

    /**
     * Get module domain.
     */
    public static function getDomain(): string
    {
        return 'maintenance';
    }

    /**
     * Boot the module after registration.
     */
    public static function boot(): void
    {
        add_action('rest_api_init', [self::class, 'regsiter_routes']);
        // Deactivation handler (works for both logged in and logged out users)
        add_action('admin_post_ultimate_security_deactivate', [self::class, 'ultimate_security_handle_plugin_deactivation']);
        add_action('admin_post_nopriv_ultimate_security_deactivate', [self::class, 'ultimate_security_handle_plugin_deactivation']);
    }

    public static function regsiter_routes()
    {
        // register_rest_route('ultimate-security/v1', '/disable-ultimate-security-setup', [
        //     'methods' => 'POST',
        //     'callback' => function () {
        //         update_option('ultimate_security_setup', true);
        //         return new WP_REST_Response(['message' => 'Setup disabled successfully'], 200);
        //     },
        // ]);

        // Register GET endpoint to check popup status
        register_rest_route('ultimate-security/v1', '/disable-ultimate-security-popup', [
            'methods' => 'GET',
            'callback' => [self::class, 'get_ultimate_security_popup_status'],
            'permission_callback' => function () {
                return current_user_can('manage_options');
            },
        ]);

        // Register POST endpoint to dismiss popup
        register_rest_route('ultimate-security/v1', '/disable-ultimate-security-popup', [
            'methods' => 'POST',
            'callback' => [self::class, 'dismiss_ultimate_security_popup'],
            'permission_callback' => function () {
                return current_user_can('manage_options');
            },
        ]);

        // Register POST endpoint to regenerate deactivation URL
        register_rest_route('ultimate-security/v1', '/regenerate-deactivation-url', [
            'methods' => 'POST',
            'callback' => [self::class, 'regenerate_deactivation_url'],
            'permission_callback' => function () {
                return current_user_can('manage_options');
            },
        ]);
    }
    // GET method - only check the status, don't update
    public static function get_ultimate_security_popup_status()
    {
        $ultimate_security_disable_popup_showed = get_option('ultimate_security_disable_popup_showed', 0);
        // Return 1 if already shown (don't show popup), 0 if not shown (show popup)
        return new WP_REST_Response($ultimate_security_disable_popup_showed ? 1 : 0, 200);
    }

    // POST method - dismiss the popup when Finish is clicked
    public static function dismiss_ultimate_security_popup($request)
    {
        $dismissed = $request->get_param('dismissed');

        if ($dismissed) {
            update_option('ultimate_security_disable_popup_showed', 1);
            return new WP_REST_Response(['success' => true, 'message' => 'Popup dismissed'], 200);
        }

        return new WP_REST_Response(['success' => false, 'message' => 'Invalid request'], 400);
    }

    /**
     * Regenerate deactivation URL with new secret key
     */
    public static function regenerate_deactivation_url()
    {
        $new_key = StringHelper::random(20);
        $encrypted_key = CryptoHelper::encrypt($new_key);
        if ($encrypted_key) {
            update_option('ultimate_security_plugin_deactivation_secret_key', $encrypted_key);
        } else {
            update_option('ultimate_security_plugin_deactivation_secret_key', $new_key);
        }

$new_url = add_query_arg(
                [
                    'action' => 'ultimate_security_deactivate',
                    'secret_key' => $new_key,
                ],
                site_url('wp-admin/admin-post.php')
            );

        return new WP_REST_Response([
            'success' => true,
            'url' => $new_url,
        ], 200);
    }

    /**
     * Handle deactivation request
     */
    public static function ultimate_security_handle_plugin_deactivation()
    {

        $stored_secret_key = get_option('ultimate_security_plugin_deactivation_secret_key');
        $decrypted_key = CryptoHelper::decrypt($stored_secret_key);
        if ($decrypted_key) {
            $stored_secret_key = $decrypted_key;
        }

        if (!$stored_secret_key || !isset($_GET['secret_key']) || $_GET['secret_key'] !== $stored_secret_key) {
            wp_die('Invalid Request.', 'Unauthorized', ['response' => 403]);
        }

        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $plugins_deactivated = [];

        // Deactivate Pro first
        $pro_plugin = 'ultimate-security-pro/ultimate-security-pro.php';
        if (is_plugin_active($pro_plugin)) {
            deactivate_plugins($pro_plugin);
            $plugins_deactivated[] = 'Ultimate Security Pro';
        }

        // Then Free
        $free_plugin = 'ultimate-security/ultimate-security.php';
        if (is_plugin_active($free_plugin)) {
            deactivate_plugins($free_plugin);
            $plugins_deactivated[] = 'Ultimate Security';
        }

        if (!empty($plugins_deactivated)) {
            wp_die(
                esc_html(
                    'The following plugin(s) have been deactivated successfully: '
                    . implode(', ', array_map('esc_html', $plugins_deactivated))
                ),
                esc_html__('Plugin Deactivated', 'ultimate-security'),
                ['response' => 200]
            );

        } else {
            wp_die(
                esc_html('Neither Ultimate Security nor Ultimate Security Pro is active.')
            );
        }
    }
}
