<!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-0 align-items-center">
              <div class="col">
                <h2 class="page-title" data-translate="Events.Settings.Title"></h2>
              </div>
              <div class="col-auto">
                <span>
                  <a href="/event/<%= params.id %>" class="btn btn-primary">
                    <!-- Download SVG icon from http://tabler-icons.io/i/arrow-left -->
                    <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><path d="M5 12l14 0"></path><path d="M5 12l6 6"></path><path d="M5 12l6 -6"></path></svg>
                    <div data-translate="Button.GoBack"></div>
                  </a>
                </span>
              </div>
          </div>
        </div>
        <!-- Page body -->
        <div class="page-body">
          <div class="container-xl">
            <div class="card">
              <!-- Sidebar Toggle Button for Small Screens -->
              <div class="card-body d-md-none">
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-expanded="false" aria-label="Toggle navigation">
                  <span class="navbar-toggler-icon"></span>
                </button>
              </div>
              <div class="row g-0">
                <div class="col-12 col-md-3 d-md-block collapse border-end" id="sidebar-menu">
                  <div class="card-body">
                    <div class="list-group list-group-transparent">
                      <a href="/event/<%= params.id %>/settings" class="list-group-item list-group-item-action d-flex align-items-center active" data-translate="Events.Settings.Site.General"></a>
                      <a href="/event/<%= params.id %>/settings-announce" class="list-group-item list-group-item-action d-flex align-items-center" data-translate="Events.Settings.Site.Announce"></a>
                      <a href="/event/<%= params.id %>/settings-oauth" class="list-group-item list-group-item-action d-flex align-items-center" data-translate="Events.Settings.Site.OAuth"></a>
                    </div>
                  </div>
                </div>
                <div class="col d-flex flex-column">
                  <div class="card-body">
                    <h2 class="mb-4" data-translate="Events.Settings.Site.General"></h2>
                    <div class="row mb-3 align-items-end">
                      <div class="col-auto">
                        <div class="row align-items-center">
                          <div class="col-auto"><span class="avatar avatar-xl" id="Settings.Event.AvatarIcon" style="background-image: url()"></span></div>
                          <div class="col-auto"><a data-bs-toggle="modal" data-bs-target="#modal-upload-eavatar" class="btn" data-translate="Events.Settings.Button.SetAvatarIcon"></a></div>
                          <div class="col-auto"><a data-bs-toggle="modal" data-bs-target="#modal-danger-delete-eavatar" class="btn btn-ghost-danger" data-translate="Events.Settings.Button.DeleteAvatarIcon" id="DelEAvatarIcon"></a></div>
                        </div>
                      </div>
                    </div>
                    <!-- EventName Row -->
                    <div class="row">
                      <div class="col-lg-12">
                        <div class="mb-4">
                          <label class="form-label" data-translate="Events.Modal.NewEvent.EventName"></label>
                          <input type="text" id="EventName" data-translate-placeholder="Events.Modal.NewEvent.Placeholder.EventName" onchange="handleInputChange(this.id)" class="form-control" />
                        </div>
                      </div>
                    </div>
                    <!-- Color & Event Visibility Row-->
                    <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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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" onchange="handleColorChange(this.value)" 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="EventVisibility" onchange="handleInputChange(this.id)">
                            <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>
                    <!-- Date Row-->
                    <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="EventDateApply" class="form-control" onchange="handleInputChange(this.id)">
                        </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="EventDateStart" class="form-control" onchange="handleInputChange(this.id)">
                        </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="EventDateEnd" class="form-control" onchange="handleInputChange(this.id)">
                        </div>
                      </div>
                    </div>
                    <!-- Location & MinGroup Row-->
                    <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="EventLocation" data-translate-placeholder="Events.Modal.NewEvent.Placeholder.Location" onchange="handleInputChange(this.id)" 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="EventMinGroup" class="form-control" onchange="handleInputChange(this.id)">
                            <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>
                    <!-- Description Row-->
                    <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="EventDescription" onchange="handleInputChange(this.id)" 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>
              </div>
            </div>
          </div>
        </div>
        <%- html_content.footer %>
      </div>
    </div>
    <div class="modal fade" id="modal-upload-eavatar" tabindex="-1" aria-labelledby="uploadAvatarModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="uploadAvatarModalLabel" data-translate="Settings.Main.AvatarHeadline"></h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="col-md-12">
              <div class="card">
                <div class="card-body">
                  <h3 class="card-title" data-translate="Settings.Main.AvatarUploadArea"></h3>
                  <form class="dropzone" id="dropzone-avatar-upload" autocomplete="off" novalidate style="border: 2px dashed #ccc; border-radius: 10px; padding: 40px; text-align: center; cursor: pointer; transition: border-color 0.3s, background-color 0.3s">
                    <div class="fallback">
                      <input name="file" type="file" style="display: none" />
                    </div>
                    <div class="dz-message">
                      <h3 class="dropzone-msg-title" style="font-size: 24px; margin-bottom: 10px" data-translate="Settings.Main.AvatarDragHere"></h3>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-translate="Settings.Main.Button.Cancel"></button>
            <button type="button" class="btn btn-primary" id="upload-button" data-translate="Settings.Main.Button.Upload"></button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal modal-blur fade" id="modal-danger-delete-eavatar" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog modal-sm modal-dialog-centered" role="document">
        <div class="modal-content">
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          <div class="modal-status bg-danger"></div>
          <div class="modal-body text-center py-4">
            <!-- Download SVG icon from http://tabler-icons.io/i/alert-triangle -->
            <svg xmlns="http://www.w3.org/2000/svg" class="icon mb-2 text-danger icon-lg" 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.24 3.957l-8.422 14.06a1.989 1.989 0 0 0 1.7 2.983h16.845a1.989 1.989 0 0 0 1.7 -2.983l-8.423 -14.06a1.989 1.989 0 0 0 -3.4 0z" />
              <path d="M12 9v4" />
              <path d="M12 17h.01" />
            </svg>
            <h3 data-translate="Common_Modals.Delete.Title"></h3>
            <div class="text-muted" data-translate="Settings.Profile.AvatarDelete"></div>
          </div>
          <div class="modal-footer">
            <div class="w-100">
              <div class="row">
                <div class="col"><a class="btn w-100" data-bs-dismiss="modal" data-translate="Common_Modals.Delete.Button.Cancel"></a></div>
                <div class="col"><a class="btn btn-danger w-100" data-bs-dismiss="modal" onclick="deleteEAvatar()" data-translate="Common_Modals.Delete.Button.Delete"></a></div>
              </div>
            </div>
          </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 src="<%= domain %>/dist/libs/dropzone/dist/dropzone-min.js?<%= curentUnixTime %>" defer></script>
    <script>

      // Delete Event Avatar
      const deleteEAvatar = async () => {
        const response = await fetch("/api/v1/event/<%= params.id %>/avatar", {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        });

        if (response.status == 200) {
          const response_json = await response.json();
          closeModal("modal-danger-delete-eavatar");
          document.getElementById("Settings.Event.AvatarIcon").style.backgroundImage = `url(${response_json.fileName})`;
        }
      };

      // Dropzone Avatar
      document.querySelector("#dropzone-avatar-upload").addEventListener("dragover", function (event) {
        event.preventDefault();
        event.stopPropagation();
        this.style.borderColor = "#000";
        this.style.backgroundColor = "#f0f0f0";
      });

      document.querySelector("#dropzone-avatar-upload").addEventListener("dragleave", function (event) {
        event.preventDefault();
        event.stopPropagation();
        this.style.borderColor = "#ccc";
        this.style.backgroundColor = "";
      });

      document.querySelector("#dropzone-avatar-upload").addEventListener("drop", function (event) {
        event.preventDefault();
        event.stopPropagation();
        this.style.borderColor = "#ccc";
        this.style.backgroundColor = "";
      });

      // Handle changes to all imput fields (VanillaJS)
      const apiEndpoints = {
        "EventName": {
          "endpoint": "/api/v1/event/<%= params.id %>/name",
          "method": "POST",
          "field": "name",
          "value": "raw"
        },
        "EventDescription": {
          "endpoint": "/api/v1/event/<%= params.id %>/description",
          "method": "POST",
          "field": "description",
          "value": "raw"
        },
        "EventLocation": {
          "endpoint": "/api/v1/event/<%= params.id %>/location",
          "method": "POST",
          "field": "location",
          "value": "raw"
        },
        "EventVisibility": {
          "endpoint": "/api/v1/event/<%= params.id %>/visibility",
          "method": "POST",
          "field": "visibility",
          "value": "raw"
        },
        "EventDateApply": {
          "endpoint": "/api/v1/event/<%= params.id %>/dateapply",
          "method": "POST",
          "field": "dateApply",
          "value": "raw"
        },
        "EventDateStart": {
          "endpoint": "/api/v1/event/<%= params.id %>/datestart",
          "method": "POST",
          "field": "dateStart",
          "value": "raw"
        },
        "EventDateEnd": {
          "endpoint": "/api/v1/event/<%= params.id %>/dateend",
          "method": "POST",
          "field": "dateEnd",
          "value": "raw"
        },
        "EventMinGroup": {
          "endpoint": "/api/v1/event/<%= params.id %>/mingroup",
          "method": "POST",
          "field": "minGroup",
          "value": "raw"
        },
      };

      const getSelectedColorValue = () => {
        const colorInputs = document.querySelectorAll('input[name="color"]:checked');
        return colorInputs.length > 0 ? colorInputs[0].value : null;
      }

      const setLoadedColorValue = (color) => {
        const colorInputs = document.querySelectorAll('input[name="color"]');
        colorInputs.forEach((input) => {
          if (input.value === color) {
            input.checked = true;
          }
        });
      }

      const handleInputChange = async (id) => {
        const inputElement = document.getElementById(id);
        let value_send;

        if(apiEndpoints[id].value == "raw") {
          value_send = inputElement.value;
        } else if(apiEndpoints[id].value == "bool") {
          value_send = inputElement.checked;
        }

        const response = await fetch(apiEndpoints[id].endpoint, {
          method: apiEndpoints[id].method,
          headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + localStorage.getItem("token")
          },
          body: JSON.stringify({
            [apiEndpoints[id].field]: value_send
          })
        });

        if (response.ok) {
          inputElement.classList.remove("is-invalid");
          inputElement.classList.add("is-valid");

          setTimeout(() => {
            inputElement.classList.remove("is-valid");
          }, 3000);
        } else {
          inputElement.classList.add("is-invalid");
        }
      }

      handleColorChange = async (color) => {
        const response = await fetch("/api/v1/event/<%= params.id %>/color", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",

            "Authorization": "Bearer " + localStorage.getItem("token")
          },
          body: JSON.stringify({
            color: color
          })
        });

        if (response.ok) {
          const colorInputs = document.querySelectorAll('input[name="color"]');
          colorInputs.forEach((input) => {
            if (input.value === color) {
              input.checked = true;
            }
          });
        }
      }

      // Auto-fill user data (VanillaJS) and initialize Dropzone
      document.addEventListener("DOMContentLoaded", async () => {
        Dropzone.autoDiscover = false;

        const dropzone = new Dropzone("#dropzone-avatar-upload", {
          url: "/api/v1/event/<%= params.id %>/avatar",
          autoProcessQueue: false,
          maxFiles: 1,
          previewsContainer: ".dropzone",
          headers: {
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
          init: function () {
            this.on("addedfile", function (file) {
              // Check if the file is already compressed to prevent loop
              if (file.isCompressed) return;
              if (file.type !== "image/jpeg" && file.type !== "image/png") {
                this.removeFile(file);
                alert(i18next.t("Error.AvatarTypeNotSupported", { type: file.type.split("/")[1] }));
                return;
              }
              if (this.files.length > 1) this.removeFile(this.files[0]);
              // Compress and resize the image before adding it to the Dropzone file list
              const img = new Image();
              img.src = URL.createObjectURL(file);
              img.onload = () => {
                const canvas = document.createElement("canvas");
                const ctx = canvas.getContext("2d");
                const size = Math.min(img.width, img.height);
                const x = (img.width - size) / 2;
                const y = (img.height - size) / 2;
                canvas.width = 1024;
                canvas.height = 1024;
                ctx.drawImage(img, x, y, size, size, 0, 0, canvas.width, canvas.height);

                canvas.toBlob(
                  (blob) => {
                    let newFileType = file.type;
                    let newFileName = file.name;

                    if (file.type === 'image/png') {
                      newFileType = 'image/jpeg';
                      newFileName = file.name.replace(/\.png$/, '.jpg');
                    }

                    const croppedImage = new File([blob], newFileName, { type: newFileType });
                    croppedImage.isCompressed = true; // Set compression flag, so we don't compress it again

                    this.removeFile(file);
                    this.addFile(croppedImage);

                    const previewElement = document.querySelector("[data-dz-thumbnail]");
                    if (previewElement) {
                      previewElement.src = URL.createObjectURL(croppedImage);
                    }
                  },
                  file.type === 'image/png' ? 'image/jpeg' : file.type,
                  0.74
                );
              };
            });
            this.on("success", function (file, response) {
              // Remove the image from the dropzone
              this.removeFile(file);
              document.getElementById("Settings.Event.AvatarIcon").style.backgroundImage = `url(${response.fileName})`;
              closeModal("modal-upload-eavatar");
            });
          },
          previewTemplate: `
                <div class="dz-preview dz-file-preview">
                    <div class="dz-image"><img data-dz-thumbnail/></div>
                    <div class="dz-details">
                        <div class="dz-size"><span data-dz-size></span></div>
                    </div>
                    <button class="dz-remove" data-dz-remove><i class="fas fa-times"></i>‚ùå</button>
                </div>`,
        });

        document.getElementById("upload-button").addEventListener("click", function () {
          dropzone.processQueue();
        });

        const response = await fetch("/api/v1/event/<%= params.id %>", {
          method: "GET",
          headers: {
            "Content-Type": "application/json",

            "Authorization": "Bearer " + localStorage.getItem("token")
          }
        });

        if(response.status == 200) {
          const data = await response.json();
          setLoadedColorValue(data.color);
          document.getElementById("Settings.Event.AvatarIcon").style.backgroundImage = `url(${data.avatar_url})`;
          document.getElementById("EventName").value = data.name;
          document.getElementById("EventDescription").value = data.description;
          document.getElementById("EventLocation").value = data.location_address;
          document.getElementById("EventVisibility").value = data.visibility;
          document.getElementById("EventDateApply").value = toDateTimeLocalString(data.date_apply);
          document.getElementById("EventDateStart").value = toDateTimeLocalString(data.date_start);
          document.getElementById("EventDateEnd").value = toDateTimeLocalString(data.date_end);
          document.getElementById("EventMinGroup").value = data.min_group;
        }
      });
    </script>
  </body>
</html>