<!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.Settings.OAuth.Headline"></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>
        </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 collapse d-md-block 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" 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 active" 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.OAuth"></h2>
                    <span id="page_content"></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <%- html_content.footer %>
      </div>
    </div>
    <div class="modal modal-blur fade" id="modal-create-oauth-client" 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.Settings.OAuth.Create"></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.Settings.OAuth.Name"></label>
                <input type="text" id="NewOAuthClientName" data-translate-placeholder="Events.Settings.OAuth.Sample" class="form-control" />
              </div>
            </div>
            <div class="row mb-3 align-items-end">
              <div class="col">
                <label class="form-label" data-translate="Events.Settings.OAuth.Redirect"></label>
                <input type="text" id="NewOAuthClientRedirect" class="form-control" placeholder="https://example.com/oauth" />
              </div>
            </div>
            <div class="row mb-3">
              <label class="form-label" data-translate="Events.Settings.OAuth.PermissionsLine"></label>
              <div class="col">
                <label class="form-check">
                  <input class="form-check-input" id="USER:ID:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserIdRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserIdRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:ID:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserIdWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserIdWrite"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:USERNAME:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserUsernameRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserUsernameRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:USERNAME:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserUsernameWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserUsernameWrite"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:EMAIL:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserEmailRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserEmailRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:EMAIL:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserEmailWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserEmailWrite"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:REALNAME:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserRealnameRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserRealnameRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:REALNAME:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserRealnameWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserRealnameWrite"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:BIO:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserBioRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserBioRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:BIO:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserBioWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserBioWrite"></span>
                </label>
              </div>
              <div class="col">
                <label class="form-check">
                  <input class="form-check-input" id="EVENTS:LIST:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.EventsListRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.EventsListRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="PROJECTS:LIST:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.ProjectsListRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.ProjectsListRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:AVATAR:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserAvatarRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserAvatarRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:AVATAR:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserAvatarWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserAvatarWrite"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:GROUP:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserGroupRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserGroupRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:GROUP:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserGroupWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserGroupWrite"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:ADDRESS:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserAddressRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserAddressRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:ADDRESS:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.UserAddressWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.UserAddressWrite"></span>
                </label>
              </div>
              <div class="col">
                <label class="form-check">
                  <input class="form-check-input" id="SETTINGS:DESIGN:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.SettingsDesignRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.SettingsDesignRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="SETTINGS:DESIGN:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.SettingsDesignWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.SettingsDesignWrite"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="SETTINGS:LANG:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.SettingsLanguageRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.SettingsLanguageRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="SETTINGS:LANG:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.SettingsLanguageWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.SettingsLanguageWrite"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="INTEGRATION:TELEGRAM:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.IntegrationTelegramRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.IntegrationTelegramRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="INTEGRATION:DISCORD:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.IntegrationDiscordRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.IntegrationDiscordRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="NOTIFICATIONS:READ" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.NotificationsRead"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.NotificationsRead"></span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="NOTIFICATIONS:WRITE" type="checkbox" />
                  <span class="form-check-label" data-translate="OAuth.Permission.Name.NotificationsWrite"></span>
                  <span class="form-check-description" data-translate="OAuth.Permission.Description.NotificationsWrite"></span>
                </label>
              </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="NewoAuthSubmitBtn">
              <!-- 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.Settings.OAuth.AddoAuthClient"></span>
            </a>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fade" id="modal-upload-oavatar" 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-oavatar" 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="deleteOAvatar()" 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>
      const checkboxes_disabled = true;
      const oAuthPermissions = {
        "USER:ID:READ": 1 << 1,
        "USER:ID:WRITE": 1 << 2,
        "USER:USERNAME:READ": 1 << 3,
        "USER:USERNAME:WRITE": 1 << 4,
        "USER:EMAIL:READ": 1 << 5,
        "USER:EMAIL:WRITE": 1 << 6,
        "USER:REALNAME:READ": 1 << 7,
        "USER:REALNAME:WRITE": 1 << 8,
        "USER:BIO:READ": 1 << 9,
        "USER:BIO:WRITE": 1 << 10,
        "USER:AVATAR:READ": 1 << 11,
        "USER:AVATAR:WRITE": 1 << 12,
        "USER:GROUP:READ": 1 << 13,
        "USER:GROUP:WRITE": 1 << 14,
        "USER:ADDRESS:READ": 1 << 15,
        "USER:ADDRESS:WRITE": 1 << 16,
        "SETTINGS:DESIGN:READ": 1 << 17,
        "SETTINGS:DESIGN:WRITE": 1 << 18,
        "SETTINGS:LANG:READ": 1 << 19,
        "SETTINGS:LANG:WRITE": 1 << 20,
        "EVENTS:LIST:READ": 1 << 21,
        "PROJECTS:LIST:READ": 1 << 22,
        "INTEGRATION:TELEGRAM:READ": 1 << 23,
        "INTEGRATION:DISCORD:READ": 1 << 24,
        "NOTIFICATIONS:READ": 1 << 25,
        "NOTIFICATIONS:WRITE": 1 << 26,
      };

      const calculateSelectedPermissionsScope = () => {
        let selectedScope = 0;

        document.querySelectorAll(".form-check-input").forEach((checkbox) => {
          if (checkbox.checked) {
            const permissionKey = checkbox.id;
            if (oAuthPermissions[permissionKey]) {
              selectedScope |= oAuthPermissions[permissionKey];
            }
          }
        });

        return selectedScope;
      };

      // Handle changes to all imput fields (VanillaJS)
      const apiEndpoints = {
        OAuthClientName: {
          endpoint: "/api/v1/oauthapp/<%= params.id %>/oauthclient/name",
          method: "POST",
          field: "oAuthClient_name",
          value: "raw",
        },
        OAuthClientRedirect: {
          endpoint: "/api/v1/oauthapp/<%= params.id %>/oauthclient/redirect_uri",
          method: "POST",
          field: "oAuthClient_redirect_uri",
          value: "raw",
        },
      };

      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");
        }
      };

      document.getElementById("NewoAuthSubmitBtn").addEventListener("click", async () => {
        const name = document.getElementById("NewOAuthClientName").value;
        const redirect_uri = document.getElementById("NewOAuthClientRedirect").value;
        const scope = calculateSelectedPermissionsScope();

        const generateRequest = await fetch("/api/v1/oauthapp/<%= params.id %>/oauthclient", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
          body: JSON.stringify({
            name,
            redirect_uri,
            scope,
          }),
        });

        if (generateRequest.status === 200) {
          const result = await generateRequest.json();
          closeModal("modal-create-oauth-client");
          document.getElementById("page_content").innerHTML = createOAuthHTML(result.result);
        } else if (generateRequest.status === 400) {
          const result = await generateRequest.json();
          console.log(result);
        } else if (generateRequest.status === 500) {
          // Server Error
          alert("Server Error");
        } else {
          // Unknown Error
          alert("Unknown Error");
        }
      });

      document.addEventListener("DOMContentLoaded", async () => {
        // Check if event already has a oauth client and load them
        const hasOauthClient = await fetch("/api/v1/oauthapp/<%= params.id %>/oauthclient", {
          method: "GET",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + localStorage.getItem("token"),
          },
        });

        if (hasOauthClient.status === 200) {
          const oauthClients = await hasOauthClient.json();
          if (oauthClients.result === false) {
            document.getElementById("page_content").innerHTML = `<a href="#" class="btn btn-primary w-100" data-bs-toggle="modal" data-bs-target="#modal-create-oauth-client">${i18next.t("Events.Settings.OAuth.Create")}</a>`;
          } else {
            document.getElementById("page_content").innerHTML = createOAuthHTML(oauthClients.result);
          }
        }
      });

      const isChecked = (userPermissions, permission) => {
        const bitValue = oAuthPermissions[permission];
        return (userPermissions & bitValue) !== 0 ? "checked" : "";
      };

      const createOAuthHTML = (c) => {
        return `<div class="row mb-3 align-items-end">
          ${
            c.client_id && c.client_secret
              ? `<div class="alert alert-success" role="alert">
            <h4 class="alert-title">${i18next.t("Events.Settings.OAuth.NewClientCreated")}</h4>
            <div>
                ClientID: <kbd class="click-to-copy" onclick="copyToClipboard('${c.client_id}')">${c.client_id}</kbd><br>
                Secret: <kbd class="click-to-copy" onclick="copyToClipboard('${c.client_secret}')">${c.client_secret}</kbd>
            </div>
          </div>
          <hr>` : ""
          }
              <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(${c.avatar_url})"></span></div>
                  <div class="col-auto"><a data-bs-toggle="modal" data-bs-target="#modal-upload-oavatar" class="btn">${i18next.t("Events.Settings.Button.SetAvatarIcon")}</a></div>
                  <div class="col-auto"><a data-bs-toggle="modal" data-bs-target="#modal-danger-delete-oavatar" class="btn btn-ghost-danger" id="DelEAvatarIcon">${i18next.t("Events.Settings.Button.DeleteAvatarIcon")}</a></div>
                </div>
              </div>
            </div>
            <div class="row mb-3 align-items-end">
              <div class="col">
                <label class="form-label">${i18next.t("Events.Settings.OAuth.Name")}</label>
                <input type="text" id="OAuthClientName" onchange="handleInputChange(this.id)" placeholder="${i18next.t("Events.Settings.OAuth.Sample")}" value="${c.name}" class="form-control" />
              </div>
            </div>
            <div class="row mb-3 align-items-end">
              <div class="col">
                <label class="form-label">${i18next.t("Events.Settings.OAuth.Redirect")}</label>
                <input type="text" id="OAuthClientRedirect" onchange="handleInputChange(this.id)" class="form-control" placeholder="https://example.com/oauth" value="${c.redirect_url}" />
              </div>
            </div>
            <div class="row mb-3">
              <label class="form-label" data-translate="Events.Settings.OAuth.PermissionsLine"></label>
              <div class="col">
                <label class="form-check">
                  <input class="form-check-input" id="USER:ID:READ" type="checkbox" ${isChecked(c.scope, "USER:ID:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserIdRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserIdRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:ID:WRITE" type="checkbox" ${isChecked(c.scope, "USER:ID:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserIdWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserIdWrite")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:USERNAME:READ" type="checkbox" ${isChecked(c.scope, "USER:USERNAME:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserUsernameRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserUsernameRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:USERNAME:WRITE" type="checkbox" ${isChecked(c.scope, "USER:USERNAME:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserUsernameWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserUsernameWrite")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:EMAIL:READ" type="checkbox" ${isChecked(c.scope, "USER:EMAIL:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserEmailRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserEmailRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:EMAIL:WRITE" type="checkbox" ${isChecked(c.scope, "USER:EMAIL:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserEmailWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserEmailWrite")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:REALNAME:READ" type="checkbox" ${isChecked(c.scope, "USER:REALNAME:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserRealnameRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserRealnameRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:REALNAME:WRITE" type="checkbox" ${isChecked(c.scope, "USER:REALNAME:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserRealnameWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserRealnameWrite")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:BIO:READ" type="checkbox" ${isChecked(c.scope, "USER:BIO:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserBioRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserBioRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:BIO:WRITE" type="checkbox" ${isChecked(c.scope, "USER:BIO:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserBioWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserBioWrite")}</span>
                </label>
              </div>
              <div class="col">
                <label class="form-check">
                  <input class="form-check-input" id="EVENTS:LIST:READ" type="checkbox" ${isChecked(c.scope, "EVENTS:LIST:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.EventsListRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.EventsListRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="PROJECTS:LIST:READ" type="checkbox" ${isChecked(c.scope, "PROJECTS:LIST:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.ProjectsListRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.ProjectsListRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:AVATAR:READ" type="checkbox" ${isChecked(c.scope, "USER:AVATAR:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserAvatarRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserAvatarRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:AVATAR:WRITE" type="checkbox" ${isChecked(c.scope, "USER:AVATAR:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserAvatarWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserAvatarWrite")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:GROUP:READ" type="checkbox" ${isChecked(c.scope, "USER:GROUP:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserGroupRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserGroupRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:GROUP:WRITE" type="checkbox" ${isChecked(c.scope, "USER:GROUP:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserGroupWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserGroupWrite")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:ADDRESS:READ" type="checkbox" ${isChecked(c.scope, "USER:ADDRESS:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserAddressRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserAddressRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="USER:ADDRESS:WRITE" type="checkbox" ${isChecked(c.scope, "USER:ADDRESS:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.UserAddressWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.UserAddressWrite")}</span>
                </label>
              </div>
              <div class="col">
                <label class="form-check">
                  <input class="form-check-input" id="SETTINGS:DESIGN:READ" type="checkbox" ${isChecked(c.scope, "SETTINGS:DESIGN:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.SettingsDesignRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.SettingsDesignRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="SETTINGS:DESIGN:WRITE" type="checkbox" ${isChecked(c.scope, "SETTINGS:DESIGN:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.SettingsDesignWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.SettingsDesignWrite")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="SETTINGS:LANG:READ" type="checkbox" ${isChecked(c.scope, "SETTINGS:LANG:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.SettingsLanguageRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.SettingsLanguageRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="SETTINGS:LANG:WRITE" type="checkbox" ${isChecked(c.scope, "SETTINGS:LANG:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.SettingsLanguageWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.SettingsLanguageWrite")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="INTEGRATION:TELEGRAM:READ" type="checkbox" ${isChecked(c.scope, "INTEGRATION:TELEGRAM:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.IntegrationTelegramRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.IntegrationTelegramRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="INTEGRATION:DISCORD:READ" type="checkbox" ${isChecked(c.scope, "INTEGRATION:DISCORD:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.IntegrationDiscordRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.IntegrationDiscordRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="NOTIFICATIONS:READ" type="checkbox" ${isChecked(c.scope, "NOTIFICATIONS:READ")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.NotificationsRead")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.NotificationsRead")}</span>
                </label>
                <label class="form-check">
                  <input class="form-check-input" id="NOTIFICATIONS:WRITE" type="checkbox" ${isChecked(c.scope, "NOTIFICATIONS:WRITE")} ${checkboxes_disabled ? "disabled" : ""} />
                  <span class="form-check-label">${i18next.t("OAuth.Permission.Name.NotificationsWrite")}</span>
                  <span class="form-check-description">${i18next.t("OAuth.Permission.Description.NotificationsWrite")}</span>
                </label>
              </div>
            </div>
            <div class="row">
              <div class="col-lg-12">
                <div id="NewEventErrorLine"></div>
              </div>
            </div>
            <div class="col-auto" style="float: right;">
              <span>
                <button onclick="deleteOAuthEvent()" class="btn btn-danger">
                  <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-file-x"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M14 3v4a1 1 0 0 0 1 1h4" /><path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z" /><path d="M10 12l4 4m0 -4l-4 4" /></svg>
                  <div>${i18next.t("Events.Settings.OAuth.Delete")}</div>
                </button>
              </span>
            </div>`;
      };

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

        if (response.status == 200) {
          window.location.reload();
        }
      };

      // Delete OAuth Avatar
      const deleteOAvatar = async () => {
        const response = await fetch("/api/v1/oauthapp/<%= params.id %>/oauthclient/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-oavatar");
          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 = "";
      });

      document.addEventListener("DOMContentLoaded", async () => {
        Dropzone.autoDiscover = false;

        const dropzone = new Dropzone("#dropzone-avatar-upload", {
          url: "/api/v1/oauthapp/<%= params.id %>/oauthclient/avatar",
          autoProcessQueue: false,
          acceptedFiles: ".jpg,.jpeg",
          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-oavatar");
            });
          },
          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();
        });
      });
    </script>
  </body>
</html>
