<?php

if ( !defined( 'ABSPATH' ) ) {
	exit();
}

// Check Wallet Field
// ======================================================

function cryptoniq_subscribe_wallet( $field, $value, $existing_value ) {
	$return = array();

	// Get license key from another Redux field
	$license_key = cryptoniq_get_option( 'license_key' );

	if ( empty( $license_key ) ) {
		$field['msg'] = 'No License Key';
		$return['error'] = $field;
		$return['value'] = $value; // Always include value
		return $return;
	}

	// Prepare API request
	$responseUrl = CRYPTONIQ_API_URL . 'subscriptions/add';
	$coin = strtoupper( str_replace( 'wallets_', '', $field['id'] ) );

	$body = array(
		'licenseKey' => $license_key,
		'coin'       => $coin,
		'address'    => $value
	);

	$response = wp_remote_post( $responseUrl, array(
		'headers' => array(
			'Content-Type' => 'application/json',
		),
		'body'    => json_encode( $body ),
		'timeout' => 20,
	) );

	// Handle network errors
	if ( is_wp_error( $response ) ) {
		$field['msg'] = 'Error. Please try again.';
		$return['error'] = $field;
		$return['value'] = $value;
		return $return;
	}

	$status_code = wp_remote_retrieve_response_code( $response );
	$body_raw    = wp_remote_retrieve_body( $response );
	$body        = json_decode( $body_raw, true );

	if ( $status_code >= 400 ) {
		$field['msg'] = ! empty( $body['error'] ) ? $body['error'] : 'Error. Please try again.';
		$return['error'] = $field;
		$return['value'] = $value;
		return $return;
	}

	$return['value'] = $value;
	$return['error'] = false; // Explicitly clear previous error

	return $return;
}



// Add License Validation Callback
// ======================================================

function cryptoniq_license_validate( $field, $value, $existing_value ) {
    $api_url = CRYPTONIQ_API_URL . 'license/check';
    $callback_url = site_url( '/wp-json/cryptoniq/v1/webhook-callback' );
    $license_key = $value;

    $request_body = array(
        'licenseKey'      => $license_key,
        'wp_callback_url' => $callback_url,
    );

    $response = wp_remote_post( $api_url, array(
        'headers' => array(
            'Content-Type' => 'application/json',
        ),
        'body'    => wp_json_encode( $request_body ),
        'timeout' => 15,
    ) );

    $return = array(); // Initialize return array

    if ( is_wp_error( $response ) ) {
        $field['msg'] = 'Network error. Please try again.';
        $return['error'] = $field;
        $return['value'] = $value;
        return $return;
    }

    $code = wp_remote_retrieve_response_code( $response );
    $response_body = wp_remote_retrieve_body( $response );
    $data = json_decode( $response_body, true );

    // Defensive check in case response is not JSON
    if ( ! is_array( $data ) ) {
        $field['msg'] = 'Unexpected server response.';
        $return['error'] = $field;
        $return['value'] = $value;
        return $return;
    }

    if ( $code === 403 && ! empty( $data['error'] ) && $data['error'] === 'invalid_license_key' ) {
        $field['msg'] = 'Invalid license key.';
        $return['error'] = $field;
        $return['value'] = $value;
        return $return;
    }

    if ( $code >= 400 ) {
        $field['msg'] = 'Error. Try again.';
        $return['error'] = $field;
        $return['value'] = $value;
        return $return;
    }

    $return['value'] = $value;
    $return['error'] = false;
    return $return;
}