$(document).ready(function () {
  const Toast = Swal.mixin({
    toast: true,
    position: "top-end",
    showConfirmButton: false,
    timer: 3000,
  });

  var store_c = $("#idBoutique").val();
  var ProductList = [];
  var url = $("#url_connection").val();

  var customerRecords;

  $.ajax({
    url: url,
    type: "POST",
    data: {'action' : 'filterPointsPerPurchase'},
    dataType: "json",
    success: function (response)
    {
      ProductList = response.records.filter(product => product.store_c == store_c);
      for (let i = 0; i < ProductList.length; i++) {
        $("#purchasedProduct_c0").append('<option value="'+ProductList[i].id+'">'+ProductList[i].name+'</option>');
      }
    }
  });

    /* Birthday */

    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "June",
        "July", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
    let qntYears = 80;
    let selectYear = $("#year");
    let selectMonth = $("#month");
    let selectDay = $("#day");
    let currentYear = new Date().getFullYear() - parseInt(18);

    for (var y = 0; y < qntYears; y++) {
        let date = new Date(currentYear);
        let yearElem = document.createElement("option");
        yearElem.value = currentYear
        yearElem.textContent = currentYear;
        selectYear.append(yearElem);
        currentYear--;
    }

    for (var m = 0; m < 12; m++) {
        let month = monthNames[m];
        let monthElem = document.createElement("option");
        monthElem.value = m;
        monthElem.textContent = month;
        selectMonth.append(monthElem);
    }

    var d = new Date();
    var month = d.getMonth();
    var year = d.getFullYear();
    var day = d.getDate();

    selectYear.on("change", AdjustDays);
    selectMonth.on("change", AdjustDays);
    selectDay.on("change", SetBirthday);

    if ($("#birthday").val()=="") {
        selectYear.val(year);        
        selectMonth.val(month);
        AdjustDays();
        selectDay.val(day);
    }

    function AdjustDays() {
        
        var year = selectYear.val();
        var month = parseInt(selectMonth.val()) + 1;
        selectDay.empty();

        //get the last day, so the number of days in that month
        var days = new Date(year, month, 0).getDate();

        //lets create the days of that month
        for (var d = 1; d <= days; d++) {
            var dayElem = document.createElement("option");
            dayElem.value = d;
            dayElem.textContent = d;
            selectDay.append(dayElem);
        }
    }

    function SetBirthday() {
        var bd = selectYear.val() + '-' + ('0' + (parseInt(selectMonth.val()) + 1)).slice(-2) + '-' + ('0' + selectDay.val()).slice(-2);
        $("#birthday").val(bd);
    }

    /** */

    var now = new Date();
  $('#transaction_date_c').val(now.getFullYear()
        + "-" + (("0" + (now.getMonth() + 1)).slice(-2))
      + "-" + (("0" + now.getDate()).slice(-2)));

    $("#purchasedProduct_c0").on("change", function () {
        if ($("#ticket").val() == null || $("#ticket").val().length <= 0) {
            $("#ticket").val($("#purchasedProduct_c0").attr('name'));
        }
  });
    
  $('input[name="vipCode"]').hide();

  //show it when the checkbox is clicked
  $('input[name="isVIP"]').on("click", function () {
    if ($(this).prop("checked")) {
      $('input[name="vipCode"]').show();
    } else {
      $('input[name="vipCode"]').hide();
      $('input[name="vipCode"]').val("");
    }
  });


  //logic to add/remove new product fields
  var next = 0;
  $(document).on('click', '#add-more', function(e) {
    e.preventDefault();
    var addto = "#field" + next;
    next = next + 1;
    var newIn =
      '<div class="row" id="field'+next+'" name="field'+next+'">'+
      '<!-- Text input--><!-- Product -->'+
          '<div class="col-md-6">'+
              '<div class="form-group">'+
                  '<label for="purchasedProduct_c">Product</label>'+
                  '<select class="form-control productControl product-select" id="purchasedProduct_c'+next +'" name="productID'+next+'">'+
                      '<option></option>';
    for (var i = 0; i < ProductList.length; i++) {
      newIn +=        '<option value="'+ProductList[i].id+'">'+ProductList[i].name+'</option>';
    }
    newIn +=      '</select>'+
              '</div>'+
          '</div>'+
        '<!-- Date -->'+
        '<div class="col-md-6">'+
            '<div class="form-group">'+
                '<label for="productQuantity">Product Quantity</label>'+
                '<input type="number" min="1" max="100" class="form-control productControl product-quantity" id="productQuantity'+next +'" name="productQuantity'+next+'">'+
            '</div>'+
        '</div>'+
        '<div class="col-12 text-right mb-3">'+
          '<a id="remove-prod" name="remove-prod" class="btn btn-danger remove-prod pull-right"><i class="fas fa-trash"></i></a>'+
        '</div>'+
        '<p class="d-none">Amount: <span class="prod-amount">0</span>';

    var newInput = $(newIn);
  
    $("#field0").after(newInput);
    $("#field" + next).attr("data-source", $(addto).attr("data-source"));
  });

  $(document).on('click', '.remove-prod', function() {
    var index = $(this).closest('.row').attr('id');
    $('#'+index).remove();

    //$(this).closest('.row').remove();

    calculateTotal();
  });

  //calculate the purchase total amount
  $('#purchaseInfo').on('change', '.product-quantity, .product-select', function() {
    $(this).closest('.row').each(function() {
      var prod = $(this).find('.product-select', this).val();
      var prodQuan = parseFloat($(this).find('.product-quantity', this).val());

      var prodValue = ProductList.find(x => x.id === prod).unit_price_c;
  
      if (typeof prodQuan === 'number' && prodQuan && prodQuan != 0) {
        var calculatedValue = prodQuan * prodValue;
        calculatedValue = Math.round(calculatedValue * 100) / 100;
        $(this).find('.prod-amount').text(calculatedValue);
      } else {
        $(this).find('.prod-amount').text(0);
      }
    });

    calculateTotal();
  });

  function calculateTotal() {
    var grandTotal = 0;
     $(".prod-amount").each(function (index, element) {
          
          var prodValue = $(this).text();
          grandTotal += parseFloat(prodValue);
          $(".purchase-total").val(grandTotal)
  
      });
  }

  var input = document.querySelector("#phonenumber");

  var iti = window.intlTelInput(input, {
    //initialCountry: "auto",
    autoPlaceholder: "off",
    /*geoIpLookup: function (callback) {
      $.get("https://ipinfo.io", function () {}, "jsonp").always(function (
        resp
      ) {
        var countryCode = resp && resp.country ? resp.country : "";
        callback(countryCode);
      });
    }, auto-geolocalización*/
    utilsScript: "../plugins/intl-tel-input-17.0.0/build/js/utils.js",
  });

  // set placeholder
  /*var pattern = '999 999 9999';
  $("#phonenumber").attr("placeholder", pattern.replace(/(\d+)/gm, " "));*/

  //on change
  $("#phonenumber").on("countrychange", function (e, countryData) {
    $("#phonenumber").val("");
    $("#country").val("");
   // $("#phonenumber").attr("placeholder", pattern.replace(/(\d+)/gm, " "));
    var countryData = iti.getSelectedCountryData().name;
    var country = countryData.split("(");
    $("#country").val(country[0]);
  });

  $("#div-clientInformation").hide();
  $("#div-AdditionInformacion").hide();

  function updateLead() {
    var url = $("#url_connection").val();

    var recordId = $("#idSugarClient").val();
    var boutique_c = $("#boutique_c").val();
    var refered_by = $("#refered_by").val();
    var first_name = $("#firstname").val();
    var last_name = $("#lastname").val();
    var phonenumber = iti.getNumber(intlTelInputUtils.numberFormat.E164);
    var country = $("#country").val();
    var city = $("#city").val();
    var zippostalcode = $("#zippostalcode").val();
    var genero_c = $("#genero_c").val();
    var sendinforadios = $("input:radio[name='sendinfooptions']:checked").val();
    var birthday = $("#birthday").val();
    var consumption_ocassion_c = $("#consumption_ocassion_c").val();
    var visit_frecuency_c = $("#visit_frecuency_c").val();
    var favoritehotel_c = $("#favoritehotel_c").val();
    var usa_shopping_place_c = $("#usa_shopping_place_c").val();
    var favoritecamark_c = $("#favoritecamark_c").val();
    var buyonline = $("input:radio[name='buyonlineoptions']:checked").val();
    var experience = $("input:radio[name='experienceoptions']:checked").val();
    var agerange_c = $("#agerange").val().replace(/\s/g, "").replace("-", "");
    var email = $("#email").val();

    var contact_source_c = $("#contact_source_c").val();
    var ticket = $("#ticket").val();
    var transaction_date_c = $("#transaction_date_c").val();
    var total = parseInt($("#total").val());
    var comments = $("#comments").val();
    var productControl  = $(".productControl").serializeArray();
    var ProductsBought = [];
    var prod_id;
    var prod_qty;

    for (var index = 0; (index * 2) < productControl.length; index++)
    {
      prod_id   = productControl[(index * 2)].value
      prod_qty = productControl[(index * 2) + 1].value

      if (prod_id !== "") {
        ProductsBought[index] = {
          ProductId : prod_id,
          quantity : prod_qty,
          unit_price_c: ProductList.find(x => x.id === prod_id).unit_price_c,
        }
      }
      
    }

    var casUltraVipCode = $("#vipCode").val();
    var isCasUltraVip = "false";
    if (casUltraVipCode === "casultravip") {
      isCasUltraVip = "true";
    }
    else {
      isCasUltraVip = "false";
    }


    var jsonData = {
      action: "updateItem",
      module: "Leads",
      recordId: recordId,
      first_name: first_name,
      last_name: last_name,
      phone_mobile: phonenumber,
      primary_address_country: country,
      primary_address_city: city,
      primary_address_postalcode: zippostalcode,
      email_opt_in: sendinforadios,
      genero_c: genero_c,
      birthday: birthday,
      consumption_ocassion_c: consumption_ocassion_c,
      visit_frecuency_c: visit_frecuency_c,
      favoritehotel_c: favoritehotel_c,
      usa_shopping_place_c: usa_shopping_place_c,
      favoritecamark_c: favoritecamark_c,
      buyonline: buyonline,
      experience: experience,
      refered_by: refered_by,
      email: email,
      boutique_c: boutique_c,
      agerange_c: agerange_c,
      contact_source_c: contact_source_c,
      ticket: ticket,
      transaction_date_c: transaction_date_c,
      total: total,
      comments: comments,
      ProductsBought: ProductsBought,
      isCasUltraVip: isCasUltraVip,
      store_c: store_c
    };

     $.ajax({
          url: url,
          type: "POST",
          data: jsonData,
          dataType: "json",
          success: function (json) {
          },
      })
     .done(
            Toast.fire({
                icon: "info",
                title: "Updated successfully.",
            })
      )
      .done(            
        setTimeout(function () {
          location.href = location.href;
        }, 4000)
      );
  }

  function newContact() {
    $("#div-updateContact").hide();
    $("#div-clientInformation").show();
    $("#div-AdditionInformacion").hide();
    $("#div-newContact").show();

    $("#idSugarClient").val("");
    $("#firstname").val("");
    $("#lastname").val("");
    $("#phonenumber").val("");
    $("#country").val("");
    $("#zippostalcode").val("");

    Toast.fire({
      icon: "info",
      title: "New contact",
    });
  }

  function findbyEmail() {
    var url = $("#url_connection").val();
    var email = $("#email").val();

    $.ajax({
      url: url,
      type: "POST",
      data: {
        action: "filterItem",
        module: "Leads",
        email: email,
      },
      dataType: "json",
      success: function (json) {
        if (json.records.length > 0) {

          setValues(json.records[0])

        } else {
          newContact();
        }
      },
    });
  }

  function findbyName() {
    var url = $("#url_connection").val();
    var name = $("#name").val();

    $.ajax({
        url: url,
        type: "POST",
        data: {
          action: "filterItem",
          module: "Leads",
          name: name,
        },
        dataType: "json",
        beforeSend: function() {
          $("#loader-wrapper").show();
        },success: function (json) {
          if (json.records.length > 0) {
            customerRecords = json.records;

            if (json.records.length === 1) {
              document.getElementById("customersTable").innerHTML = "";

              setValues(json.records[0]);
            } else {
              //Show List Table
              document.getElementById("customersTable").innerHTML = "";

              $("#customersTable").append(
                '<thead><tr>' +
                '  <th style="display: none">id</th>' +
                '  <th>Full Name</th>' +
                '  <th style="display: none">Country</th>' +
                '  <th>Phone</th>' +
                '  <th>Email</th>' +
                '</tr></thead><tbody></tbody>');

              customerRecords.forEach(customer => {
                var mail = customer["email"].length > 0 ? customer["email"][0]["email_address"] : '';

                $("#customersTable tbody").append(
                  '<tr>' +
                  '  <td style="display: none">' + customer["id"] + '</td>' +
                  '  <td>' + customer["first_name"] + ' ' + customer["last_name"] + '</td>' +
                  '  <td style="display: none">' + customer["primary_address_country"] + '</td>' +
                  '  <td>' + customer["phone_mobile"] + '</td>' +
                  '  <td>'+ mail + '</td>' +
                  '</tr>')
              });

              setTableAction();
            }
          } else {
            newContact();
          }
        }
      }
    );
  }

  function setTableAction() {
    $("#customersTable tr").click(function () {
      var idCustomer = $(this).find('td:first').html();

      if (idCustomer !== undefined) {
        var customer = customerRecords.find(element => element.id === idCustomer);
        setValues(customer);
      }

    });
  }

  function clearValues() {
    $("#phonenumber").val("");

    $("#email").val("");

    $("#div-newContact").hide();

    $("#idSugarClient").val("");
    $("#firstname").val("");
    $("#lastname").val("");
    $("#country").val("");
    $("#city").val("");

    $("#sendinforadios").prop('selectedIndex',0);
    $("#zippostalcode").val("");

    $("#genero_c").prop('selectedIndex',0);
    $("#agerange").prop('selectedIndex',0);

    $("#birthday").val("");

    $("#consumption_ocassion_c").val("");
    $("#favoritehotel_c").prop('selectedIndex',0);
    $("#visit_frecuency_c").prop('selectedIndex',0);
    $("#usa_shopping_place_c").val("");
    $("#favoritecamark_c").prop('selectedIndex',0);

    $("#buyonlineoptions").attr('checked',false);

    $("#experienceoptions").attr('checked',false);
    $("#boutique_c").prop('selectedIndex',0);
  }

  function setValues(customerData){

    clearValues();
    //iti.setNumber("+19255673517"); // USA
    iti.setNumber(customerData["phone_mobile"]); // USA
    $("#phonenumber").val(intlTelInputUtils.formatNumber(customerData["phone_mobile"], null, intlTelInputUtils.numberFormat.INTERNATIONAL)); // USA

    $("#div-newContact").hide();
    $("#div-updateContact").show();
    $("#div-AdditionInformacion").show();

    $("#idSugarClient").val(customerData["id"]);
    $("#firstname").val(customerData["first_name"]);
    $("#lastname").val(customerData["last_name"]);
    $("#country").val(customerData["primary_address_country"]);
    $("#city").val(customerData["primary_address_city"]);

    $("#sendinforadios").prop('checked', customerData["email_opt_in"]);
    $("#zippostalcode").val(customerData["primary_address_postalcode"]);
    $('#genero_c option[value="' + customerData["genero_c"] + '"]' ).attr("selected", "selected");
    $('#agerange option[value="' + customerData["agerange_c"] + '"]').attr("selected", "selected");
    if (customerData["birthdate"].length > 1) {
      $("#birthday").val(customerData["birthdate"]);
      var birthday = new Date(customerData["birthdate"]);
      selectYear.val(birthday.getUTCFullYear());
      selectMonth.val(birthday.getUTCMonth());
      AdjustDays();
      selectDay.val(birthday.getUTCDate());
    }
    $("#consumption_ocassion_c").val(customerData["consumption_ocassion_c"]);
    $('#favoritehotel_c option[value="' + customerData["favoritehotel_c"] + '"]').attr("selected", "selected");
    $('#visit_frecuency_c option[value="' + customerData["visit_frecuency_c"] + '"]').attr("selected", "selected");
    $("#usa_shopping_place_c").val(customerData["usa_shopping_place_c"]);
    $('#favoritecamark_c option[value="' + customerData["favoritecamark_c"] +'"]').attr("selected", "selected");
    customerData["interested_to_buy_online_c"].length > 1
      ? $(
        "input[name=buyonlineoptions][value=" +
        customerData["interested_to_buy_online_c"] +
        "]"
      ).attr("checked", "checked")
      : "";
    customerData["interested_in_experiences_c"].length > 1
      ? $(
        "input[name=experienceoptions][value=" +
        customerData["interested_in_experiences_c"] +
        "]"
      ).attr("checked", "checked")
      : "";
    $('#boutique_c option[value="' + customerData["boutique_c"] + '"]').attr("selected", "selected");

    $("#div-clientInformation").show();
    $("#div-AdditionInformacion").show();

    if (customerData["email"].length > 0){
      $("#email").val(customerData["email"][0]["email_address"]   ?? "");
      var optIn = customerData["email"][0]['opt_out'] === true ? "off" : "on";
      $("input[name=sendinfooptions][value='"+optIn+"']").attr("checked","checked");
    }
  }




  function insertLead() {
    var url = $("#url_connection").val();

    var first_name = $("#firstname").val();
    var last_name = $("#lastname").val();
    var phonenumber = iti.getNumber(intlTelInputUtils.numberFormat.E164);
    var country = $("#country").val();
    var city = $("#city").val();
    var zippostalcode = $("#zippostalcode").val();
    var genero_c = $("#genero_c").val();
    var agerange_c = $("#agerange").val().replace(/\s/g, "").replace("-", "");
    var sendinforadios = $("input:radio[name='sendinfooptions']:checked").val();
    var idBoutique = $("#idBoutique").val();
    var refered_by = $("#refered_by").val();
    var email = $("#email").val();

    $.ajax({
      url: url,
      type: "POST",
      data: {
        action: "insertItem",
        module: "Leads",
        first_name: first_name,
        last_name: last_name,
        phone_mobile: phonenumber,
        primary_address_country: country,
        primary_address_city: city,
        primary_address_postalcode: zippostalcode,
        email_opt_in: sendinforadios,
        genero: genero_c,
        agerange: agerange_c,
        refered_by: refered_by,
        boutique_c: idBoutique,
        email: email,
      },
      dataType: "json",
      success: function (json) {
        $("#idSugarClient").attr("value", json.id);
      },
    })
      .done(
        Toast.fire({
          icon: "info",
          title: "New lead created successfully.",
        })
      )
      .done(updateForm());
  }

  function updateForm() {
    $("#div-newContact").hide();
    $("#div-updateContact").show();
    $("#div-AdditionInformacion").show();
  }

  function validaForm() {
    if ($("#email").val() == "") {
      $("#email").focus();
      return false;
    }
    if ($("#firstname").val() == "") {
      $("#firstname").focus();
      return false;
    }
    if ($("#lastname").val() == "") {
      $("#lastname").focus();
      return false;
    }
    if ($("#country").val() == "") {
      $("#country").focus();
      return false;
    }

    return true;
  }
          
  $('[type="checkbox"][name="seeds"]').change(function(){
  $('select.selectDrop').toggle(this.checked);
  });

  function getYear() {
    var now = new Date();
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);

    var agerange = $("#agerange").val();
    var year = (
      now.getFullYear() - parseInt(agerange.substring(0, 2))
    ).toString();
    var dateBirth = year + "-" + month + "-" + day;
    $("#birthday").val(dateBirth);
  }

  $("#search-btn").on("click", function () {
    findbyName();
    //findbyEmail();
  });

  $("#updateContact").on("click", function () {
    if (validaForm()) {
      updateLead();
    }
  });

  $("#btn-newContact").on("click", function () {
    if (validaForm()) {
      insertLead();
    }
  });

  var coll = document.getElementsByClassName("collapsible");
  var i;

  for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
      this.classList.toggle("active");
      var content = this.nextElementSibling;
      if (content.style.display === "block") {
        content.style.display = "none";
      } else {
        content.style.display = "block";
      }
    });
  }

});

