<?php
/**
 * Deactivation Feedback Class
 *
 * @package CodeandcoreUserRegistrationCF7
 */

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

/**
 * Class CNC_CF7_Deactivation
 *
 * Handles deactivation feedback popup, scripts, and AJAX processing.
 */
class CNC_CF7_Deactivation
{
    /**
     * Initialize the deactivation hooks
     */
    public static function init()
    {
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_deactivation_scripts']);
        add_action('wp_ajax_cnc_cf7_submit_deactivation_reason', [__CLASS__, 'handle_deactivation_feedback_ajax']);
    }

    /**
     * Enqueue deactivation popup scripts only on plugins page
     */
    public static function enqueue_deactivation_scripts($hook)
    {
        if ($hook !== 'plugins.php') {
            return;
        }

        wp_enqueue_style(
            'cnc-cf7-deactivation-css',
            CNC_CF7_PLUGIN_URL . 'assets/css/deactivation.css',
            [],
            CNC_CF7_VERSION
        );

        wp_enqueue_script(
            'cnc-cf7-deactivation-js',
            CNC_CF7_PLUGIN_URL . 'assets/js/deactivation.js',
            ['jquery'],
            CNC_CF7_VERSION,
            true
        );

        $current_user = wp_get_current_user();
        wp_localize_script('cnc-cf7-deactivation-js', 'cnc_cf7_deactivation', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('cnc_cf7_deactivation_nonce'),
            'user_name' => $current_user->display_name,
            'user_email' => $current_user->user_email,
        ]);
    }

    /**
     * Handle AJAX request for deactivation feedback submission
     */
    public static function handle_deactivation_feedback_ajax()
    {
        if (!current_user_can('activate_plugins')) {
            wp_send_json_error(['message' => __('Permission denied', 'codeandcore-user-registration-cf7')], 403);
        }

        check_ajax_referer('cnc_cf7_deactivation_nonce', 'nonce');

        $reason = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : '';
        $details = isset($_POST['details']) ? sanitize_textarea_field(wp_unslash($_POST['details'])) : '';
        $agree_contact = isset($_POST['agree_contact']) ? sanitize_text_field(wp_unslash($_POST['agree_contact'])) : 'no';

        $current_user = wp_get_current_user();

        if (class_exists('CNC_CF7_Tracking')) {
            $plugin_data = CNC_CF7_Tracking::get_plugin_info();
        } else {
            $plugin_data = [];
        }

        $theme = wp_get_theme();

        $data = [
            'site_url' => home_url(),
            'deactivation_reason' => $reason,
            'reason_message' => $details,
            'admin_name' => ($agree_contact === 'yes') ? $current_user->display_name : '',
            'admin_email' => ($agree_contact === 'yes') ? $current_user->user_email : '',
            'plugin_name' => isset($plugin_data['Name']) ? $plugin_data['Name'] : 'Codeandcore User Registration for CF7',
            'plugin_version' => isset($plugin_data['Version']) ? $plugin_data['Version'] : CNC_CF7_VERSION,
            'event' => 'deactivation_feedback',
            'php_version' => phpversion(),
            'wp_version' => get_bloginfo('version'),
            'theme_name' => $theme->get('Name'),
            'theme_version' => $theme->get('Version'),
            'is_multisite' => is_multisite() ? 'yes' : 'no',
            'site_language' => get_locale(),
            'timestamp' => current_time('mysql'),
        ];

        $secret_key = "8jF29fLkmsP0V9as0DLkso2P9lKs29FjsP4k2F0lskM2k";

        // Fallback encryption if tracking class is missing
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted_data = openssl_encrypt(wp_json_encode($data), 'AES-256-CBC', $secret_key, 0, $iv);
        $encrypted = base64_encode($iv . $encrypted_data);

        $signature = hash_hmac('sha256', $encrypted, $secret_key);

        wp_remote_post('https://dashboard.wordpress-plugins.pro/deactive-receiver.php', [
            'body' => [
                'data' => $encrypted,
                'signature' => $signature,
            ],
            'timeout' => 15,
        ]);

        wp_send_json_success(['message' => __('Feedback submitted successfully', 'codeandcore-user-registration-cf7')]);
    }
}
