$(() => {
  $("#anio_select").select2({
    placeholder: "Seleccione un año",
    allowClear: true,
    theme: "bootstrap",
    width: "100%",
  });

  $("#mes_select").select2({
    placeholder: "Seleccione un mes",
    allowClear: true,
    theme: "bootstrap",
    width: "100%",
  });

  $("#dia_select").select2({
    placeholder: "Seleccione un dia",
    allowClear: true,
    theme: "bootstrap",
    width: "100%",
  });

  $("#empleado_select, #user_select").select2({
    placeholder: "Seleccione un empleado",
    allowClear: true,
    theme: "bootstrap",
    width: "100%",
    ajax: {
      url: "../../controller/biometrico.php?op=select_bio",
      dataType: "json",
      delay: 250,
      data: function (params) {
        return {
          searchTerm: params.term,
        };
      },
      processResults: function (response) {
        return {
          results: response,
        };
      },
    },
    minimumInputLength: 2,
  });

  $("#data-biometric").DataTable({
    ajax: {
      url: "../../controller/biometrico.php?op=filter&fil=all&anio=&mes=&dia=&usuario=",
      type: "GET",
    },
    columns: [
      { data: "fecha_registro" },
      { data: "nombre" },
      { data: "hora_registro" },
      { data: "estado" },
      { data: "observacion" },
      { data: "tipo_registro" },
      { data: "acciones" },
    ],
    fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
      var tipo_registro = aData.tipo_registro.replace("_", " ");

      tipo_registro = tipo_registro
        .toLowerCase()
        .replace(/\b[a-z]/g, function (letter) {
          return letter.toUpperCase();
        });

      $("td:eq(5)", nRow).html(tipo_registro);

      var now = new Date(aData.fecha_registro);

      $("td:eq(0)", nRow).html(getDateInString(now));

      //Badge
      if (aData.estado == "REGULAR") {
        $("td:eq(3)", nRow).html(
          "<span class='badge badge-success'>" + aData.estado + "</span>"
        );
      } else if (aData.estado == "TARDANZA") {
        $("td:eq(3)", nRow).html(
          "<span class='badge badge-warning'>" + aData.estado + "</span>"
        );
      } else if (aData.estado == "FALTA") {
        $("td:eq(3)", nRow).html(
          "<span class='badge badge-danger'>" + aData.estado + "</span>"
        );
      } else if (aData.estado == "SALIDA ANTICIPADA") {
        $("td:eq(3)", nRow).html(
          "<span class='badge badge-info'>" + aData.estado + "</span>"
        );
      }
    },
  });
});

function getDateInString(now) {
  const options = {
    month: "long",
    day: "numeric",
    year: "numeric",
    weekday: "long",
  };

  var date = new Date(now);
  date.setDate(date.getDate() + 1);

  return date.toLocaleDateString("default", options);
}

$("#form_filter").on("submit", function (e) {
  e.preventDefault();
  var anio = $("#anio_select").val();
  var mes = $("#mes_select").val();
  var dia = $("#dia_select").val();
  var empleado = $("#empleado_select").val();
  var url =
    "../../controller/biometrico.php?op=filter&fil=all&anio=" +
    anio +
    "&mes=" +
    mes +
    "&dia=" +
    dia +
    "&usuario=" +
    empleado;
  $("#data-biometric").DataTable().ajax.url(url).load();
});

$("#register_form").on("submit", function (e) {
  e.preventDefault();

  var formData = new FormData($("#register_form")[0]);

  $.ajax({
    url: "../../controller/biometrico.php?op=registro_admin",
    type: "POST",
    data: formData,
    contentType: false,
    processData: false,
    success: function (data) {
      if (data.status == "success") {
        $("#registro_biometrico").modal("hide");
        $("#data-biometric").DataTable().ajax.reload();
        Swal.fire({
          title: "Registro exitoso",
          text: data.message,
          icon: "success",
          confirmButtonText: "Aceptar",
        });
      } else {
        Swal.fire({
          title: "Error",
          text: data.message,
          icon: "error",
          confirmButtonText: "Aceptar",
        });
      }
    },
  });
});

$("#save_register").on("click", function (e) {
  e.preventDefault();
  $("#register_form").submit();
});

function nuevo() {
  $("#register_form")[0].reset();
  $("#user_current").addClass("d-none");
  $("#person_update").html("");
  $("#registro_biometrico").modal("show");
}

function getTime() {
  const hourInitial = "08:00:00";
  const houtInitialLimit = "08:30:00";
  const hourFinal = "05:00:00 PM";

  var date = new Date();
  var h = date.getHours();
  var m = date.getMinutes();
  var s = date.getSeconds();
  var session = "AM";

  if (h == 0) {
    h = 12;
  }

  if (h > 12) {
    h = h - 12;
    session = "PM";
  }

  h = h < 10 ? "0" + h : h;
  m = m < 10 ? "0" + m : m;
  s = s < 10 ? "0" + s : s;

  var timeState = h + ":" + m + ":" + s;
  var time = h + ":" + m + ":" + s + " " + session;

  document.getElementById("MyClockDisplay").innerText = time;
  document.getElementById("MyClockDisplay").textContent = time;

  setTimeout(getTime, 1000);
}

function getCurrentDate() {
  const date = new Date();
  const options = {
    month: "long",
    day: "numeric",
    year: "numeric",
    weekday: "long",
  };

  document.getElementById("MyDateDisplay").innerText = date.toLocaleDateString(
    "default",
    options
  );
  document.getElementById("MyDateDisplay").textContent =
    date.toLocaleDateString("default", options);
}

getTime();
getCurrentDate();

function eliminar(id) {
  Swal.fire({
    title: "¿Esta seguro de eliminar el registro?",
    text: "¡No podrás revertir esto!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#3085d6",
    cancelButtonColor: "#d33",
    confirmButtonText: "Si, eliminarlo!",
  }).then((result) => {
    if (result.isConfirmed) {
      $.post(
        "../../controller/biometrico.php?op=eliminar_registro",
        { id: id },
        function (e) {
          $("#data-biometric").DataTable().ajax.reload();
          Swal.fire("Eliminado!", "El registro ha sido eliminado.", "success");
        }
      );
    }
  });
}

function editar(id) {
  $("#register_form")[0].reset();
  $.post(
    "../../controller/biometrico.php?op=mostrar_biometrico",
    { id: id },
    function (data, status) {
      $("#id_registro").val(data.id);
      $("#date_register").val(data.fecha_registro);
      $("#hour_register").val(data.hora_registro);
      $("#register_format").val(data.tipo_registro);
      $("#biometricodbk").val(data.biometricodbk);
      $("#personadbk").val(data.personadbk);

      $("#user_current").removeClass("d-none");
      $("#person_update").html(data.nombre);

      $("#status").val(data.estado);

      $("#observation").val(data.observacion);

      $("#registro_biometrico").modal("show");
    }
  );
}

$("#clear_filter").on("click", function (e) {
  e.preventDefault();
  $("#form_filter")[0].reset();

  $("#anio_select").val("").trigger("change");
  $("#mes_select").val("").trigger("change");
  $("#dia_select").val("").trigger("change");
  $("#empleado_select").val("").trigger("change");

  $("#data-biometric")
    .DataTable()
    .ajax.url(
      "../../controller/biometrico.php?op=filter&fil=all&anio=&mes=&dia=&usuario="
    )
    .load();
});
