<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Configuration.aspx.cs" Inherits="GUI.Web.Base.Pages.Wizdom365" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" style="height: 100%;">

<head>

    <title>Administration - LiveTiles Intranet</title>

    <script src="../scriptloader.js?v=<%=GetWizdomVersion%>"></script>

    <script src="../Scripts/msal-browser/msal-browser.js"></script>
    <script src="../Scripts/msal-browser/msalConfig.js"></script>
    <script src="../Scripts/tokenHandlerMsal.js"></script>

    <script type="module">
        var token = "";
        var isSaaS = false;
        var adminDependencies = ["swaggerUi", 'ui.ace'];
        window["adminDependencies"] = adminDependencies;
 <%=WizdomClientSideFeatureToggles%>
       if (wizdomClientSideFeatureToggles && wizdomClientSideFeatureToggles != null && JSON.stringify(wizdomClientSideFeatureToggles) !== "")
        window["wizdomClientSideFeatureToggles"] = wizdomClientSideFeatureToggles;
        var enableCustomModules = "<%=IframeModulesEnabled%>";
        window["enableCustomModules"] = enableCustomModules;
 //var urlSpecificConfigurationEnabled = true;
 var sessionId = "<%=SessionId%>";
        var wizdomVersion = "<%=GetWizdomVersion%>";

        var tokenValidTo = null;
        const sessionStorageKey = "wzTokenValidTo.<%=SPHostUrl%>.<%=SessionId%>";
        const isOnline = <%=isOnline.ToString().ToLower()%>;
        var IsModulesTabAvailable = false;
        var IsCustomModulesTabAvailable = false;

        let msalConfigAuthData = <%=MsalConfigAuth%>
            msalConfigAuthData.redirectUri = window.location.origin + "/Base/WizdomContextProxy.aspx";
        msalConfig.auth = msalConfigAuthData;
        let myMSALObj = new msal.PublicClientApplication(msalConfig);

        async function getModalHtml() {
            let response = await fetch("../Templates/ModalPopupBlocked.html");
            response = await response.text();
            document.getElementById("PopupBlocked").innerHTML = response;
        }
        const tokenHandlerMsal = new TokenHandlerMsal( <%=LoginAuthScopes%>, "<%=SPHostUrl%>", "<%=SessionId%>",
            "", "<%=SPLanguage %>", "<%=SPClientTag%>", "<%=SPProductNumber%>", myMSALObj);
        const contextCreatorInit = async () => {
            try {
                if (!isOnline) {
                    await avaliableTabs();
                    return;
                }
                let urlpopup = "_blank";
                var newWin = window.open(urlpopup,"popup");

                if (!newWin || newWin.closed || typeof newWin.closed == 'undefined') {
                    //alert("popup blocked");
                    await getModalHtml();
                    return;
                }
                newWin.close();
                //var validateTokenResp = await isTokenValid();
                // if (!validateTokenResp.IsTokenValid) {
              
                await tokenHandlerMsal.msalGenerateToken();
                await getUserRoles();
                await avaliableTabs();
                await getUserProfilePicture();
                //}
            } catch (error) {
                console.error(error);
            } 
        };

        async function avaliableTabs() {
            const isOnline = <%=isOnline.ToString().ToLower()%>;

            const token = isOnline ? await tokenHandlerMsal.msalGenerateToken() : "";


            //let loginName = window["loginName"];

            let url = window.location.origin + "/Base/Pages/Configuration.aspx/avaliableTabs";
            const headers = {
                "Content-Type": "application/json",
                "SPProductNumber": "<%=SPProductNumber%>",
                "sessionId": "<%=SessionId%>"
            };

            // Só adiciona o Authorization se a variável permitir
            if (isOnline && token) {
                headers["Authorization"] = `Bearer ${token}`;
            }
            let response = await fetch(url, {
                method: "GET", // *GET, POST, PUT, DELETE, etc.
                mode: "cors", // no-cors, *cors, same-origin
                cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
                credentials: "same-origin", // include, *same-origin, omit
                headers: headers,
                redirect: "follow", // manual, *follow, error
                referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url

            });
            response = await response.json();
            response = response.d;
            if (!response.IsModulesTabAvailable) {
                document.getElementById("liIsModuleTabAvaliable").outerHTML = '';
            }
            if (!response.IsCustomModulesTabAvailable) {
                document.getElementById("liIsCustomModulesTabAvailable").outerHTML = '';
            }
            if (!response.IsAdminTabAvailable) {
                document.getElementById("liIsAdminTabAvailable").outerHTML = '';
            }

            return response;
        }

        async function getUserRoles() {
            const loginName = sessionStorage.getItem("wizdomLoginName");

            if (!loginName) {
                console.warn("User login name is not available. Cannot fetch roles.");
                return [];
            }
            try {
                const response = await fetch("/Base/WizdomCorsProxy.aspx/GetRolesForUser", {
                    method: "POST",
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ userLoginName: loginName }),
                });
                const data = await response.json();
                localStorage.setItem("Wizdom365RolesForCurrentUser", data.d);
                return data.d;
            } catch (error) {
                console.error("Erro to fetch roles:", error);
                return [];
            }
        };

        async function getUserProfilePicture() {
            const isOnline = <%=isOnline.ToString().ToLower()%>;
            const token = isOnline ? await tokenHandlerMsal.msalGenerateToken() : "";
            const loginName = sessionStorage.getItem("wizdomLoginName");
            let hostUrl = "<%=SPHostUrl %>";
            let url = window.location.origin + `/Base/Pages/Configuration.aspx/getUserProfilePicture?accountName=${loginName}&SPHostUrl=${hostUrl}`;
            
            const headers = {
                "Content-Type": "application/json",
                "SPProductNumber": "<%=SPProductNumber%>",
                "sessionId": "<%=SessionId%>"
            };

            // Só adiciona o Authorization se a variável permitir
            if (isOnline && token) {
                headers["Authorization"] = `Bearer ${token}`;
            }

            let response = await fetch(url, {
                method: "POST", // *GET, POST, PUT, DELETE, etc.
                mode: "cors", // no-cors, *cors, same-origin
                cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
                credentials: "same-origin", // include, *same-origin, omit
                headers: headers,
                redirect: "follow", // manual, *follow, error
                referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
                body: JSON.stringify({ accountName: loginName, SPHostUrl: hostUrl }),
            });
            response = await response.json();
            response = response.d;
            
            // Update DOM elements with fetched user data
            if (response) {
                // Update user avatar
                if (response) {
                    const avatarImg = document.getElementById("wizdom-current-user-avatar");
                    if (avatarImg) {
                        avatarImg.src = response;
                        avatarImg.style.padding = "0";
                    }
                }
                
                // Update username - prefer response data, fallback to session storage
                const userName = sessionStorage.getItem("wizdomDisplayName") || sessionStorage.getItem("wizdomLoginName");
                if (userName) {
                    const userNameBtn = document.getElementById("wizdom-current-user-name");
                    if (userNameBtn) {
                        userNameBtn.textContent = userName;
                    }
                }
            }
        }

      
        if (<%=isReadyToLoad.ToString().ToLower()%>) {
            await contextCreatorInit();
            await wizdomInject(
                wizdomVersion,
                "/",
            <%=string.IsNullOrEmpty(BlobUrl) ? "null":"\"" + BlobUrl + "\"" %>,
                true,
                true,
                false,
            <%= PartnerModulesBundle%>,
                null,
                null,
                [],
                null,
            <%= InternalModules%>,
                null,
                isOnline
            );

        }

    </script>
</head>

<body ng-cloak style="margin: 0; height: 100%;" id="bodyId">
    <div class="wizdom display-table" ng-controller="Wizdom365SuitebarController">
        <div class="wizdom-fixed-row">
            <div class="wizdom-header">
                <div class="wizdom-header-logo">
                    <div class="wizdom-header-title pull-left"></div>
                    <span>{{'v.' + version}}</span>
                    <p ng-hide="statusIcon==''" class="wizdom-header-version-status pull-left">
                        <i ng-class="statusIcon" title="{{statusText}}"></i>
                    </p>
                </div>
                <div class="wizdom-user pull-right">
                    <img id ="wizdom-current-user-avatar" src="<%=UserPictureUrl%>" class="user-photo" onerror="this.style.padding='18px'" />
                    <button id ="wizdom-current-user-name" class="btn btn-link"><%=Username%></button>
                </div>
            </div>
        </div>
        <div class="wizdom-fixed-row" ng-if="fullConfigLoaded">
            <nav class="navbar navbar-default">
                <ul class="nav wizdom-navbar-nav">
                    <li ng-class="{active:isActive('Home.html')}" ng-click='setContent("Home.html")'>
                        <a href=""><i class="streamline icon-house-1 wizdom-navbar-icon"></i><span class="wizdom-navbar-text">{{'Home' | translate}}</span></a>
                    </li>
                    <li ng-class="{active:isActive('Support.html')}" ng-click='setContent("Support.html")'>
                        <a href=""><i class="streamline icon-headphones-customer-support wizdom-navbar-icon"></i><span class="wizdom-navbar-text">{{'Support' | translate}}</span></a>
                    </li>


                    <li ng-class="{active:isActive('Modules.html')}" ng-click='setContent("Modules.html")' id="liIsModuleTabAvaliable">
                        <a href=""><i class="streamline icon-module-puzzle wizdom-navbar-icon"></i><span class="wizdom-navbar-text">{{'Modules' | translate}}</span></a>
                    </li>

                    <li ng-class="{active:isActive('CustomModules.html')}" ng-click='setContent("CustomModules.html")' id="liIsCustomModulesTabAvailable">
                        <a href=""><i class="streamline icon-module-hand-puzzle wizdom-navbar-icon"></i><span class="wizdom-navbar-text">{{'Custom modules' | translate}}</span></a>
                    </li>


                    <%--  <% if (IsAnalyticsTabAvailable)
                       { %>
                    <li ng-class="{active:isActive('Analytics')}" ng-click='setContent("Analytics.html")'>
                        <a href=""><i class="glyphicon glyphicon-calendar wizdom-navbar-icon"></i><span class="wizdom-navbar-text">{{'Analytics' | translate}}</span></a>
                    </li>
                    <% } %>--%>


                    <li ng-class="{active:isActive('Administration.html')}" ng-click='setContent("Administration.html")' id="liIsAdminTabAvailable">
                        <a href=""><i class="streamline icon-cog-double-2 wizdom-navbar-icon"></i><span class="wizdom-navbar-text">{{'Admin' | translate}}</span></a>
                    </li>


                    <li class="ml-auto">
                        <a href="<%=SPHostUrl %>">
                            <i class="streamline icon-logout-2 wizdom-navbar-icon"></i>
                            <span class="wizdom-navbar-text">{{'Back to Sharepoint' | translate}}</span>
                        </a>
                    </li>
                    <li ng-if>
                        <a href="" ng-click='setContent("Support.html")'>
                            <i class="streamline icon-headphones-customer-support wizdom-navbar-icon wizdom-navbar-icon-empty"></i>
                        </a>
                    </li>
                </ul>
            </nav>
            <wizdom365-license-status></wizdom365-license-status>
        </div>
        <div class="wizdom-flex-row" ng-if="fullConfigLoaded || fullConfigNotAllowed">
            <div class="container-fluid full-height wizdom-fixed-cell" wizdom-include='pageUrl'></div>
        </div>
      
    </div>
      <div id="PopupBlocked"></div>
</body>

</html>
