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

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

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