//live atga api key
let stripe = Stripe('pk_live_TKWoRaSmmMOKD3XijTcpdfE4');  //  pk_live_FRhCsyM1O8PQGjotPIZMDWVA

let elements = stripe.elements();
let isFormLoading = false;
let USER_DATA = {};



var FITMENTOPTIONS = {
  RemoteImmob: '1',
  AlarmIntegration: '2',
  SOSButton: '4',
  NotConnectedIgn: '8',
  FitmentAfterIsolater: '16',
  EngineTheft: '32',
  Siren: '64',
  BilgeAlarm: '128',
  ShorePowerDisconn: '256',
  RemoteDoor: '512'
}

var PRODUCTFEATURES = {
  Input1: 16777216,
  Input2: 131072,

  Input3: 33554432,
  Input4: 67108864,
  Output1: 134217728,
  Output2: 268435456,

  Power: 128,
}


const style = {
  base: {
    color: "#32325d",
    fontFamily:
      '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
    fontSmoothing: "antialiased",
    fontSize: "16px",
    "::placeholder": {
      color: "#aab7c4"
    },
    ":-webkit-autofill": {
      color: "#32325d"
    }
  },
  invalid: {
    color: "#fa755a",
    iconColor: "#fa755a",
    ":-webkit-autofill": {
      color: "#fa755a"
    }
  }
};

const options = {
  style: style,
  disabled: false,
  hideIcon: false,
  iconStyle: "default" // or "solid"
};

// Create an instance of the auBankAccount Element.
const auBankAccount = elements.create("auBankAccount", options);

// Add an instance of the auBankAccount Element into
// the `au-bank-account-element` <div>.
auBankAccount.mount("#au-bank-account-element");

auBankAccount.on("change", function (event) {
  // Reset error state
  document.getElementById("error-message").classList.remove("visible");
  // Display bank name corresponding to auBankAccount, if available.
  const bankName = document.getElementById("bank-name");
  if (event.bankName && event.branchName) {
    bankName.textContent = `${event.bankName} (${event.branchName})`;
    bankName.classList.add("visible");
  } else if (event.bankName) {
    bankName.textContent = `${event.bankName}`;
    bankName.classList.add("visible");
  } else {
    bankName.classList.remove("visible");
  }
  // Handle real-time validation errors from the Element.
  if (event.error) {
    showError(event.error.message);
  }
});


$(function () {
  let card = elements.create('card');
  let form = document.getElementById("payment-form");
  let formBecs = document.getElementById("payment-form-becs");
  

  card.mount('#card-element');

  card.on('change', function (event) {
    // Disable the Pay button if there are no card details in the Element
    document.querySelector("#submit").disabled = event.empty;
    document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
  });

  form.addEventListener("submit", handleSubmitPaymentForm);
  formBecs.addEventListener("submit", handleSubmitPaymentForm);
 

  function handleSubmitPaymentForm(event) {
    event.preventDefault();

 
    //let $this = $('[name="activation"]');
    let address_state = $('[name="address4"]').val();
    let address_zip = $('[name="address5"]').val();
    let address_city = $('[name="address3"]').val();
    let address_line1 = $('[name="address1"]').val();
    let country = $('[name="country"]').val();

    let firstName = $('[name="firstName"]').val();
    let subName = $('[name="subName"]').val();
    let name = firstName + ' ' + subName;
    let email = $('[name="email"]').val();
    let imei = $('[name="imei"]').val();
    let account = $('[name="account"]').val();
    let priceId = $('[name="servicePlan"] option:selected').data('priceid');
    let solution = $('[name="solutionType"]').val();
    let paymentType = $('input[name="paymentType"]:checked').val();


    let $this = $('[name="activation"]');
 

    let splitedName = name.split(' ');


    if (imei) {
        imei = imei.padStart(16, '0');  
    }
 

    if (!firstName && !subName) {
      if (account.indexOf("@") !== -1) {
        name = account.split("@")[0];
      } else {
        name = account
      }
    }
    /*if($this.hasClass('form-register')){
      name = $('[name="firstName"]').val() + ' ' + $('[name="subName"]').val();
    }else if($this.hasClass('form-activate') || $this.hasClass('form-replace') || $this.hasClass('form-upgrade')){
      if(email) {
        name = email.split("@")[0];
      }else if(account){
        name = account.split("@")[0];
      }
    }*/

    // Complete payment when the submit button is clicked
    loading(true);

    console.log('paymentType', paymentType)
    if (paymentType === '12') {
      stripe
      .createPaymentMethod({
        type: 'card',
        card: card,
        billing_details: {
          name: name,
        },
      })
      .then((result) => {
        if (result.error) {
          showError(result.error.message);
        } else {
          createSubscription({
            //customerId: customerId,
            paymentMethodId: result.paymentMethod.id,
            priceId: priceId,
            email: email,
            imei: imei,
            firstName: firstName,
            subName: subName,
            country: country,
            address_line1: address_line1,
            address_city: address_city,
            address_zip: address_zip,
            address_state: address_state
          });
        }
      });
    } else if (paymentType === '13') {

      const submitButton = document.getElementById('submit-button-becs');
      const clientSecret = submitButton.dataset.secret;

      stripe.confirmAuBecsDebitSetup(
        clientSecret,
        {
          payment_method: {
            au_becs_debit: auBankAccount,
            billing_details: {
              name: name,
              email: email
            }
          }
        }
      ).then((result) => {
        if (result.error) {
          showError(result.error.message);
        } else {
          console.log('result', result)

       
            
         
            createSubscription({
              //customerId: customerId,
              setupIntentId: result.setupIntent.id,
              paymentMethodId: result.setupIntent.payment_method,
              priceId: priceId,
              email: email,
              imei: imei,
              firstName: firstName,
              subName: subName,
              account
            });
       
        }
      });
     
     

    }

  }
})



$('[name="activation"]').validator().on('submit', function (e) {
  $('.info').empty();

  if (e.isDefaultPrevented()) {
    // handle the invalid form...
    console.log('has error');
    return
  }
  // everything looks good!
  e.preventDefault();

  let verifyUrl = '';

  let $this = $(this);
  USER_DATA.domain = $('[name="domain"]').val();
  USER_DATA.projectTypeNumber = $('[name="projectNumber"]').val();
  USER_DATA.dealerToken = $('[name="dealerToken"]').val();
  USER_DATA.dealerName = $('[name="dealerName"]').val();
  USER_DATA.imei = $('[name="imei"]').val();
  USER_DATA.imei2 = $('[name="imei2"]').val();
  USER_DATA.isIridium = $('[name="isDeviceIridiumConnected"]:checked').val()  === 'yes' ? 1 : 0;

  /*new email*/

  //newEmail($('[name="account"]').val())

  /*new email*/

  USER_DATA.MajorToken = $('[name="MajorToken"]').val();
  USER_DATA.MinorToken = $('[name="MinorToken"]').val();
  USER_DATA.account = $('[name="account"]').val();
  USER_DATA.email = $('[name="email"]').val();

  USER_DATA.name = $('[name="name"]').val();
  USER_DATA.describe1 = $('[name="describe1"]').val();
  USER_DATA.describe2 = $('[name="describe2"]').val();
  USER_DATA.describe3 = $('[name="describe3"]').val();
  USER_DATA.describe4 = $('[name="describe4"]').val();
  USER_DATA.servicePlanCode = $('[name="servicePlan"]').val();
  USER_DATA.servicePlan = $('[name="servicePlan"] option:selected').text();
  USER_DATA.servicePlanType = $('[name="servicePlan"] option:selected').data('plantype');
  USER_DATA.solutionCode = $('[name="solution"]').val();
  USER_DATA.solution = $('[name="solution"] option:selected').text();
  USER_DATA.deviceType = $('[name="deviceType"]').val();

  USER_DATA.assetType = $('[name="assetType"]').val();
  USER_DATA.instalLocation = $('[name="instalLocation"]').val();
  USER_DATA.notes = $('[name="notes"]').val();
  USER_DATA.isDeviceInstalled = $('[name="isDeviceInstalled"]:checked').val();
  USER_DATA.initialMileage = $('[name="initialMileage"]').val();
  USER_DATA.initialEngineHours = $('[name="initialEngineHours"]').val();

  USER_DATA.paymentTypeCode = $('input[name="paymentType"]:checked').val();
  USER_DATA.paymentType = $('input[name="paymentType"]:checked').siblings('span').text();

  switch (USER_DATA.paymentTypeCode) {
    case '1':
      USER_DATA.paymentType += '';
      USER_DATA.payment1 = $('[name="ccType"]:checked').val();
      USER_DATA.payment2 = $('[name="ccNumber"]').val();
      USER_DATA.payment3 = $('[name="ccExpiryDate"]').val();
      USER_DATA.payment4 = $('[name="ccNameOnCard"]').val();
      USER_DATA.payment5 = $('[name="ccCVV"]').val();
      break;
    case '12':
      USER_DATA.paymentType += '';
      USER_DATA.payment1 = $('[name="ccType"]:checked').val();
      USER_DATA.payment2 = $('[name="ccNumber"]').val();
      USER_DATA.payment3 = $('[name="ccExpiryDate"]').val();
      USER_DATA.payment4 = $('[name="ccNameOnCard"]').val();
      USER_DATA.payment5 = $('[name="ccCVV"]').val();

      //error_code = validateCreditCardNumber({'ccNum':USER_DATA.payment2});
      break;
    case '2':
      USER_DATA.payment1 = $('[name="bankAccountName"]').val();
      USER_DATA.payment2 = $('[name="bankName"]').val();
      USER_DATA.payment3 = $('[name="bankBSB"]').val();
      USER_DATA.payment4 = $('[name="bankAccountNumber"]').val();
      break;
    case '4':
      USER_DATA.paymentType = 'voucher';
      USER_DATA.payment1 = $('[name="voucherCode"]').val();
      break;
    default:
      USER_DATA.payment1 = $('[name="invoiceName"]').val();
      USER_DATA.payment2 = $('[name="invoiceNumber"]').val();
      USER_DATA.payment3 = $('[name="invoiceRUT"]').val();
      USER_DATA.payment4 = $('[name="invoiceEmail"]').val();
  }

  if ($('[name="autosuspend"]').prop('checked')) {
    USER_DATA.autosuspend = 1;
  } else {
    USER_DATA.autosuspend = 0;
  }

  if ($('[name="renewal"]').prop('checked')) {
    USER_DATA.localRenewal = 1;
  } else {
    USER_DATA.localRenewal = 0;
  }

  /*USER_DATA.fitoptions = $('[name="fitoptions"]').val();
  if (USER_DATA.fitoptions && USER_DATA.fitoptions.length) {
    USER_DATA.fitoptions = USER_DATA.fitoptions.reduce((a, b) => parseInt(a) + parseInt(b), 0);
  }else{
    USER_DATA.fitoptions = 0;
  }*/


  let solutionTypeFeatures = $('#solution').find('option:selected').data('features');
  if (solutionTypeFeatures && solutionTypeFeatures.indexOf("IO,") >= 0) {
    let deviceTypeFeatures = $('#deviceType').data('features');
    if ((deviceTypeFeatures & PRODUCTFEATURES.Input1) > 0
      || (deviceTypeFeatures & PRODUCTFEATURES.Input2) > 0) {
      let isInputsConnected = $('[name="isDeviceInputsConnected"]:checked').val();
      if (isInputsConnected === 'yes') {
        if ((deviceTypeFeatures & PRODUCTFEATURES.Input1) > 0) {
          USER_DATA.Input1 = $('[name="Input1"]').val();
          USER_DATA.Input1MaskTime = $('[name="Input1MaskTime"]').val();
          USER_DATA.Input1Type = $('[name="Input1Type"]').val();
          if (!USER_DATA.Input1.length) {
            alert('Please choose option for the Input1 name')
            return
          }
        }
        if ((deviceTypeFeatures & PRODUCTFEATURES.Input2) > 0) {
          USER_DATA.Input2 = $('[name="Input2"]').val();
          USER_DATA.Input2MaskTime = $('[name="Input2MaskTime"]').val();
          USER_DATA.Input2Type = $('[name="Input2Type"]').val();
          if (!USER_DATA.Input2.length) {
            alert('Please choose option for the Input2 name')
            return
          }
        }
      } else if (isInputsConnected === 'notselected') {
        alert('Please choose one option "Yes" or "No" under the question "Has the device inputs been connected ?"')
        return
      }
    }
  }
  if (solutionTypeFeatures && solutionTypeFeatures.indexOf("LOWER_POWER,") >= 0) {
    USER_DATA.LowerPower = $('[name="LowerPower"]').val();
  }
  if (solutionTypeFeatures && solutionTypeFeatures.indexOf("DISCONNECT_POWER,") >= 0) {
    USER_DATA.DisconnectPower = $('[name="DisconnectPower"]').val();
  }
  if (solutionTypeFeatures && solutionTypeFeatures.indexOf("IGNITION_ON,") >= 0) {
    USER_DATA.IgnitionPower = $('[name="IgnitionPower"]').val();
  }


  USER_DATA.fitoptions = $('[name="fitoptions"]').val();
  if (USER_DATA.fitoptions && USER_DATA.fitoptions.length) {
    USER_DATA.fitoptions = USER_DATA.fitoptions.reduce((a, b) => parseInt(a) + parseInt(b), 0);
  } else {
    USER_DATA.fitoptions = 0;
  }

  if ($this.hasClass('form-register')) {



    verifyUrl = 'php/save_in_db_r_verify.php';

    USER_DATA.accountName = $('[name="accountName"]').val();
    USER_DATA.firstName = $('[name="firstName"]').val();
    USER_DATA.subName = $('[name="subName"]').val();
    USER_DATA.fullName = USER_DATA.firstName + ' ' + USER_DATA.subName;

    USER_DATA.countryCode = $('[name="country"]').val();
    USER_DATA.country = $('[name="country"] option:selected').text();
    USER_DATA.timeZone = $('[name="timeZone"]').val();
    USER_DATA.languageCode = $('[name="language"]').val();
    USER_DATA.language = $('[name="language"] option:selected').text();
    USER_DATA.address1 = $('[name="address1"]').val();
    /*USER_DATA.address2 = $('[name="address2"]').val();*/
    USER_DATA.address3 = $('[name="address3"]').val();
    USER_DATA.address4 = $('[name="address4"]').val();
    USER_DATA.address5 = $('[name="address5"]').val();
    //USER_DATA.password = $('[name="password"]').val();

    USER_DATA.emContact = {
      contact1: {
        firstName: $('[name="emcfirstname1"]').val(),
        lastName: $('[name="emclastname1"]').val(),
        email: $('[name="emcemail1"]').val(),
        phone: $('[name="emcphone1"]').val(),
      },
      contact2: {
        firstName: $('[name="emcfirstname2"]').val(),
        lastName: $('[name="emclastname2"]').val(),
        email: $('[name="emcemail2"]').val(),
        phone: $('[name="emcphone2"]').val(),
      },
    };

    var phoneCode = $('[name="phoneCode"]').val();
    var mobile = $('[name="mobile"]').val();
    if ('+61' == phoneCode) {
      if (mobile[0] === 0) {
        mobile = mobile.substring(1);
      }
    }
    USER_DATA.phoneCode = phoneCode;
    USER_DATA.mobile = mobile;



    /*let isInputsConnected = $('[name="isDeviceInputsConnected"]:checked').val();
            if(isInputsConnected === 'yes'){
              if((deviceTypeFeatures & PRODUCTFEATURES.Input1) > 0){
                USER_DATA.Input1 = $('[name="Input1"]').val();
                USER_DATA.Input1MaskTime = $('[name="Input1MaskTime"]').val();
                USER_DATA.Input1Type = $('[name="Input1Type"]').val();
                            if(!USER_DATA.Input1.length){
                              alert('Please choose option for the Input1 name')
                              return
                          }
              }
              if((deviceTypeFeatures & PRODUCTFEATURES.Input2) > 0){
                USER_DATA.Input2 = $('[name="Input2"]').val();
                USER_DATA.Input2MaskTime = $('[name="Input2MaskTime"]').val();
                USER_DATA.Input2Type = $('[name="Input2Type"]').val();
                            if(!USER_DATA.Input2.length){
                              alert('Please choose option for the Input2 name')
                              return
                          }
              }
            }else if(isInputsConnected === 'notselected'){
              alert('Please choose one option "Yes" or "No" under the question "Has the device inputs been connected ?"')
                        return
            }*/


  } else if ($this.hasClass('form-replace')) {
    verifyUrl = 'php/save_in_db_replace_verify.php';
    USER_DATA.imeiOld = $('[name="imeiOld"]').val();

  } else if ($this.hasClass('form-activate')) {
    verifyUrl = 'php/save_in_db_a_verify.php';

  } else if ($this.hasClass('form-reactivate')) {
    verifyUrl = 'php/save_in_db_a_verify.php';

  } else if ($this.hasClass('form-upgrade')) {
    //TODO need to finish with verify file
    verifyUrl = 'php/save_in_db_u2l_verify.php';

  }

  if (isFormLoading) {
    return;
  }

  //|| $this.hasClass('form-activate'

  if (USER_DATA.paymentTypeCode === '12' || USER_DATA.paymentTypeCode === '13') {
    isFormLoading = true;
    $('.form_submit').toggleClass('disabled');
    $('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
    preloader.on();
    fetch(verifyUrl, {
      method: 'post',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(USER_DATA),
    })
      .then((response) => {
        return response.json();
      })
      .then((result) => {
        isFormLoading = false;
        $('.form_submit').toggleClass('disabled');
        $('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
        preloader.off();

        switch (result.replyCode) {
          case '9999': case '1005': case '1004': case '1002': case '1000':
            $('.info').html('<div class="errors">' + result.msg + '</div>');
            break;

          case '000':
            console.log('before stripe')
            if (!$this.hasClass('form-register')) {
              let email = $('[name="email"]').val();
              let imei = $('[name="imei"]').val();
              let paymentType = $('input[name="paymentType"]:checked').val();
              let priceId = $('[name="servicePlan"] option:selected').data('priceid');
             
              if(isDefaultPaymentExists) {
                createSubscription({
                  priceId: priceId,
                  email: email,
                  imei: imei,
                });
              } else {
                if(USER_DATA.paymentTypeCode === '12') {
                  $('#modalStripePayment').modal({ keyboard: false, show: true, backdrop: 'static' });
                } else {
                  $('#modalStripePaymentBSB').modal({ keyboard: false, show: true, backdrop: 'static' });
                }
              }
              
            } else {
              //console.log('USER_DATA.paymentTypeCode', USER_DATA.paymentTypeCode)
              
                if(USER_DATA.paymentTypeCode === '12') {
                  $('#modalStripePayment').modal({ keyboard: false, show: true, backdrop: 'static' });
                } else {
                  $('#modalStripePaymentBSB').modal({ keyboard: false, show: true, backdrop: 'static' });
                }
         
           
            }

            break;
          default:
            $('.info').html('<div class="processing">Your request is being processed in the background at the moment. Please wait 15 minutes and check your asset, if it is still not processed, please try again.</div>');
        }
      }).catch((error) => {
        // An error has happened. Display the failure to the user here.
        // We utilize the HTML element we created.
        //showCardError(error);
        //console.log(error)
        //console.log(error.message)
        isFormLoading = false;
        $('.form_submit').toggleClass('disabled');
        $('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
        preloader.off();
        showError(error.message);
      })

  } else if (USER_DATA.paymentTypeCode === '13') {

  }
  else {
    console.log('fin', USER_DATA)
    finalizeActivation(USER_DATA)
  }
  /*else if(USER_DATA.paymentTypeCode === '1'){
    isFormLoading = true;
    $('.form_submit').toggleClass('disabled');
    $('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
	
        USER_DATA.payment1 = $('[name="ccType"]:checked').val();
        USER_DATA.payment2 = $('[name="ccNumber"]').val();
        USER_DATA.payment3 = $('[name="ccExpiryDate"]').val();
        USER_DATA.payment4 = $('[name="ccNameOnCard"]').val();
        USER_DATA.payment5 = $('[name="ccCVV"]').val();

        error_code = validateCreditCardNumber({'ccNum':USER_DATA.payment2});
    preloader.on();
  }*/



});

async function sendReqLog(LOG_DATA) {
  LOG_DATA.Dealer = 'atga'
  LOG_DATA.Login = '_';//$('[name="account"]').val();
  LOG_DATA.DealerToken = '_';//$('[name="dealerToken"]').val();
  LOG_DATA.IMEI = LOG_DATA.Msg;


let query = {
          "imei": LOG_DATA.IMEI,
          "demoAndTrail":"763926247",
          "servicePlan":"37344553990",
          "deliveryDestinations":[{
              "destination":"136.243.44.238:30903",
              "deliveryMethod":1,
              "geoDataFlag":"true",
              "moAckFlag":"false"
          },
          {
              "destination":"216.219.94.83:30902",
              "deliveryMethod":1,
              "geoDataFlag":"true",
              "moAckFlag":"false"
          },
          {
              "destination":"sbd.quiktrak@gmail.com",
              "deliveryMethod":0,
              "geoDataFlag":"true",
              "moAckFlag":"false"
          },
          {
              "destination":"mark@sinopacific.co",
              "deliveryMethod":0,
              "geoDataFlag":"true",
              "moAckFlag":"false"
          }
          ]
      }


await fetch('https://webhook.quiktrak.co/Iws/ActivateDevice', {
						method: "POST",
						body: JSON.stringify(query), 
						headers: {
							'Accept': 'application/json',
							'Content-Type': 'application/json'
						  }
					});

  $.ajax({
    type: "POST",
    url: "https://cartrack.co/activation/al3rtgps/php/reqlog_activation.php",
    dataType: 'json',
    data: LOG_DATA,
    async: true,
    cache: false,
    beforeSend: function () {

    },
    success: function (data) {
      console.log('sent')
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      console.log('not sent')
    }
  });
}

function sendLog(LOG_DATA) {
  LOG_DATA.Dealer = 'atga'
  LOG_DATA.Login = '_';//$('[name="account"]').val();
  LOG_DATA.DealerToken = '_';//$('[name="dealerToken"]').val();
  LOG_DATA.IMEI = $('[name="imei"]').val();


  $.ajax({
    type: "POST",
    url: "https://cartrack.co/activation/al3rtgps/php/log_activation.php",
    dataType: 'json',
    data: LOG_DATA,
    async: true,
    cache: false,
    beforeSend: function () {

    },
    success: function (data) {
      console.log('sent')
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      console.log('not sent')
    }
  });
}


function createSubscription({ email, paymentMethodId, priceId, imei, firstName, subName, address_line1, address_city, address_zip, address_state, paymentType, setupIntentId }) {

  const requestBody = {
    email: email,
    priceId: priceId,
    imei: imei,
    line1: address_line1,
    city: address_city,
    postal_code: address_zip,
    state: address_state,
    country: "AU",
    firstName: firstName,
    subName: subName,
    paymentType: paymentType
  };

  if (paymentMethodId) {
    requestBody.paymentMethodId = paymentMethodId;
  }

  if (setupIntentId) {
    requestBody.setupIntentId = setupIntentId;
  }

  return (
    fetch('php/stripe-create.php', {
      method: 'post',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(requestBody),

    })
      .then((response) => {
        return response.json();
      })
      // If the card is declined, display an error to the user.
      .then((result) => {
        console.log('result1', result);
        if (result.message) {
          showModalInfo({
            textClass: 'text-success',
            text: result.message
          });
        }
        if (result.error) {
          if(result.replyCode === '200') {
            //console.log('paymentType', paymentType)
            if(paymentType == "12") {
              $('#modalStripePayment').modal({ keyboard: false, show: true, backdrop: 'static' });

            }else if(paymentType == '13') {
              $('#modalStripePaymentBSB').modal({ keyboard: false, show: true, backdrop: 'static' });

            }
          }
          else {
            showModalInfo({
              textClass: 'text-danger',
              text: result.error
            });
          }
         
          throw result;
        }
      

        return result;
      })
      // Normalize the result to contain the object returned by Stripe.
      // Add the additional details we need.
      .then((result) => {
        const returnObject = {
          priceId: priceId,
          subscription: result,
        };
        if (paymentMethodId) {
          returnObject.paymentMethodId = paymentMethodId;
        }

        console.log('returnObject', returnObject)
        return returnObject;
      })
      // Some payment methods require a customer to be on session
      // to complete the payment process. Check the status of the
      // payment intent to handle these actions.
      //.then(handlePaymentThatRequiresCustomerAction)
      .then(handlePaymentThatRequiresCustomerActionWrapper)
      // If attaching this card to a Customer object succeeds,
      // but attempts to charge the customer fail, you
      // get a requires_payment_method error.
      .then(handleRequiresPaymentMethod)
      // No more actions required. Provision your service for the user.
      .then(onSubscriptionComplete)
      .then(saveSuccessPaymentDetails)
      .then(finalizeActivation)
      .catch((error) => {
        // An error has happened. Display the failure to the user here.
        // We utilize the HTML element we created.
        //showCardError(error);
        //console.log(error)
        //console.log(error.message)
        loading(false);
        let message = error.message ? error.message : error.error ? error.error : 'Error, try again with another card'
        showError(message);
      })
  );
}


function handlePaymentThatRequiresCustomerActionWrapper({
  subscription,
  invoice,
  priceId,
  paymentMethodId,
  isRetry,
}) {
  if (paymentMethodId) {
    return handlePaymentThatRequiresCustomerActionWithPaymentMethodId({
      subscription,
      invoice,
      priceId,
      paymentMethodId,
      isRetry,
    });
  } else {
    return handlePaymentThatRequiresCustomerActionWithoutPaymentMethodId({
      subscription,
      priceId,
      invoice,
      isRetry,
    });
  }
}

function handlePaymentThatRequiresCustomerActionWithPaymentMethodId({
  subscription,
  invoice,
  priceId,
  paymentMethodId,
  isRetry,
}) {

  //console.log('subscription', subscription)
  if (subscription.data && subscription.data.status === 'active') {
    // Subscription is active, no customer actions required.
    return { 
      subscription: subscription.data, 
      priceId, 
      paymentMethodId };
  }

  let paymentIntent = invoice ? invoice.payment_intent : subscription.data.latest_invoice.payment_intent;

  if (
    paymentIntent.status === 'requires_action' ||
    (isRetry === true && paymentIntent.status === 'requires_payment_method')
  ) {
    return stripe
      .confirmCardPayment(paymentIntent.client_secret, {
        payment_method: paymentMethodId,
      })
      .then((result) => {
        if (result.error) {
          throw result.error;
        } else {
          if (result.paymentIntent.status === 'succeeded') {
            subscription.data.status = 'active';
            return {
              priceId: priceId,
              subscription: subscription.data,
              invoice: invoice,
              paymentMethodId: paymentMethodId,
            };
          }
        }
      })
      .catch((error) => {
        throw error;
      });
  } else {
    return { subscription: subscription.data, priceId, paymentMethodId };
  }
}

function handlePaymentThatRequiresCustomerActionWithoutPaymentMethodId({
  subscription,
  priceId,
  invoice,
  isRetry,
}) {
  console.log('subscription', subscription)
  if (subscription.data && subscription.data.status === 'active') {

 

    return { 
      priceId: priceId,
      subscription: subscription.data,
    };
  }

  let paymentIntent = subscription.data.latest_invoice.payment_intent;


  console.log('paymentIntent.status', paymentIntent.status)
  if (
    paymentIntent.status === 'requires_action' ||
    (isRetry === true && paymentIntent.status === 'requires_payment_method')
  ) {
    return stripe.confirmCardPayment(paymentIntent.client_secret)
      .then((result) => {
        if (result.error) {
          throw result.error;
        } else {
          if (result.paymentIntent.status === 'succeeded') {
            subscription.data.status = 'active';
            return {
              priceId: priceId,
              subscription: subscription.data,
              invoice: invoice,
            };
          }
        }
      })
      .catch((error) => {
        throw error;
      });
  } else if (paymentIntent.status === 'requires_confirmation') {
   
    console.log('paymentIntent', paymentIntent)
   
    return stripe.confirmAuBecsDebitPayment(paymentIntent.client_secret, {
      payment_method: paymentIntent.payment_method
    }).then((result) => {
      if (result.error) {
        console.log(result.error.message);
        throw result.error;
      } else {
        if (result.paymentIntent && result.paymentIntent.status === 'processing') {
          console.log('result2', result)
          subscription.data.status = 'active';
          return {
            priceId: priceId,
            subscription: subscription.data,
            invoice: invoice,
          };
        }
      }
    }).catch((error) => {
      throw error;
    });
  } else {
    return { subscription: subscription.data, priceId };
  }
}

function handleRequiresPaymentMethod({
  subscription,
  paymentMethodId,
  priceId,
}) {
   console.log('here2')
   console.log(subscription)
  if (subscription.status === 'active') {
    // subscription is active, no customer actions required.
    return { subscription, priceId, paymentMethodId };
  } else if (
    subscription.latest_invoice.payment_intent.status ===
    'requires_payment_method'
  ) {
    // Using localStorage to manage the state of the retry here,
    // feel free to replace with what you prefer.
    // Store the latest invoice ID and status.
    localStorage.setItem('latestInvoiceId', subscription.latest_invoice.id);
    localStorage.setItem(
      'latestInvoicePaymentIntentStatus',
      subscription.latest_invoice.payment_intent.status
    );
    throw { message: 'Your card was declined.' };
  } else {
    //console.log('here3')
    return { subscription, priceId, paymentMethodId };
  }
}


function onSubscriptionComplete(result) {
  // Payment was successful.
  if (result.subscription.status === 'active') {
    // Change your UI to show a success message to your customer.
    // Call your backend to grant access to your service based on
    // `result.subscription.items.data[0].price.product` the customer subscribed to.

    console.log('success')
    loading(false);
    $('#modalStripePayment').modal('hide');
    $('#modalStripePaymentBSB').modal('hide');
    USER_DATA.stripePyment = {
      subscriptionId: result.subscription.id,
      currentPeriodEnd: result.subscription.current_period_end,
      customer: result.subscription.customer,
      priceItemId: result.subscription.items.data[0].price.id,
    }
    if (result.subscription.latest_invoice && result.subscription.latest_invoice.hosted_invoice_url) {
      window.open(result.subscription.latest_invoice.hosted_invoice_url, '_blank');
    }
    return USER_DATA
  }
}

function saveSuccessPaymentDetails(userData) {
  return (
    fetch('php/save_success_payment.php', {
      method: 'post',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(userData),
    })
      .then((response) => {
        return response.json();
      })
      .then((result) => {
        userData.stripePyment.savedStripeDetailsId = result.id
        return userData
      })
      .catch((error) => {
        console.log(error)
        throw error;
      })
  )
}


function newEmail(account) {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: "https://newapi.quiktrak.co/Quiktrak/V2/Customer/GetList?MajorToken=00000000-0000-0000-0000-000000000000&MinorToken=00000000-0000-0000-0000-000000000000&rows=1&page=1&sort=Name&order=asc&LoginName=" + account,
    //data: data,
    success: function (result) {
      if (result) {

        if (JSON.parse(result)?.rows?.length) {
          //console.log(JSON.parse(result).rows[0])
          let checkArr = JSON.parse(result).rows.filter(el => el.Email == account || el.LoginName == account)

          if (checkArr.length) {
            console.log(checkArr[0].Email)
            $('[name="email"]').val(checkArr[0].Email);
            $('[name="firstName"]').val(checkArr[0].Name);
            $('[name="subName"]').val('');
          } else {
            //$('.info').html('<div class="errors">Current account has no email address</div>');
          }
        }
      }

    },
    complete: function () {

    },
    dataType: "html"
  });
}


function finalizeActivation(userData) {
  /*console.log(userData)
  console.log('SUCCESS, finalizing activation')
  var letter = `letter/witi/live/?ac=${ userData.account }&at=${ userData.assetType }&st=${ userData.solution }&sp=${ userData.servicePlan }`;
  if (letter) {
    window.open(letter,'_blank');
  }
  return ;*/

  if (userData.paymentType == 'Credit Card (Stripe API)') {
    userData.localRenewal = 1
  }

  let $this = $('[name="activation"]');
  let activateUrl = 'php/save_in_db_r.php';

  if ($this.hasClass('form-activate')) {
    activateUrl = 'php/save_in_db_a.php';
  } else if ($this.hasClass('form-reactivate')) {
    activateUrl = 'php/save_in_db_ra.php';
  } else if ($this.hasClass('form-replace')) {
    activateUrl = 'php/save_in_db_replace.php';
  } else if ($this.hasClass('form-upgrade')) {
    activateUrl = 'php/save_in_db_u2l.php';
  }

  $.ajax({
    type: "POST",
    url: activateUrl,
    dataType: 'json',
    data: userData,
    async: true,
    cache: false,
    beforeSend: function () {
      isFormLoading = true;
      $('.form_submit').toggleClass('disabled');
      $('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
      preloader.on();
    },
    success: function (data) {
      isFormLoading = false;
      $('.form_submit').toggleClass('disabled');
      $('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
      preloader.off();

      //console.log(data);
      var replyCode = data.replyCode;
      var respondMsg = data.msg;

      sendLog({ Code: replyCode, Msg: respondMsg + ' - ' + activateUrl })
      switch (replyCode) {
        case '9999': case '1005': case '1004': case '1002': case '1000':
          Swal.fire({
            icon: 'error',
            title: '',
            text: respondMsg,
            confirmButtonColor: '#e9142b',
            footer: '<a href="https://support.quiktrak.au/?s=32">Contact support</a>'
          })
          $('.info').html('<div class="errors">' + respondMsg + '</div>');
          break;

        case '000':
          $('.clearAfter').val('');
          /*$('.device_count').empty();*/


          $('.info').html('<div class="success">' + respondMsg + '</div>');
          let isIridiumConnected = $('[name="isDeviceIridiumConnected"]:checked').val();
          console.log('isIridiumConnected', isIridiumConnected)
          if (isIridiumConnected === 'yes') {
            sendReqLog({ Code: replyCode, Msg: userData?.imei2 })
          }

          var letter = data.letter;
          if (letter) {
            //window.open(letter,'_blank');

            /*var letterFrame = '<iframe src="'+letter+'" onload="resizeIframe(this)" style="width: 100%;"></iframe>';
            $('#modalLetter').modal('show');
            $('#modalLetter .modal-content').html(letterFrame);*/
          }
          break;
        default:
          $('.info').html('<div class="processing">Your request is being processed in the background at the moment. Please wait 15 minutes and check your asset, if it is still not processed, please try again...</div>');
      }

    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      console.log(XMLHttpRequest);
      console.log(textStatus);
      console.log(errorThrown);
      $('.form_submit').toggleClass('disabled');
      $('.form_submit .submit_text, .form_submit .preloader').toggleClass('vis_hidden');
      $('.info').html('<div class="processing">Your request is being processed in the background at the moment. Please wait 15 minutes and check your asset, if it is still not processed, please try again</div>');
      isFormLoading = false;
      preloader.off();
    }
  });
}

// Show the customer the error from Stripe if their card fails to charge
var showError = function (errorMsgText) {
  loading(false);
  var errorMsg = document.querySelector("#card-error");
  errorMsg.textContent = errorMsgText;
  setTimeout(function () {
    errorMsg.textContent = "";
  }, 5000);
};
// Show a spinner on payment submission
var loading = function (isLoading) {
  if (isLoading) {
    // Disable the button and show a spinner
    document.querySelector("#submit").disabled = true;
    document.querySelector("#spinner").classList.remove("hidden");
    document.querySelector("#button-text").classList.add("hidden");
  } else {
    document.querySelector("#submit").disabled = false;
    document.querySelector("#spinner").classList.add("hidden");
    document.querySelector("#button-text").classList.remove("hidden");
  }
};