<?php
declare(strict_types=1);

/**
 * Deactivation Feedback Handler
 * Generates HMAC-signed payloads for secure submission to tribulant.com
 */

// Security: Define the shared secret for HMAC signatures
// IMPORTANT: This MUST match the $hmacSecret in tribulant.com/deactivation_feedback/index.php
// Generate a strong secret using: bin2hex(random_bytes(32))
if (!defined('NEWSLETTERS_DEACTIVATION_SECRET')) {
    define('NEWSLETTERS_DEACTIVATION_SECRET', '3fbcdc7e8a9b370d658d82e221aa4a10d2c31ba14d541464945179ec6370f816');
}

/**
 * AJAX handler to generate signed deactivation feedback payload
 * Called by JavaScript before submitting to external endpoint
 */
function newsletters_ajax_sign_deactivation() {
    // Verify nonce for security
    check_ajax_referer('newsletters_deactivation_nonce', 'nonce');
    
    // Get the feedback data from POST
    $plugin_slug = sanitize_text_field($_POST['plugin_slug'] ?? '');
    $plugin_name = sanitize_text_field($_POST['plugin_name'] ?? '');
    $site_url = sanitize_text_field($_POST['site_url'] ?? '');
    $reason = sanitize_text_field($_POST['reason'] ?? '');
    $details = sanitize_textarea_field($_POST['details'] ?? '');
    
    // Validate required fields
    if (empty($plugin_slug) || empty($plugin_name) || empty($site_url) || empty($reason)) {
        wp_send_json_error(['message' => 'Missing required fields'], 400);
        return;
    }
    
    // Generate timestamp
    $timestamp = (string)time();
    
    // Create canonical payload (must match endpoint's verification logic)
    $payload = [
        'plugin_slug' => $plugin_slug,
        'plugin_name' => $plugin_name,
        'site_url'    => $site_url,
        'reason'      => $reason,
        'details'     => $details,
        'ts'          => $timestamp,
    ];
    
    // Generate JSON (same flags as endpoint)
    $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    
    // Generate HMAC signature
    $signature = hash_hmac('sha256', $json, NEWSLETTERS_DEACTIVATION_SECRET);
    
    // Return signed payload
    wp_send_json_success([
        'payload' => array_merge($payload, ['sig' => $signature])
    ]);
}

/**
 * Register AJAX actions
 */
function newsletters_register_deactivation_ajax() {
    // Register for logged-in users (admin area)
    add_action('wp_ajax_newsletters_sign_deactivation', 'newsletters_ajax_sign_deactivation');
    
    // Also register for non-logged-in users (just in case)
    add_action('wp_ajax_nopriv_newsletters_sign_deactivation', 'newsletters_ajax_sign_deactivation');
}
add_action('init', 'newsletters_register_deactivation_ajax');

/**
 * Enqueue nonce for AJAX requests
 */
function newsletters_enqueue_deactivation_nonce() {
    // Only on plugins page
    $screen = get_current_screen();
    if ($screen && $screen->id === 'plugins') {
        wp_localize_script('jquery', 'newslettersDeactivation', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('newsletters_deactivation_nonce')
        ]);
    }
}
add_action('admin_enqueue_scripts', 'newsletters_enqueue_deactivation_nonce');
