document.addEventListener("DOMContentLoaded", function () {
  var calendarEl = document.getElementById("calendar");
  var container = document.getElementById("external-events");

  var Calendar = FullCalendar.Calendar;
  var Draggable = FullCalendar.Draggable;

  new Draggable(container, {
    itemSelector: ".external-event",
    eventData: function (eventEl) {
      return {
        title: eventEl.innerText,
        backgroundColor: window
          .getComputedStyle(eventEl, null)
          .getPropertyValue("background-color"),
        borderColor: window
          .getComputedStyle(eventEl, null)
          .getPropertyValue("background-color"),
        textColor: window
          .getComputedStyle(eventEl, null)
          .getPropertyValue("color"),
      };
    },
  });

  var calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: "dayGridMonth",
    initialDate: "2022-12-07",
    headerToolbar: {
      left: "prev,next today",
      center: "title",
      right: "dayGridMonth,timeGridWeek,timeGridDay",
    },
    editable: true,
    droppable: true,
    themeSystem: "bootstrap",
    eventDrop: function (info) {
      var id = info.event.id;

      UpdateEventsCalendar(id, info.event.startStr);
    },
    drop: function (info) {
      var id = info.draggedEl.getAttribute("data-id");

      CreateEventsCalendar(id, info.dateStr);
    },
    eventClick: function (info) {
      var id = info.event.id;

      Swal.fire({
        title: "¿Está seguro de eliminar el evento?",
        text: "¡No podrás revertir esto!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Si, eliminarlo!",
      }).then((result) => {
        if (result.isConfirmed) {
          $.ajax({
            url: "../../controller/calendar.php?op=delete",
            type: "POST",
            data: {
              calendardbk: id,
            },
            success: function (data) {
              if (data.status == "success") {
                info.event.remove();
                Swal.fire({
                  title: "Evento Eliminado",
                  text: "El evento se ha eliminado correctamente",
                  icon: "success",
                  confirmButtonText: "Aceptar",
                });
              } else {
                Swal.fire({
                  title: "Error",
                  text: "El evento no se ha eliminado correctamente",
                  icon: "error",
                  confirmButtonText: "Aceptar",
                });
              }
            },
          });
        }
      });
    },
  });

  calendar.render();

  loadEventsCalendar(calendar);
});

function UpdateEventsCalendar(id, date) {
  $.ajax({
    url: "../../controller/calendar.php?op=update",
    type: "POST",
    data: {
      calendardbk: id,
      fecha_evento: date,
    },
    success: function (data) {
      if (data.status == "success") {
        Swal.fire({
          title: "Evento Actualizado",
          text: "El evento se ha actualizado correctamente",
          icon: "success",
          confirmButtonText: "Aceptar",
        });
      } else {
        Swal.fire({
          title: "Error",
          text: "El evento no se ha actualizado correctamente",
          icon: "error",
          confirmButtonText: "Aceptar",
        });
      }
    },
  });
}

function CreateEventsCalendar(id, date) {
  $.ajax({
    url: "../../controller/calendar.php?op=create",
    type: "POST",
    data: {
      eventodbk: id,
      fecha_evento: date,
    },
    success: function (data) {
      if (data.status == "success") {
        //getEvents();
        Swal.fire({
          title: "Evento Agregado",
          text: "El evento se ha agregado correctamente",
          icon: "success",
          confirmButtonText: "Aceptar",
        });
      }
    },
  });
}

function events(ele) {
  ele.each(function () {
    var eventObject = {
      title: $.trim($(this).text()),
    };
    $(this).data("eventObject", eventObject);
    $(this).draggable({
      zIndex: 999,
      revert: true,
      revertDuration: 0,
    });
  });
}

events($("#external-events div.external-event"));

var currentColor = "#3c8dbc";

$("#color-chooser > li > a").click(function (e) {
  e.preventDefault();

  currentColor = $(this).css("color");

  $("#add-new-event").css({
    "background-color": currentColor,
    "border-color": currentColor,
  });
});

$("#create-event").submit(function (e) {
  e.preventDefault();

  var val = $("#title_event").val();

  const data = {
    title: val,
    color: currentColor,
  };

  $.ajax({
    url: "../../controller/event.php?op=create",
    type: "POST",
    data: data,
    success: function (data) {
      if (data.status == "success") {
        getEvents();
      }
    },
  });
});

function getEvents() {
  $("#external-events").html("");

  $.ajax({
    url: "../../controller/event.php?op=eventos",
    type: "GET",
    success: function (data) {
      data.forEach((element) => {
        var event = $(
          `<div data-id="${element.eventodbk}" data-color="${element.color_evento}" />`
        );

        event
          .css({
            "background-color": element.color_evento,
            "border-color": element.color_evento,
            color: "#fff",
          })
          .addClass("external-event");
        event.html(
          `<div class="fc-event">
            <div class="fc-event-title">
              <button type="button" class="btn btn-outline-light btn-xs btn-icon mr-2" data-toggle="dropdown" aria-expanded="false">  
                <i class="fas fa-cog"></i>
              </button>
              <div class="dropdown-menu" role="menu" style="">
                <a class="dropdown-item btn-del-event" href="javascript:void(0)" onClick="DeleteEvent(${element.eventodbk});">
                    <i class="fas fa-trash mr-2"></i> Eliminar Evento
                </a>
                <a class="dropdown-item btn-edit-event" href="javascript:void(0)" onClick="EditEvent(${element.eventodbk}, '${element.titulo_evento}');">
                    <i class="fas fa-edit mr-2"></i> Editar Evento
                </a>
              </div>
              <span class="fc-event-title">${element.titulo_evento}</span>
            </div>
          </div>`
        );
        $("#external-events").prepend(event);

        events(event);
      });
    },
  });
}

function loadEventsCalendar(calendar) {
  $.ajax({
    url: "../../controller/calendar.php?op=get",
    type: "GET",
    success: function (data) {
      var events = [];

      data.data.forEach((element) => {
        events.push({
          title: element.titulo_evento,
          start: element.fecha_evento,
          end: element.fecha_evento,
          backgroundColor: element.color_evento,
          borderColor: element.color_evento,
          textColor: "#fff",
          id: element.calendardbk,
        });
      });

      calendar.addEventSource(events);
    },
  });
}

function DeleteEvent(id) {
  Swal.fire({
    title: "¿Estas seguro?",
    text: "No podras revertir esta accion!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#3085d6",
    cancelButtonColor: "#d33",
    confirmButtonText: "Si, eliminar!",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../controller/event.php?op=delete",
        type: "POST",
        data: { id: id },
        success: function (data) {
          if (data.status == "success") {
            Swal.fire("Eliminado!", "El evento ha sido eliminado.", "success");
            getEvents();
          }
        },
      });
    }
  });
}

function EditEvent(id, title) {
  Swal.fire({
    title: "Editar Evento",
    input: "text",
    inputValue: title,
    showCancelButton: true,
    confirmButtonText: "Guardar",
    showLoaderOnConfirm: true,
    preConfirm: (value) => {
      const data = {
        id: id,
        title: value,
      };

      return $.ajax({
        url: "../../controller/event.php?op=update",
        type: "POST",
        data: data,
        success: function (data) {},
      });
    },
    allowOutsideClick: () => !Swal.isLoading(),
  }).then((result) => {
    if (result.isConfirmed) {
      if (result.value.status == "success") {
        Swal.fire("Actualizado!", "El evento ha sido actualizado.", "success");
        getEvents();
      } else {
        Swal.fire(
          "Error!",
          "Ocurrio un error al actualizar el evento.",
          "error"
        );
      }
    }
  });
}

getEvents();
