<?php
/**
 * Deactivation Feedback Handler
 *
 * Handles the deactivation feedback popup functionality including
 * script enqueuing and AJAX request processing.
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/* ---------------------------------------------------------
   ENQUEUE DEACTIVATION SCRIPTS
----------------------------------------------------------- */

/**
 * Enqueue deactivation popup scripts only on plugins page
 *
 * @param string $hook Current admin page hook.
 * @return void
 */
function admilogu_enqueue_deactivation_scripts($hook)
{
    // Only load on plugins.php page
    if ($hook !== 'plugins.php') {
        return;
    }

    // Enqueue Google Fonts (Poppins)
    wp_enqueue_style(
        'admilogu-poppins-font',
        'https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap',
        [],
        '1.0'
    );

    // Enqueue CSS
    wp_enqueue_style(
        'admilogu-deactivation-css',
        admilogu_URL . 'assets/css/admilogu_deactivation.css',
        ['admilogu-poppins-font'],
        '1.0'
    );

    // Enqueue JavaScript
    wp_enqueue_script(
        'admilogu-deactivation-js',
        admilogu_URL . 'assets/js/admilogu_deactivation.js',
        ['jquery'],
        '1.0',
        true
    );

    // Localize script with AJAX data
    $current_user = wp_get_current_user();
    wp_localize_script('admilogu-deactivation-js', 'admilogu_deactivation', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('admilogu_deactivation_nonce'),
        'user_name' => $current_user->display_name,
        'user_email' => $current_user->user_email,
        'plugin_slug' => 'admin-login-guard-branding'
    ]);
}
add_action('admin_enqueue_scripts', 'admilogu_enqueue_deactivation_scripts');


/* ---------------------------------------------------------
   AJAX HANDLER FOR DEACTIVATION FEEDBACK
----------------------------------------------------------- */

/**
 * Handle AJAX request for deactivation feedback submission
 *
 * @return void Sends JSON response and exits
 */
function admilogu_submit_deactivation_reason()
{
    // Check user permissions
    if (!current_user_can('activate_plugins')) {
        wp_send_json_error(['message' => __('Permission denied', 'admin-login-guard-branding')], 403);
    }

    // Verify nonce for security
    check_ajax_referer('admilogu_deactivation_nonce', 'nonce');

    // Sanitize and collect data from frontend
    // phpcs:ignore WordPress.Security.NonceVerification.Missing
    $reason = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Missing
    $details = isset($_POST['details']) ? sanitize_textarea_field(wp_unslash($_POST['details'])) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Missing
    $agree_contact = isset($_POST['agree_contact']) ? sanitize_text_field(wp_unslash($_POST['agree_contact'])) : 'no';

    // Get current user
    $current_user = wp_get_current_user();

    // Get plugin info
    if (!function_exists('get_plugin_data')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }
    $plugin_data = get_plugin_data(admilogu_PATH . 'admin-login-guard-branding.php');

    // Get theme data
    $theme = wp_get_theme();

    // Prepare comprehensive data array
    $data = [
        'site_url' => get_site_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' => $plugin_data['Name'],
        'plugin_version' => $plugin_data['Version'],
        'event' => 'deactivation',
        '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 for encryption (matching telemetry)
    $secret_key = "8jF29fLkmsP0V9as0DLkso2P9lKs29FjsP4k2F0lskM2k";

    // Encrypt payload and create signature (using functions from admilogu_telemetry.php)
    if (function_exists('admilogu_encrypt_payload')) {
        $encrypted = admilogu_encrypt_payload($data, $secret_key);
        $signature = hash_hmac('sha256', $encrypted, $secret_key);

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

    // Send success response regardless of remote endpoint response
    wp_send_json_success(['message' => __('Feedback submitted successfully', 'admin-login-guard-branding')]);
}
add_action('wp_ajax_admilogu_submit_deactivation_reason', 'admilogu_submit_deactivation_reason');
