// Comanda
function initOrder(hotel_id, adults, nights, date_arrival, date_departure) {
  return {
    rooms: [],
    adults: adults,
    number_of_nights: nights,
    services: [],
    date_arrival: date_arrival,
    date_departure: date_departure,
    hotel_id: hotel_id,
    checkout_tpv: 0,
  };
}

// Reset other room selects on select rate
// $("select[data-roomid]").on("change", function () {
//   $("select[data-roomid]").not(this).val(0);
// });

function selectRoom(el, next_step = 2) {
  var room_id = $(el).data("roomid");
  var guests = $(el).data("guests");
  var hotel_rate_id = $(el).data("hotelrateid");
  var $rate_data = $('.js-ratedata[data-roomid="' + room_id + '"][data-hotelrateid="'+hotel_rate_id+'"][data-guests="'+guests+'"]');
  var checkout_tpv = 0;

  order.rooms = [];

    var room_name = $rate_data.data("name");
    var price = $rate_data.data("amount");
    var old_price = $rate_data.data("oldprice");
    var meal_plan_id = $rate_data.data("mealplanid");
    var meal_plan_name = $rate_data.data("mealplanname");
    var rate_plan_id = $rate_data.data("rateplanid");
    var rate_plan_name = $rate_data.data("rateplanname");
    var hotel_rate_id = $rate_data.data("hotelrateid");
    var is_petfriendly = $rate_data.data("petfriendly");
    var qty = 1;

      let room = new Room(
        room_id,
        room_name,
        price,
        old_price,
        meal_plan_id,
        meal_plan_name,
        rate_plan_id,
        rate_plan_name,
        hotel_rate_id,
        qty,
      );
      order.rooms.push(room);
      checkout_tpv = $rate_data.data("checkout_tpv");
      order.checkout_tpv = $rate_data.data("checkout_tpv");
      order.adults = guests;

      if (is_petfriendly == 1) {
        $("#services_type_5").show();
      } else {
        $("#services_type_5").hide();

        order.services = order.services.filter((service) => {
          return service.type_id != 5;
        });
      }

    toggleBookingPayment(checkout_tpv);
    updateRoom();
    updateServices();
    updateOrderData();
    updateTotal();

    $(".js-guests-info").text(guests + ' persona' + (guests > 1 ? 's' : ''));

    if (next_step == 3) {
      showStep3();
    } else {
      showStep2();
    }

    showMobileOverview();
}

$(".js-add-service").on("click", function () {
  var service_id = $(this).data("serviceid");
  var service_type_id = $(this).data("servicetypeid");
  var service_name = $(this).data("servicename");
  var service_price = $(this).data("serviceprice");
  var service_qty = $('select[data-serviceid="' + service_id + '"]').val();
  var service_people =
    $('select[data-serviceid="' + service_id + '"][data-people]').val() || 1;
  var duplicate = false;

  if (service_qty == 0 || service_people == 0) {
    alert("Selecciona una cantidad");
    return;
  }

  // Si ja existeix aquest servei.
  $(order.services).each(function (i) {
    if (this.id == service_id) {
      duplicate = true;
    }
  });

  if (duplicate) {
    alert("¡Ya has añadido este servicio!");
    return false;
  }

  if (service_qty > 0) {
    let service = new Service(
      service_id,
      service_type_id,
      service_name,
      service_price,
      service_qty * service_people,
    );
    order.services.push(service);
  }

  updateServices();
  updateOrderData();
  updateTotal();

  if ($("body").hasClass("mobile-detected")) {
    toggleMobileDetail(true);
  }
});

// Elimina servei
$("body").on("click", ".js-del-service", function () {
  var id = $(this).data("id");

  $(order.services).each(function (i) {
    if (this.id == id) {
      order.services.splice(i, 1);
      return false;
    }
  });

  updateServices();
  updateOrderData();
  updateTotal();
});

$(".js-gotostep1").on("click", function () {
  showStep1();
});

$(".js-gotostep2").on("click", function () {
  showStep2();
});

$(".js-gotostep3").on("click", function () {
  showStep3();
});

// Detall checkout mobil
var $body = $("body");
var $co_d_overview = $(".js-checkout-detail-mb");
var $co_d_tgl = $(".js-toggle-checkout-detail-mb");
var $co_d_tgl_img = $(".js-toggle-checkout-detail-mb img");
var $co_d_cnt = $(".js-checkout-detail-mb-content");
var $co_d_ovr = $(".js-checkout-detail-mb-overlay");

$co_d_tgl.on("click", function () {
  toggleMobileDetail();
});

$co_d_ovr.on("click", function () {
  closeMobileDetail();
});

function showMobileOverview() {
  $co_d_overview.addClass("open");
}

function toggleMobileDetail(scrollToEnd = false) {
  $co_d_cnt.slideToggle();
  $co_d_ovr.fadeToggle();
  $co_d_tgl_img.toggleClass("rotate180");
  $body.toggleClass("lock");

  if (scrollToEnd) {
    $co_d_cnt.scrollTop($co_d_cnt[0].scrollHeight);
  }
}

function closeMobileDetail() {
  $co_d_cnt.slideUp();
  $co_d_ovr.fadeOut();
  $co_d_tgl_img.removeClass("rotate180");
  $body.removeClass("lock");
}

function toggleBookingPayment(payment) {
  if (payment == 1) {
    $('[data-payment="0"]').hide();
    $('[data-payment="1"]').show();

    $('[data-payment="0"] input, [data-payment="0"] select')
      .attr("disabled", true)
      .attr("required", false);
    $('[data-payment="1"] input, [data-payment="1"] select')
      .attr("disabled", false)
      .attr("required", true);

    $('[name="tpv_checkout"]').val(1);
  } else {
    $('[data-payment="0"]').show();
    $('[data-payment="1"]').hide();

    $('[data-payment="0"] input, [data-payment="0"] select')
      .attr("disabled", false)
      .attr("required", true);
    $('[data-payment="1"] input, [data-payment="1"] select')
      .attr("disabled", true)
      .attr("required", false);

    $('[name="tpv_checkout"]').val(0);
  }
}

function updateRoom() {
  let price = formatPrice(order.rooms[0].total);
  if (order.rooms[0].old_price != order.rooms[0].total) {
    price = `<s>${formatPrice(order.rooms[0].old_price)}€</s> ${formatPrice(
      order.rooms[0].total,
    )}`;
  }

  var html = `
        <h4>${order.rooms[0].name}</h4>
        <div>${order.rooms[0].meal_plan_name}</div>
        <div>${order.rooms[0].rate_plan_name}</div>
        <div>Habitaciones: ${order.rooms[0].qty}</div>
    `;
    // <div>Precio: ${price}€</div>
  $(".js-room").html(html);
}

function updateServices() {
  var html = "";

  if (order.services.length == 0) {
    html = "Puedes añadir los servicios que quieras al regalo.";
  } else {
    order.services.forEach((service) => {
      html += `
                <div style="margin-bottom: 10px;">
                    <h4>${service.qty} x ${service.name}</h4>
                    <div>Precio: ${formatPrice(service.total)}€</div>
                    <u class='js-del-service' data-id='${
                      service.id
                    }' style='cursor: pointer; font-size: 12px'>Eliminar</u>
                </div>
            `;
    });
  }

  $(".js-services").html(html);
}

function updateOrderData() {
  $('[name="order_data"]').val(JSON.stringify(order));
  // console.log(order)
}

function updateTotal() {
  var total = 0;
  var total_without_discount = 0;
  let text;

  order.rooms.forEach((room) => {
    total += room.total;

    if (room.old_price != room.total) {
      total_without_discount += room.old_price;
    } else {
      total_without_discount += room.total;
    }
  });

  order.services.forEach((service) => {
    total += service.total;
    total_without_discount += service.total;
  });

  text = `${formatPrice(total)}`;

  if (total_without_discount != total) {
    text = `<s style='color: red; margin-left: 2px; margin-right: 6px'>${formatPrice(total_without_discount)}€</s>
        <b>${formatPrice(total)}</b>`;
  }

  $('[name="final_price"]').val(total);

  $(".js-total").html(text);
}

function scrollToSteps() {
  $("html, body").animate({ scrollTop: $("#steps").offset().top - 80 }, 800);
}

function scrollToDates() {
  $("html, body").animate({ scrollTop: $("#dates").offset().top }, 800);
}

function showStep1() {
  $(".js-step-1").fadeIn();
  $(".js-step-2").fadeOut();

  $(".js-gotostep3").hide();

  $(".js-extra").show();

  scrollToSteps();

  updateSteps(1);
}

function showStep2() {
  $(".js-step-1").fadeOut();
  $(".js-step-2").fadeIn();
  $(".js-step-2_1").fadeIn();
  $(".js-step-2_2").fadeOut();
  $(".js-gotostep3").show();

  $(".js-extra").hide();

  initSliders();

  scrollToSteps();

  updateSteps(2);
}

function showStep3() {
  $(".js-step-1").fadeOut();
  $(".js-step-2").fadeIn();
  $(".js-step-2_1").fadeOut();
  $(".js-step-2_2").fadeIn();
  $(".js-gotostep3").hide();

  $(".js-extra").hide();

  scrollToSteps();

  updateSteps(3);
}

function updateSteps(id) {
  $(".js-tab-step").removeClass("steps__step--current");
  $(".js-tab-step").addClass("hidden-xs");

  $('.js-tab-step[data-step="' + id + '"]').addClass("steps__step--current");
  $('.js-tab-step[data-step="' + id + '"]').removeClass("hidden-xs");
}

function Room(
  id,
  name,
  price,
  old_price,
  meal_plan_id,
  meal_plan_name,
  rate_plan_id,
  rate_plan_name,
  hotel_rate_id,
  qty,
) {
  (this.id = id),
    (this.name = name),
    (this.price = price),
    (this.old_price = old_price),
    (this.meal_plan_id = meal_plan_id),
    (this.meal_plan_name = meal_plan_name),
    (this.rate_plan_id = rate_plan_id),
    (this.rate_plan_name = rate_plan_name),
    (this.hotel_rate_id = hotel_rate_id),
    (this.qty = qty),
    (this.total = price * qty);
}

function Service(id, type_id, name, price, qty) {
  (this.id = id),
    (this.type_id = type_id),
    (this.name = name),
    (this.price = price),
    (this.qty = qty),
    (this.total = price * qty);
}

function initSliders() {
  $(".rsSlider").royalSlider({
    controlNavigation: false,
    autoScaleSlider: true,
    autoScaleSliderHeight: 550,
    // imageScaleMode: 'fill',
    imgWidth: "100%",
    usePreloader: true,
    numImagesToPreload: 1,
  });
}

function valid_credit_card(value) {
  // Accept only digits, dashes or spaces
  if (/[^0-9-\s]+/.test(value)) return false;

  // The Luhn Algorithm. It's so pretty.
  let nCheck = 0;
  value = value.replace(/\D/g, "");

  for (let n = 0; n < value.length; n++) {
    let nDigit = parseInt(value[n], 10);

    if (!(n % 2) && (nDigit *= 2) > 9) nDigit -= 9;

    nCheck += nDigit;
  }

  return nCheck % 10 === 0;
}

function formatPrice(price) {
  if (price % 1 === 0) {
    return new Intl.NumberFormat("es-ES", {
      useGrouping: "always",
      style: "decimal",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(price);
  }

  return new Intl.NumberFormat("es-ES", {
    useGrouping: "always",
    style: "decimal",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(price);
}
