@inherits Dynamicweb.Rendering.RazorTemplateBase<Dynamicweb.Rendering.RazorTemplateModel<Dynamicweb.Rendering.Template>>
@using Dynamicweb.Environment;

@{
    var categories = CookieManager.GetCategories();

    string cookieNoticeLink = Pageview.AreaSettings.GetLink("CookiePolicyLink") != null ? Pageview.AreaSettings.GetLink("CookiePolicyLink").Url : "";
    string privacyPolicyLink = Pageview.AreaSettings.GetLink("PrivacyPolicyLink") != null ? Pageview.AreaSettings.GetLink("PrivacyPolicyLink").Url : "";
    int cookieNoticePageID = Pageview.AreaSettings.GetLink("CookiePolicyLink") != null ? Pageview.AreaSettings.GetLink("CookiePolicyLink").PageId : 0;
    int privacyPolicyPageID = Pageview.AreaSettings.GetLink("PrivacyPolicyLink") != null ? Pageview.AreaSettings.GetLink("PrivacyPolicyLink").PageId : 0;
    string googleTagManagerID = Pageview.AreaSettings.GetString("GoogleTagManagerID");

    string layout = Pageview.AreaSettings.GetRawValueString("CookieLayout", "modal");

    layout = Pageview.Page.ID == cookieNoticePageID || Pageview.Page.ID == privacyPolicyPageID ? "both" : layout;
}

@if (!Pageview.IsVisualEditorMode) {
    if (layout == "banner" || layout == "both")
    {
        <div class="position-fixed bottom-0 w-100 shadow bg-body" id="dwCookieBanner">
            <div class="align-items-center grid p-3">
                @if (layout == "banner")
                {
                    <div class="g-col-12 g-col-md-6	g-col-lg-8">
                        <span>@Translate("By clicking 'Accept All' you consent that we may collect information about you for various purposes, including: Statistics and Marketing")</span>
                    </div>
                    <div class="g-col-12 g-col-md-6 g-col-lg-4">
                        <div class="grid grid-1 grid-sm-2">
                            <button type="button" onclick="setOptInCookie(2)" class="btn btn-primary" data-dw-button="primary" id="CookiesAcceptAll">
                                @Translate("Accept all")
                            </button>
                            <button type="button" onclick="setOptInCookie(1)" class="btn btn-secondary" data-dw-button="secondary" id="CookiesDeclineAll">
                                @Translate("Decline")
                            </button>
                        </div>
                    </div>
                }
                @if (layout == "both")
                {
                    <div class="g-col-12 g-col-lg-6 g-col-xxl-8">
                        <span>@Translate("By clicking 'Accept All' you consent that we may collect information about you for various purposes, including: Statistics and Marketing")</span>
                    </div>
                    <div class="g-col-12 g-col-lg-6 g-col-xxl-4">
                        <div class="grid grid-1 grid-sm-3">
                            <button type="button" class="btn btn-link" data-bs-toggle="modal" data-bs-target="#dwCookieModal">
                                @Translate("Customize settings")
                            </button>
                            <button type="button" onclick="setOptInCookie(2)" class="btn btn-secondary" data-dw-button="secondary" id="CookiesAcceptAll">
                                @Translate("Accept all")
                            </button>
                            <button type="button" onclick="setOptInCookie(1)" class="btn btn-secondary" data-dw-button="secondary" id="CookiesDeclineAll">
                                @Translate("Decline")
                            </button>
                        </div>
                    </div>
                }
            </div>
        </div>
    }

    if (layout == "modal" || layout == "both")
    {
        <div class="modal fade" id="dwCookieModal">
            <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" style="max-width:560px;">
                <div class="modal-content bg-body">
                    <div style="overflow-y:auto;overflow-x:hidden">
                        <div class="p-3 p-md-4 overflow-auto" style="max-height:50vh;">
                            <div class="h3 mb-3">@Translate("You control your data")</div>
                            <p>@Translate("We and our partners use technologies, including cookies, to collect information about you for various purposes, including"):</p>
                            <ol>
                                <li>@Translate("Functionality")</li>
                                <li>@Translate("Statistics")</li>
                                <li>@Translate("Marketing")</li>
                            </ol>
                            <p>@Translate("By clicking 'Accept All' you consent to all these purposes. You can also choose to indicate what purposes you will consent to using the custom selections and then click 'Accept selected'").</p>

                            @if (!string.IsNullOrEmpty(cookieNoticeLink) || !string.IsNullOrEmpty(privacyPolicyLink))
                            {
                                <p>@Translate("You can read more about our use of cookies and other technologies, as well as our collection and processing of personal data by clicking here"):</p>
                            }

                            @if (!string.IsNullOrEmpty(cookieNoticeLink))
                            {
                                <a href="@cookieNoticeLink" class="d-block mb-3" id="CookiesReadModeAbout">@Translate("Read more about Cookies")</a>
                            }
                            @if (!string.IsNullOrEmpty(privacyPolicyLink))
                            {
                                <a href="@privacyPolicyLink" class="d-block" id="CookiesPrivacyPolicy">@Translate("Our privacy policy")</a>
                            }
                        </div>

                        <div class="p-3 px-md-4 border-top">
                            <div class="grid grid-1 grid-sm-2 gap-3">
                                <button type="button" onclick="setOptInCookie(1)" class="btn btn-secondary" data-bs-dismiss="modal" id="dwCookieDeclineAll">@Translate("Decline")</button>
                                @if (categories.Any())
                                {
                                    <button type="button" onclick="acceptCustomSetup()" class="btn btn-secondary d-none" data-bs-dismiss="modal" id="dwCookieAcceptSelected">@Translate("Accept selected")</button>
                                }
                                <button type="button" onclick="setOptInCookie(2)" class="btn btn-secondary" data-bs-dismiss="modal" id="dwCookieAcceptAll">@Translate("Accept All")</button>
                            </div>
                        </div>

                        @if (categories.Any())
                        {
                            int categoriesCount = 0;
                            int totalCategories = categories.Count();

                            <form id="dwCookieModalCustomForm" method="post" action="/Admin/Public/CookieOptInLevelConfig.aspx">
                                <input type="hidden" name="cmd" value="SetCookieOptInLevel">
                                <input type="hidden" name="OptInLevel" id="OptInLevel" value="1">
                                <div class="grid grid-2 grid-sm-4 gap-0 px-md-3 border-top border-1">
                                    <div class="p-3">
                                        <label class="form-check-label" for="dwCookieNecessary"><span>@Translate("Necessary")</span></label>
                                        <div class="form-check form-switch form-control-lg py-0">
                                            <input class="form-check-input opacity-100" type="checkbox" id="dwCookieNecessary" checked disabled style="background-color: rgba(0,0,0,0.1);">
                                        </div>
                                    </div>
                                    @foreach (var category in categories)
                                    {
                                        string border = categoriesCount < (totalCategories - 1) ? "" : "";

                                        <div class="p-3 @(border)">
                                            <label class="form-check-label" for="CookieCategory_@category"><span>@Translate(category)</span></label>
                                            <div class="form-check form-switch form-control-lg py-0">
                                                <input class="form-check-input js-checkbox" type="checkbox" name="OptInCategory" value="@category" id="CookieCategory_@category" onchange="toggleAcceptSelected()" style="background-color: rgba(0,0,0,0.1);">
                                            </div>
                                        </div>
                                        categoriesCount++;
                                    }
                                </div>
                            </form>
                        }
                    </div>
                </div>
            </div>
        </div>
    }


    <script>
        async function setOptInCookie(optInLevel) {
            let response = await fetch("/admin/public/CookieOptInLevelConfig.aspx?cmd=SetCookieOptInLevel&OptInLevel=" + optInLevel);
            @if (!string.IsNullOrWhiteSpace(googleTagManagerID)){
                <text>
                if (optInLevel == '2') {
                    consentGrantedAll();
                }
                </text>
            }
            
            if (response.ok) {
                if (document.querySelector("#dwCookieBanner")) {
                    document.querySelector("#dwCookieBanner").classList.add("d-none");
                }
                document.location.reload();
                return false;
            } else {
                return false;
            }
        }

        async function acceptCustomSetup() {
            var form = document.querySelector("#dwCookieModalCustomForm");

            let formData = new FormData(form);
            var fetchOptions = {
                method: 'POST',
                body: formData
            };

            for (const value of formData.values()) {
                console.log(value);
                if (value == 'Marketing') {
                    console.log('Granting marketing cookies')
                    consentGrantedMarketing();
                }
                if (value == 'Statistical') {
                    console.log('Granting statistical cookies')
                    consentGrantedAnalyticsStorage();
                }
            }
            

            let response = await fetch(form.action, fetchOptions);

            if (response.ok) {
                if (document.querySelector("#dwCookieBanner")) {
                    document.querySelector("#dwCookieBanner").classList.add("d-none");
                }
                document.location.reload();
                return false;
            } else {
                return false;
            }
        }


        function consentGrantedAll() {
            consentGrantedMarketing();
            consentGrantedAnalyticsStorage();
        }

        function consentGrantedMarketing() {
            consentGrantedAdStorage();
            consentGrantedAdUserData();
            consentGrantedAdPersonalization();
        }

        function consentGrantedAdStorage() {
            if (!window.dataLayer) return;
            gtag('consent', 'update', {
                'ad_storage': 'granted'
            });
        }

        function consentGrantedAdUserData() {
            if (!window.dataLayer) return;
            gtag('consent', 'update', {
                'ad_user_data': 'granted'
            });
        }

        function consentGrantedAdPersonalization() {
            if (!window.dataLayer) return;
            gtag('consent', 'update', {
                'ad_personalization': 'granted'
            });
        }

        function consentGrantedAnalyticsStorage() {
            if (!window.dataLayer) return;
            gtag('consent', 'update', {
                'analytics_storage': 'granted'
            });
        }

        function toggleAcceptSelected() {
            var cookieCalegoriesElement = document.querySelector("#dwCookieModalCustomForm");
            var enableAcceptSelected = false;

            cookieCalegoriesElement.querySelectorAll(".js-checkbox").forEach(function (field) {
                if (field.checked == true) {
                    enableAcceptSelected = true;
                }
            });

            if (enableAcceptSelected) {
                document.querySelector("#dwCookieDeclineAll").classList.add("d-none");
                document.querySelector("#dwCookieAcceptSelected").classList.remove("d-none");
            } else {
                document.querySelector("#dwCookieDeclineAll").classList.remove("d-none");
                document.querySelector("#dwCookieAcceptSelected").classList.add("d-none");
            }
        }

        function showCookieModal() {
            var cookieModal = new bootstrap.Modal(document.querySelector('#dwCookieModal'), {
                backdrop: 'static'
            });
            cookieModal.show();
        }
    </script>

    if (layout == "modal")
    {
        <script type="module">
            showCookieModal();
        </script>
    }
}
