// Miva Merchant
//
// This file and the source codes contained herein are the property of
// Miva, Inc.  Use of this file is restricted to the specific terms and
// conditions in the License Agreement associated with this file.  Distribution
// of this file or portions of this file for uses not covered by the License
// Agreement is not allowed without a written agreement signed by an officer of
// Miva, Inc.
//
// Copyright 1998-2024 Miva, Inc.  All rights reserved.
// http://www.miva.com
//
// Prefix         : MER-PAY-AMZV2-RUN-
// Next Error Code: 3
//

// AmazonPay v2 Runtime helper functions
////////////////////////////////////////////////////

function AmazonPay_ChangeShippingAddress( checkout_session_id )
{
	amazon.Pay.changeShippingAddress( {
		amazonCheckoutSessionId: checkout_session_id
	} );
}

function AmazonPay_ChangePaymentMethod( checkout_session_id )
{
	amazon.Pay.changePaymentMethod( {
		amazonCheckoutSessionId: checkout_session_id
	} );
}

function AmazonPay_ReloadBasketContents( url, callback )
{
	const http_request				= new XMLHttpRequest();
	http_request.withCredentials	= true;

	http_request.open( 'POST', `${url}Store_Code=${AJAX_CharsetEncodeAttribute( Store_Code )}&Screen=AMAZONPAY_REVIEW`, true );
	http_request.setRequestHeader( 'If-Modified-Since',				'Sat, 1 Jan 2000 00:00:00 GMT' );
	http_request.setRequestHeader( 'Content-Type',					'application/json' );
	http_request.setRequestHeader( 'X-Miva-Partial-Render',			'basket' );
	http_request.setRequestHeader( 'X-Miva-Partial-Render-Output',	'json' );

	http_request.addEventListener( 'load', function( event )
	{
		var response;

		try
		{
			response = JSON.parse( http_request.responseText );
		}
		catch ( e )
		{
			response				= new Object();
			response.success		= 0;
			response.error_code		= 'MER-PAY-AMZV2-RUN-00001';
			response.error_message	= 'Miva Merchant returned an invalid response.\n' +
									  'Function: Partial Page Load' + '\n' +
									  'Response: ' + http_request.responseText;
		}

		if ( typeof callback === 'function' )
		{
			callback( response );
		}
	} );

	http_request.send( JSON.stringify( { Session_Type: 'runtime' } ) );
}

function AmazonPay_Runtime_FindAndValidateProductAddForm( button_element )
{
	var form;

	for ( form = button_element.parentNode; form && form.nodeName != 'FORM'; form = form.parentNode )
	{
		;
	}

	if ( !form )										return;
	if ( !AmazonPay_Runtime_FormIsProductAdd( form ) )	return;

	return form;
}

function AmazonPay_Runtime_FormIsProductAdd( form )
{
	return form.elements[ 'Quantity' ]		&&
		   form.elements[ 'Product_Code' ]	&&
		   form.elements[ 'Action' ]		&&
		   form.elements[ 'Action' ].value === 'ADPR';
}

function AmazonPay_Runtime_FormGatherInputElements( parent_element )
{
	var i, type, inputs, selects, textareas, output_array, addToOutput;

	output_array	= new Array();
	inputs			= parent_element.getElementsByTagName( 'input' );
	textareas 		= parent_element.getElementsByTagName( 'textarea' );
	selects			= parent_element.getElementsByTagName( 'select' );

	addToOutput		= ( field ) =>
	{
		const name = field?.name?.toLowerCase() ?? '';

		if ( name == 'quantity'						||
			 name == 'product_code'					||
			 name == 'product_subscription_term_id'	||
			 name.indexOf( 'product_attributes[' ) == 0 )
		{
			output_array.push( field );
		}
	}

	for ( const input of inputs )
	{
		type = input.type.toLowerCase();

		if ( ( type == 'text' ) || ( type == 'number' ) || ( type == 'tel' ) || ( type == 'hidden' ) )
		{
			addToOutput( { name: input.name, value: input.value } );
		}
		else if ( ( type == 'checkbox' ) || ( type == 'radio' ) )
		{
			if ( input.checked )
			{
				addToOutput( { name: input.name, value: input.value } );
			}
		}
	}

	for ( const textarea of textareas )
	{
		addToOutput( { name: textarea.name, value: textarea.value } );
	}

	for ( const select of selects )
	{
		if ( !select.multiple )
		{
			if ( select.selectedIndex >= 0 && select.options[ select.selectedIndex ] )
			{
				addToOutput( { name: select.name, value: select.options[ select.selectedIndex ].value } );
			}
		}
		else
		{
			for ( i = 0; i < select.options.length; i++ )
			{
				if ( !select.options[ i ].selected )
				{
					continue;
				}

				addToOutput( { name: select.name, value: select.options[ i ].value } );
			}
		}
	}

	return output_array;
}

// AmazonPay v2 Runtime AJAX calls
////////////////////////////////////////////////////

function AmazonPay_Runtime_SetShippingMethod( shipping_method, callback, delegator )
{
	return AJAX_Call_Module_JSON( callback, 'runtime', 'amazonpayv2', 'AmazonPay_Runtime_SetShippingMethod',
	{
		ShippingMethod: shipping_method
	}, delegator );
}

function AmazonPay_Runtime_GetCheckoutSessionPayload( callback, delegator )
{
	return AJAX_Call_Module_JSON( callback, 'runtime', 'amazonpayv2', 'AmazonPay_Runtime_GetCheckoutSessionPayload', null, delegator );
}

function AmazonPay_Runtime_GetCheckoutSessionPayloadWithProduct( button_container_id, callback, delegator )
{
	var product_add_form;

	if ( ( product_add_form = AmazonPay_Runtime_FindAndValidateProductAddForm( document.getElementById( button_container_id ) ) ) == null )
	{
		return callback( {
			success:		0,
			error_code:		'MER-PAY-AMZV2-RUN-00002',
			error_message:	'Unable to locate product form'
		} );
	}

	return AJAX_Call_Module_JSON_FieldList( callback, 'runtime', 'amazonpayv2', 'AmazonPay_Runtime_GetCheckoutSessionPayloadWithProduct', null, AmazonPay_Runtime_FormGatherInputElements( product_add_form ), delegator );
}