/* URL */
document.querySelectorAll('.url').forEach((url) => {
  url.value = window.location.href;
});

/* Password */
function generatePassword() {
  var length = 8,
    charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
    retVal = '';
  for (var i = 0, n = charset.length; i < length; ++i) {
    retVal += charset.charAt(Math.floor(Math.random() * n));
  }
  return retVal;
}
document.querySelectorAll('.password').forEach((password) => {
  password.value = generatePassword();
});

/* URL */
function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

/* Sesion User ID*/
function generate() {
  var chars = '123456789';

  var string_length = 7;
  var randomstring = '';
  for (var i = 0; i < string_length; i++) {
    var rnum = Math.floor(Math.random() * chars.length);
    randomstring += chars.substring(rnum, rnum + 1);
  }

  return randomstring + Math.floor(Math.random() * chars.length);
}

let st = localStorage.getItem('status');
let usid = localStorage.getItem('userid');
let id = st === 'lead' ? usid : generate();
let statusall = st === 'lead' ? st : 'guest';
let userid = {
  userid: id,
  status: statusall,
};
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ userId: userid });

/* Form sendiong*/
var formConf = {
  postback: true,
  postbackURL: 'example',
  redirectURL: './pages/thanks.php',
};
jQuery(document).ready(function () {
  var country = null;
  var ip = null;
  var city = null;
  document.querySelectorAll('.formbox').forEach((formbox) => {
    /* Tel */
    var iti = intlTelInput(document.querySelector(`#${formbox.getAttribute('id')} .phone`), {
      hiddenInput: 'fulltel',
      nationalMode: true,
      initialCountry: 'auto',
      geoIpLookup: function (success, failure) {
        jQuery
          .get(
            'https://api.ipdata.co/?api-key=2f6d239ceda281f702f4a2cd5c1f451658642e83d55983b369e65973',
            function () {},
            'jsonp',
          )
          .always(function (resp) {
            var countryCode = resp && resp.country_code ? resp.country_code : '';
            country = resp && resp.country_code ? resp.country_code : '';
            ip = resp && resp.ip ? resp.ip : '';
            city = resp && resp.city ? resp.city : '';
            jQuery(`#${formbox.getAttribute('id')} .ctry`).val(country);
            success(countryCode);
            jQuery(`#${formbox.getAttribute('id')} #ctrlist select`).val(resp.country_code);
          });
      },
    });
    formbox.addEventListener('submit', function (e) {
      e.preventDefault();

      let submitBtn = document.querySelector(`#${formbox.getAttribute('id')} input[type=submit]`);
      submitBtn.style.pointerEvents = 'none';
      submitBtn.style.opacity = '0.1';

      document.querySelector(`#${formbox.getAttribute('id')} .loadingView`).style.display = 'block';
      if (!document.querySelector(`#${formbox.getAttribute('id')} .check`).checked) {
        submitBtn.style.pointerEvents = 'all';
        submitBtn.style.opacity = '1';
        document.querySelector(`#${formbox.getAttribute('id')} .loadingView`).style.display =
          'none';
        jQuery(
          `#${formbox.getAttribute('id')} .check,#${formbox.getAttribute('id')} .checklabel`,
        ).addClass('error');
        return false; // don't submit
      }

      var fbclid = getParameterByName('fbclid');
      var clickid = getParameterByName('clickid');
      var site_source_name = getParameterByName('site_source_name');
      var source = getParameterByName('source');
      var placement = getParameterByName('placement');
      var ad_name = getParameterByName('ad_name');

      var ad_id = getParameterByName('ad_id');
      var adset_id = getParameterByName('adset_id');
      var profile = getParameterByName('profile');
      var campaign_id = getParameterByName('campaign_id');

      var device = navigator.userAgent;
      var postback = 0;
      var postbackURL = '';
      if (formConf.postback) {
        postback = 1;
        postbackURL = formConf.postbackURL;
      }
      var full = iti.getNumber();
      jQuery(`#${formbox.getAttribute('id')} .fulltel`).val(full);
      var fnameval = jQuery(`#${formbox.getAttribute('id')} .fname`).val();
      var lnameval = jQuery(`#${formbox.getAttribute('id')} .lname`).val();
      var emailval = jQuery(`#${formbox.getAttribute('id')} .email`).val();
      var phoneval = full;
      var passval = jQuery(`#${formbox.getAttribute('id')} .password`).val();
      var urlval = jQuery(`#${formbox.getAttribute('id')} .url`).val();
      var ctryval = jQuery(`#${formbox.getAttribute('id')} .ctry`).val();
      var data =
        'fname=' +
        fnameval +
        '&lname=' +
        lnameval +
        '&email=' +
        emailval +
        '&phone=' +
        phoneval +
        '&fbclid=' +
        fbclid +
        '&postback=' +
        postback +
        '&postbackurl=' +
        postbackURL +
        '&url=' +
        urlval +
        '&ctry=' +
        ctryval +
        '&city=' +
        city +
        '&ip=' +
        ip +
        '&password=' +
        passval +
        '&site_source_name=' +
        site_source_name +
        '&source=' +
        source +
        '&placement=' +
        placement +
        '&ad_name=' +
        ad_name +
        '&device=' +
        device +
        '&userid=' +
        userid.userid +
        '&clickid=' +
        clickid +
        '&ad_id=' +
        ad_id +
        '&adset_id=' +
        adset_id +
        '&profile=' +
        profile +
        '&campaign_id=' +
        campaign_id;
      jQuery.ajax({
        method: 'POST',
        crossDomain: true,
        url: './api/lead.php',
        data: data,
        cache: false,
        success: function (response) {
          var obj = jQuery.parseJSON(response);
          if (obj.status == 'success') {
            userid.status = 'lead';
            localStorage.setItem('userid', userid.userid);
            localStorage.setItem('status', userid.status);
            document.querySelector(`#${formbox.getAttribute('id')} .loadingView`).style.display =
              'none';
            localStorage.setItem('encodeURL', encodeURI(obj.url));
            window.location.href = formConf.redirectURL;
          } else {
            submitBtn.style.pointerEvents = 'all';
            submitBtn.style.opacity = '1';
            var errordiv = document.querySelector(`#${formbox.getAttribute('id')} .error-msg`);
            errordiv.style.display = 'block';
            if ((errordiv.style.display = 'block')) {
              document.querySelector(`#${formbox.getAttribute('id')} .loadingView`).style.display =
                'none';
            }
            errordiv.innerHTML =
              'La tua registrazione non è riuscita. Assicurati che il tuo indirizzo email e il numero di cellulare siano corretti e riprova!';
            //window.location.href =formConf.redirectURL;
          }
        },
      });
    });
  });
});
