<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>EBG - Dashboard</title>
    <!-- Essential JS -->
    <script>
      const lang = <%- JSON.stringify(language) %>
    </script>
    <script src="<%= domain %>/appjs/i18next.js?<%= curentUnixTime %>"></script>
    <!-- CSS files -->
    <link href="<%= domain %>/dist/css/tabler.min.css?<%= curentUnixTime %>" rel="stylesheet" />
    <link href="<%= domain %>/dist/css/tabler-flags.min.css?<%= curentUnixTime %>" rel="stylesheet" />
  </head>
  <body>
    <script src="/appjs/format.js"></script>
    <div class="page">
      <!-- Navbar -->
      <%- html_content.navbar %>
      <div class="page-wrapper">
        <!-- Page header -->
        <div class="page-header d-print-none">
          <div class="container-xl">
            <div class="row g-2 align-items-center">
              <div class="col">
                <h2 class="page-title" data-translate="Events.Body.Head.Title"></h2>
                <div class="text-muted mt-1" data-translate="Events.Body.Head.SubTitle"></div>
              </div>
              <!-- Page title actions -->
              <div class="col-auto ms-auto d-print-none">
                <div class="d-flex">
                  <div class="me-3">
                    <div class="input-icon">
                      <input type="text" value="" class="form-control" id="PageSearch" onkeypress="debouncedLoadPage()" onchange="loadPage()" data-translate-placeholder="Page.Search" placeholder="" />
                      <span class="input-icon-addon">
                        <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                          <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                          <path d="M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0" />
                          <path d="M21 21l-6 -6" />
                        </svg>
                      </span>
                    </div>
                  </div>
                  <a class="btn btn-primary" class="btn" data-bs-toggle="modal" data-bs-target="#modal-report">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                      <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                      <path d="M12 5l0 14" />
                      <path d="M5 12l14 0" />
                    </svg>
                    <div data-translate="Events.Body.Head.AddButton"></div>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- Page body -->
        <div class="page-body">
          <div class="container-xl">
            <div class="row row-cards row-deck" id="event-container"></div>
            <div id="paginationContainer"></div>
          </div>
        </div>
        <%- html_content.footer %>
      </div>
    </div>
    <div class="modal modal-blur fade" id="modal-report" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" data-translate="Events.Modal.NewEvent.Title"></h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="row mb-3 align-items-end">
              <div class="col">
                <label class="form-label" data-translate="Events.Modal.NewEvent.EventName"></label>
                <input type="text" id="NewEventEventName" data-translate-placeholder="Events.Modal.NewEvent.Placeholder.EventName" class="form-control" />
              </div>
            </div>
            <div class="row">
              <div class="col-lg-7">
                <label class="form-label" data-translate="Events.Modal.NewEvent.Color"></label>
                <div class="row g-2">
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="dark" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-dark"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput form-colorinput-light">
                      <input name="color" type="radio" value="white" class="form-colorinput-input" checked />
                      <span class="form-colorinput-color bg-white"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="blue" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-blue"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="azure" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-azure"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="indigo" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-indigo"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="purple" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-purple"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="pink" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-pink"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="red" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-red"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="orange" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-orange"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="yellow" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-yellow"></span>
                    </label>
                  </div>
                  <div class="col-auto">
                    <label class="form-colorinput">
                      <input name="color" type="radio" value="lime" class="form-colorinput-input" />
                      <span class="form-colorinput-color bg-lime"></span>
                    </label>
                  </div>
                </div>
              </div>

              <div class="col-lg-5">
                <div class="mb-5">
                  <label class="form-label" data-translate="Events.Modal.NewEvent.Visibility"></label>
                  <select class="form-select" id="NewEventVisibility">
                    <option value="1" data-translate="Events.Modal.NewEvent.Visibility_Open" selected></option>
                    <option value="0" data-translate="Events.Modal.NewEvent.Visibility_Hidden"></option>
                  </select>
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col-lg-4">
                <div class="mb-4">
                  <label class="form-label" data-translate="Events.Modal.NewEvent.DateApply"></label>
                  <input type="datetime-local" id="NewEventDateApply" class="form-control" />
                </div>
              </div>
              <div class="col-lg-4">
                <div class="mb-4">
                  <label class="form-label" data-translate="Events.Modal.NewEvent.DateStart"></label>
                  <input type="datetime-local" id="NewEventDateStart" class="form-control" />
                </div>
              </div>
              <div class="col-lg-4">
                <div class="mb-4">
                  <label class="form-label" data-translate="Events.Modal.NewEvent.DateEnd"></label>
                  <input type="datetime-local" id="NewEventDateEnd" class="form-control" />
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col-lg-8">
                <div class="mb-4">
                  <label class="form-label" data-translate="Events.Modal.NewEvent.Location"></label>
                  <input type="text" id="NewEventLocation" data-translate-placeholder="Events.Modal.NewEvent.Placeholder.Location" class="form-control" />
                </div>
              </div>

              <div class="col-lg-4">
                <div class="mb-4">
                  <label class="form-label" data-translate="Events.Modal.NewEvent.MinGroup"></label>
                  <select type="form-select" id="NewEventMinGroup" class="form-control">
                    <option value="<%= default_group %>" data-translate="Events.Modal.NewEvent.MinGroup_RegOnly" selected></option>
                    <option value="<%= default_member_group %>" data-translate="Events.Modal.NewEvent.MinGroup_Members"></option>
                  </select>
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col-lg-12">
                <div class="mb-4">
                  <label class="form-label" data-translate="Events.Modal.NewEvent.Description"></label>
                  <textarea class="form-control" id="NewEventDescription" data-translate-placeholder="Events.Modal.NewEvent.Placeholder.Description" rows="3"></textarea>
                </div>
              </div>
            </div>

            <div class="row">
              <div class="col-lg-12">
                <div id="NewEventErrorLine"></div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <a class="btn btn-link link-secondary" data-bs-dismiss="modal" data-translate="Events.Modal.NewEvent.Cancel"></a>
            <a class="btn btn-primary ms-auto" id="NewEventSubmitBtn">
              <!-- Download SVG icon from http://tabler-icons.io/i/plus -->
              <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                <path d="M12 5l0 14" />
                <path d="M5 12l14 0" />
              </svg>
              <span data-translate="Events.Modal.NewEvent.AddNew"></span>
            </a>
          </div>
        </div>
      </div>
    </div>
    <!-- Libs JS -->
    <!-- Tabler Core -->
    <script src="<%= domain %>/appjs/permission.js?<%= curentUnixTime %>" defer></script>
    <script src="<%= domain %>/appjs/translate.js?<%= curentUnixTime %>"></script>
    <script src="<%= domain %>/dist/js/tabler.min.js?<%= curentUnixTime %>" defer></script>
    <script src="<%= domain %>/appjs/layout.js?<%= curentUnixTime %>"></script>
    <script>
      // Load events and display them
      const loadPageContent = (page, size) => {
        const search = document.getElementById("PageSearch").value;
        fetch(`api/v1/event?page=${page}&size=${size}&search=${search}`, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        }).then(async (response) => {
          const response_json = await response.json();
          if (response.status == 200) {
            const eventContainer = document.getElementById("event-container");
            eventContainer.innerHTML = "";
            response_json.forEach((event) => {
              const permResult = checkPermission(`group.${event.min_group}`);
              eventContainer.innerHTML += `<div class="col-12">
                <a class="card card-link" href="/event/${event.puuid}">
                  <div class="card-status-top bg-${event.color}"></div>
                  <div class="d-flex" style="align-items: flex-start;">
                    <div style="flex: 0 0 auto; width: 164px; height: 164px; overflow: hidden;">
                      <img src="${event.avatar_url}" style="width: 100%; height: 100%; object-fit: cover;">
                    </div>
                    <div style="flex-grow: 1; padding-left: 8px;">
                      <div class="card-body">
                        <div class="d-flex justify-content-between">
                          <h3 class="card-title">${event.name}</h3>
                          <div>
                            ${
                              event.user_participates
                                ? `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-user-check">
                              <path stroke="none" d="M0 0h24v24H0z" fill="none"/>
                              <path d="M8 7a4 4 0 1 0 8 0a4 4 0 0 0 -8 0"/>
                              <path d="M6 21v-2a4 4 0 0 1 4 -4h4"/>
                              <path d="M15 19l2 2l4 -4"/>
                            </svg>
                            <span>${i18next.t("Events.Body.Card.Participates")}</span>`
                                : `<div class="btn btn-primary ${!permResult.result ? "disabled " : ""}" style="cursor: pointer;" onclick="event.stopPropagation(); joinEvent(this.id); return false;" id="${event.puuid}">
                              <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 5v14M5 12h14" /></svg>
                              <div>${i18next.t("Events.Body.Card.JoinButton")}</div>
                              </div>`
                            }
                          </div>
                        </div>
                        <p class="text-secondary">${event.description}</p>
                        <div>
                          <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0z" /></svg>
                          ${i18next.t("Events.Body.Card.Location")}: ${event.location_address}
                        </div>
                        <div class="d-flex justify-content-between">
                          <div class="mt-3">
                            <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-alarm"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M12 13m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0" /><path d="M12 10l0 3l2 0" /><path d="M7 4l-2.75 2" /><path d="M17 4l2.75 2" /></svg>
                            <span>${i18next.t("Events.Body.Card.JoinDate")}: ${new Date(event.date_apply).toLocaleString("de-DE", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit", year: "numeric" })}</span>
                          </div>
                          <div class="mt-3">
                            <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-calendar-event"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 5m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z" /><path d="M16 3l0 4" /><path d="M8 3l0 4" /><path d="M4 11l16 0" /><path d="M8 15h2v2h-2z" /></svg>
                            <span>${i18next.t("Events.Body.Card.StartDate")}: ${new Date(event.date_start).toLocaleString("de-DE", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit", year: "numeric" })}</span>
                          </div>
                          <div class="mt-3">
                            <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-calendar-event"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 5m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z" /><path d="M16 3l0 4" /><path d="M8 3l0 4" /><path d="M4 11l16 0" /><path d="M8 15h2v2h-2z" /></svg>
                            <span>${i18next.t("Events.Body.Card.EndDate")}: ${new Date(event.date_end).toLocaleString("de-DE", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit", year: "numeric" })}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </a>
              </div>
              `;
            });
          } else {
            // Error
          }
        });
      };

      const loadPage = async () => {
        const search = document.getElementById("PageSearch").value;
        const pagerequest = await fetch(`api/v1/event/count?search=${search}`, {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        });

        if (pagerequest.status == 200) {
          const response_json = await pagerequest.json();
          generatePagination(parseInt(response_json, 10), 10, 1, loadPageContent);
        } else {
          // Error
        }
      };

      const joinEvent = async (id) => {
        const response = await fetch(`/api/v1/event/${id}/join`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        });

        if (response.status == 200) {
          const event_data = await response.json();

          loadPage();
        } else {
          // ToDo: Snackbar Error
        }
      };

      const keys = {
        eventName: "NewEventEventName",
        minGroup: "NewEventMinGroup",
        visibility: "NewEventVisibility",
        dateApply: "NewEventDateApply",
        dateStart: "NewEventDateStart",
        dateEnd: "NewEventDateEnd",
        location: "NewEventLocation",
        description: "NewEventDescription",
      };
      const getSelectedColorValue = () => {
        const colorInputs = document.querySelectorAll('input[name="color"]:checked');
        return colorInputs.length > 0 ? colorInputs[0].value : null;
      };
      // Detekt submit button press
      document.getElementById("NewEventSubmitBtn").addEventListener("click", function () {
        // Get values
        const eventName = document.getElementById("NewEventEventName").value;
        const color = getSelectedColorValue();
        const minGroup = document.getElementById("NewEventMinGroup").value;
        const visibility = document.getElementById("NewEventVisibility").value;
        const dateApply = document.getElementById("NewEventDateApply").value;
        const dateStart = document.getElementById("NewEventDateStart").value;
        const dateEnd = document.getElementById("NewEventDateEnd").value;
        const location = document.getElementById("NewEventLocation").value;
        const description = document.getElementById("NewEventDescription").value;

        fetch("/api/v1/event", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
          body: JSON.stringify({
            eventName: eventName,
            color: color,
            minGroup: minGroup,
            visibility: visibility,
            dateApply: dateApply,
            dateStart: dateStart,
            dateEnd: dateEnd,
            location: location,
            description: description,
          }),
        }).then(async (response) => {
          const response_json = await response.json();
          if (response.status == 200) {
            for (const key in keys) {
              document.getElementById(keys[key]).classList.remove("is-invalid");
            }
            closeModal("modal-report");
            loadPage();
          } else {
            if (typeof response_json.reason === "string") {
              document.getElementById("NewEventErrorLine").innerHTML = '<div class="alert alert-danger">' + i18next.t(`Error.${response_json.message}`) + "</div>";
              return;
            }
            const input_name = response_json.reason[0].path[0];
            const input_type = response_json.reason[0].type;
            for (const key in keys) {
              document.getElementById(keys[key]).classList.remove("is-invalid");
            }

            document.getElementById("NewEventErrorLine").innerHTML = '<div class="alert alert-danger">' + i18next.t(`Error.Joi.${input_type}`, { field: i18next.t(`Events.Modal.NewEvent.${capitalizeFirstLetter(input_name)}`), limit: response_json.reason[0].context?.limit }) + "</div>";
            document.getElementById(keys[input_name]).classList.add("is-invalid");
          }
        });
      });

      loadPage();
      const debouncedLoadPage = debounce(loadPage);
    </script>
  </body>
</html>
