async function setupApplepay() {
	
  const applepay = paypal.Applepay();
    const {
      isEligible,
      countryCode,
      currencyCode,
      merchantCapabilities,
      supportedNetworks,
    } = await  applepay.config();

  if (!isEligible) {
    throw new Error("Not eligible for Apple Pay");
  } else {
  	//alert("Eligible for ApplePay");
  }

  document.getElementById("applepay-container").innerHTML =
    '<div class="apple-pay-button apple-pay-button-white" id="btn-appl"></div>';
    
   /* '<apple-pay-button id="btn-appl" buttonstyle="plain" type="buy" locale="en" style="-apple-pay-button-type: plain !important;">';*/

  document.getElementById("btn-appl").addEventListener("click", onClick);

//	alert('Test');
//
//	const client_id = "AZsMPHqx0TlbCyV_8AY5LlNzzmilpaP8lbfQQQ4iPRpk_WC8hOWFWdvnGMgln4RJAAO2oWd7g1PhhMtu";
//	const client_secret = "EFZpihetGeQCYOA_zWas7iTQ1Le32fSmBvgZd5tZ01TvonU8hwxEQnbjD6Xjmqzasu4ZtiDHmO4sBaRa";
//	const auth = base64.encode(client_id + ":" + client_secret);
//	
//	alert(auth);

	console.log({ merchantCapabilities, currencyCode, supportedNetworks })
	//var amountt= document.getElementById("t_amount").value;
	var amountt= "0.01";
	var memID= document.getElementById("mem_ID").value;
	var chID= document.getElementById("ch_ID").value;
	
	//alert('Update works!')
	
  async function onClick() {
	
	console.log("Amount: ",amountt);
	console.log("Member ID: ",memID);

    const paymentRequest = {
      countryCode,
      currencyCode: 'USD',
      merchantCapabilities,
      supportedNetworks,
      requiredBillingContactFields: [
        "name",
        "phone",
        "email",
        "postalAddress",
      ],
      requiredShippingContactFields: [
      ],
      total: {
        label: "CrowdKode Credits: " + chID,
        amount: amountt,
        type: "final",
      },
    };

    let session = new ApplePaySession(4, paymentRequest);

    session.onvalidatemerchant = (event) => {
      applepay
        .validateMerchant({
          validationUrl: event.validationURL,
        })
        .then((payload) => {
          session.completeMerchantValidation(payload.merchantSession);
        })
        .catch((err) => {
          console.error(err);
          session.abort();
        });
    };

    session.onpaymentmethodselected = () => {
      session.completePaymentMethodSelection({
        newTotal: paymentRequest.total,
      });
    };
 
    session.onpaymentauthorized = async (event) => {
      try {
      	/* Generate Access Token */
      	const response = await fetch('genaccessToken.php', {
			  method: 'POST',
			  headers: {'Accept': 'application/json'},
			  body: "nada"
		  })
		  /*.then((response) => response.json())
		  .then((result) => {
			  const accessToken = result.access_token;
			  //alert("New Access Token Generated: ", accessToken)
		  })*/

		  const result = await response.json();
		  const accessToken = result.access_token;
		  //alert(accessToken)
		  
        /* Create Order on the Server Side */
        /* const base = "https://api-m.sandbox.paypal.com"; */
        const base = "https://api-m.paypal.com/v2";
        /* const accessToken = "A21AAORwBgrkZI5RFQvD0WkfY5N2GPHd0J1xXDS6Vo6HI37sc6JHqcr7yCMGxKfVbQsZiQ_g3hrBIa1MF89316JNL7fK23v_A"; */
        const orderResponse = await fetch(`https://api-m.paypal.com/v2/checkout/orders`,{
          method:'POST',
          headers : {
            'Content-Type': 'application/json',
             Authorization: `Bearer ${accessToken}`,
          },
          body: JSON.stringify({
			  intent: "CAPTURE",
			  purchase_units: [
				  {
					  amount: {
						  currency_code: "USD",
						  value: amountt
					  },
					  description: 'CrowdKode Credits: ' + chID,
					  custom_id: memID,
				  },
			  ],
		   }),
        })
        /* '1.00' '123456' */
        if(!orderResponse.ok) {
            throw new Error("error creating order")
            //alert('Error with orderResponse')
        }
        console.log("MemID2:", memID);
        console.log("Order Response New 87...")  
        
        const orderData = await orderResponse.json();
		//alert('orderData section....')

		if (orderData.id) {
			console.log("orderData.id does exist")
			console.log(orderData.id);
			console.log(orderData);
			//const checkoutAmount = orderData.purchase_units['amount']['value'];
			//console.log(checkoutAmount)
			//return orderData.id;
		} else {
			const errorDetail = orderData?.details?.[0];
			const errorMessage = errorDetail
			? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
			: JSON.stringify(orderData);

			throw new Error(errorMessage);
		}
		
 		//console.log(orderResponse);
 		//console.log(orderResponse.text());
        /* WAS: const { id } = await orderResponse.json() */
        //const { id } = await orderResponse.text()
        //console.log({ id })
        
        //const orderData = await orderResponse.text()

//		if (orderData.id) {
//			console.log("orderData.id does exist")
//			 console.log(orderData.id)
//			return orderData.id;
//		} else {
//			orderData.id = "71130573LJ748815F";	
//		}

        /**
         * Confirm Payment   
         */
        console.log("Confirm Order starts...")
        console.log(event.payment.token)
        await applepay.confirmOrder({ 
	        orderId: orderData.id, 
	        token: event.payment.token, 
	        billingContact: event.payment.billingContact, 
	        shippingContact: event.payment.shippingContact 
        });
		console.log("Confirm Order ends...")
        /*
        * Capture order (must currently be made on server) 
        */
        /* https://api-m.paypal.com/v2/checkout/orders/6UD051085Y0427820/capture */
        await fetch(`https://api-m.paypal.com/v2/checkout/orders/${orderData.id}/capture`, {
          method: 'POST',
          headers : {
			  'Content-Type': 'application/json',
			  Authorization: `Bearer ${accessToken}`,
		  },
        });
		console.log("Almost complete...")
		/* 
		LOG IT IN THE TRANSACTIONS TABLE
		SHOW A SUCCESS MESSAGE */

        session.completePayment({
          status: window.ApplePaySession.STATUS_SUCCESS,
        });
        
        // TRY TO SAVE THE ORDER IN THE TRANSACTIONS TABLE //
        
        var postData = {paypal_order_check: 1, order_id: orderData.id};
		fetch('paypal_checkout_validate.php', {
			method: 'POST',
			headers: {'Accept': 'application/json'},
			body: encodeFormData(postData)
		})
		.then((response) => response.json())
		.then((result) => {
			if (result.status == 1) {
				window.location.href = "payment-status.php?checkout_ref_id="+result.ref_id;
			} else {
				const messageContainer = document.querySelector("#paymentResponse");
				messageContainer.classList.remove("hidden");
				messageContainer.textContent = result.msg;

				setTimeout(function () {
					messageContainer.classList.add("hidden");
					messageText.textContent = "";
				}, 5000);
			}
			setProcessing(false);
		})
        
        /////////////////////////////////////////////////////
        resultMessage(
		`Thank you! Your ApplePay payment was successful.`,
		);
		document.querySelector("#result-message").classList.remove("hidden");
		
		var postData = {paypal_order_check: 1, order_id: orderData.id};
		fetch('paypal_checkout_validate.php', {
			method: 'POST',
			headers: {'Accept': 'application/json'},
			body: encodeFormData(postData)
		})
      } catch (err) {
        console.error(err);
        session.completePayment({
          status: window.ApplePaySession.STATUS_FAILURE,
        });
      }
    };

    session.oncancel  = () => {
      console.log("Apple Pay Cancelled!")
    }

    session.begin();
  }
}

document.addEventListener("DOMContentLoaded", () => {
	if (window.ApplePaySession) {
		if (window.ApplePaySession.canMakePayments) {
			//alert('hi, I can do ApplePay.....');
			setupApplepay().catch(console.error);
		}
	}
  // eslint-disable-next-line no-undef
//  if(ApplePaySession?.supportsVersion(4) && ApplePaySession?.canMakePayments()) {
//    setupApplepay().catch(console.error);
//  }
});

// Example function to show a result to the user. Your site's UI library can be used instead.
function resultMessage(message){
	const container = document.querySelector("#result-message");
	container.innerHTML = message;
}