<?php

function iafwzcai_process_request_handler()
{
    // Verify nonce for security
    if (
        !isset($_POST['iafwzcai_request_key_nonce']) ||
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['iafwzcai_request_key_nonce'])),
            'iafwzcai_request_key_action'
        )
    ) {
        set_transient('iafwzcai_license_fail', "Session expired. Please refresh the page and try again.", 300);
        wp_safe_redirect(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=settings&menu=license'));
        exit;
    }
    // Sanitize and retrieve the request key
    $request_key = isset($_POST['iafwzcai_request_key'])
        ? sanitize_text_field(wp_unslash($_POST['iafwzcai_request_key']))
        : '';
    if (empty($request_key)) {
        set_transient('iafwzcai_license_fail', "Key not found. Please enter a valid key to proceed.", 300);
        wp_safe_redirect(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=settings&menu=license'));
        exit;
    }

    // Determine which button was clicked
    if (isset($_POST['iafwzcai_process_request_key'])) {
        // Process Key Button clicked
        iafwzcai_process_request_key($request_key);
    } elseif (isset($_POST['iafwzcai_revoke_request_key'])) {
        // Deactivate Key Button clicked
        iafwzcai_revoke_request_key($request_key);
    } else {
        set_transient('iafwzcai_license_fail', "Invalid action. Please try again.", 300);
        wp_safe_redirect(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=settings&menu=license'));
        exit;
    }
}
add_action('admin_post_iafwzcai_process_request', 'iafwzcai_process_request_handler');
