<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function iafwzc_process_request_handler()
{
    // Verify nonce for security
    if (
        !isset($_POST['iafwzc_request_key_nonce']) ||
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['iafwzc_request_key_nonce'])),
            'iafwzc_request_key_action'
        )
    ) {
        set_transient('iafwzc_license_fail', "Session expired. Please refresh the page and try again.", 300);
        wp_safe_redirect(admin_url('admin.php?page=integrate-any-form-with-zoho-crm&tab=settings&menu=license'));
        exit;
    }

    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('Insufficient permissions.', 'integrate-any-form-with-zoho-crm'));
    }

    // Sanitize and retrieve the request key
    $request_key = isset($_POST['iafwzc_request_key'])
        ? sanitize_text_field(wp_unslash($_POST['iafwzc_request_key']))
        : '';
    if (empty($request_key)) {
        set_transient('iafwzc_license_fail', "Key not found. Please enter a valid key to proceed.", 300);
        wp_safe_redirect(admin_url('admin.php?page=integrate-any-form-with-zoho-crm&tab=settings&menu=license'));
        exit;
    }

    // Determine which button was clicked
    if (isset($_POST['iafwzc_process_request_key'])) {
        // Process Key Button clicked
        iafwzc_process_request_key($request_key);
    } elseif (isset($_POST['iafwzc_revoke_request_key'])) {
        // Deactivate Key Button clicked
        iafwzc_revoke_request_key($request_key);
    } else {
        set_transient('iafwzc_license_fail', "Invalid action. Please try again.", 300);
        wp_safe_redirect(admin_url('admin.php?page=integrate-any-form-with-zoho-crm&tab=settings&menu=license'));
        exit;
    }
}
add_action('admin_post_iafwzc_process_request', 'iafwzc_process_request_handler');
