<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles/main.css">
    <script src="../scripts/jquery.min.js"></script>
    <script src="../scripts/helpPopup.js"></script>
    <title>Настройки профиля</title>
    <style>
        body {
            background-color: #EEEFF5;
        }
    </style>
</head>
<body>
    <header>
      <a href="/account"><h1>Бюро пропусков / Личный кабинет</h1></a>
      <nav>
            <div class="dropdown">
                <a class="help-button" onclick="toggleDropdown('dropdownHelp-1')">Техническая поддержка</a>               
                <div id="dropdownHelp-1" class="dropdown-help">
                    <a href="tel:83477527706">8 (34775) 2-77-06</a>
                    <a href="tel:89174023516">8 (917) 402-35-16</a>
                </div>
              </div>
            <div class="dropdown">
                <a class="help-button" onclick="toggleDropdown('dropdownHelp-2')">Инструкции</a>               
                <div id="dropdownHelp-2" class="dropdown-help dropdown-manual">
                    <a href="/docs/manual.pdf" target="_blank">Текст</a>
                    <a href="https://drive.google.com/file/d/1CxrAgr2brQclZqtbbreSUU9tN-jsNTwf/view?usp=sharing" target="_blank">Видео</a>
                </div>
              </div>
            {{#if (eq Role 'legal')}}
            <span>{{User.Наименование}}</span>
            {{else}}
            <span>{{User.Фамилия}} {{User.Имя}} {{User.Отчество}}</span>
            {{/if}}
            <a class="exit-button" href="/logout"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="16" fill="none" viewBox="0 0 20 16">
                <path fill="#6B7A99" d="m4.016 7.13 2.608-2.606-1.226-1.226L.696 8l4.702 4.702 1.226-1.226L4.016 8.87h4.858V7.131H4.016ZM8.874.179v6.953h5.215V8.87H8.874v6.953h10.43V.178H8.873Z"/>
              </svg>
              </a>
        </nav>
    </header>
    
    <form id="update-form" autocomplete="off">
    <section class="main-content">
        <h1>Редактирование профиля</h1>
        <div class="hub-bg settings-area">
            {{#if (eq Role 'legal')}}
            <div class="input-area">
                <label for="name-input">Наименование организации*</label>
                <input type="text" id="name-input" value="{{User.Наименование}}">
            </div>
            <div class="input-area">
                <label for="inn-input">ИНН*</label>
                <input maxlength="10" type="text" id="inn-input" value="{{User.ИНН}}" required>
            </div>
            <div class="input-area">
                <label for="ogrn-input">ОГРН*</label>
                <input maxlength="13" type="text" id="ogrn-input" value="{{User.ОГРН}}" required>
            </div>
            <div class="input-area">
                <label for="legaladdress-input">Юридический адрес*</label>
                <input type="text" id="legaladdress-input" value="{{User.Юридический_адрес}}" required>
            </div>
            <div class="input-area">
                <label for="address-input">Фактический адрес*</label>
                <input type="text" id="address-input" value="{{User.Фактический_адрес}}" required>
            </div>
            <div class="input-area">
                <label for="contact-input">Имя контактного лица</label>
                <input type="text" id="contact-input" value="{{User.Контактное_лицо}}">
            </div>
            <div class="input-area">
                <label for="contactphone-input">Номер телефона контактного лица</label>
                <input type="text" id="contactphone-input" value="{{User.Телефон}}">
            </div>
            {{else}}
            <div class="input-area">
                <label for="surname-input">Фамилия*</label>
                <input type="text" id="surname-input" value="{{User.Фамилия}}" required>
            </div>
            <div class="input-area">
                <label for="firstname-input">Имя*</label>
                <input type="text" id="firstname-input" value="{{User.Имя}}" required>
            </div>
            <div class="input-area">
                <label for="secondname-input">Отчество (при наличии)</label>
                <input type="text" id="secondname-input" value="{{User.Отчество}}">
            </div>
            <div class="input-area">
                <label for="born-input">Дата рождения*</label>
                <input type="date" id="born-input">
            </div>
            <div class="input-area">
                <label for="phone-input">Номер телефона</label>
                <input type="text" id="phone-input" value="{{User.Телефон}}">
            </div>
            <div class="input-area">
                <label for="bornplace-input">Место рождения</label>
                <input type="text" id="bornplace-input" value="{{User.Место_рождения}}">
            </div>
            <div class="input-area">
                <label for="passport-input">Серия и номер паспорта</label>
                <input type="text" id="passport-input" value="{{User.Паспорт}}">
            </div>
            <div class="input-area">
                <label for="citizenship-input">Гражданство</label>
                <input type="text" id="citizenship-input" value="{{User.Гражданство}}">
            </div>
            <div class="input-area">
                <label for="regaddress-input">Место регистрации</label>
                <input type="text" id="regaddress-input" value="{{User.Место_регистрации}}">
            </div>
            <div class="input-area">
                <label for="realaddress-input">Место жительства</label>
                <input type="text" id="realaddress-input" name="address" autocomplete="off" value="{{User.Место_жительства}}">
            </div>
            <div class="input-area">
                <label for="dms-input">Полис ДМС</label>
                <input type="text" id="dms-input" value="{{User.Полис_ДМС}}">
            </div>
            {{/if}}
            <div class="input-area">
                <label for="password-input">Новый пароль (Опционально)</label>
                <input type="password" id="password-input" name="new-password" autocomplete="new-password" new-password>
            </div>

            <button id="update-button">Сохранить</button>

        </div>
    </section>
    </form>
    <script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.js"></script>
    <script>
        $(document).ready(function(){
      
            $('#phone-input').inputmask({"mask": "+7 (999) 999-9999"});
            $('#contactphone-input').inputmask({"mask": "+7 (999) 999-9999"});
      
        });
      </script>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            function formatDateForDateInput(dateString, inputId) {
                const date = new Date(dateString);
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                const formattedDate = `${year}-${month}-${day}`;

                document.getElementById(inputId).value = formattedDate;
            }

            formatDateForDateInput("{{User.Дата_рождения}}", "born-input");

        });
    </script>

<script>
                function getCookie(name) {
            var cookies = document.cookie.split(";");
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                if (cookie.startsWith(name + "=")) {
                return cookie.substring(name.length + 1);
                }
            }
            return null;
            }
    document.addEventListener("DOMContentLoaded", function() {
        const updateForm = document.getElementById("update-form");

        updateForm.addEventListener("submit", async function(event) {
            event.preventDefault();
            $('#update-button').addClass('inactive');

            {{#if (eq Role 'legal')}}
                const name = $('#name-input').val();
                const inn = $('#inn-input').val();
                const ogrn = $('#ogrn-input').val();
                const legaladdress = $('#legaladdress-input').val();
                const address = $('#address-input').val();
                const contact = $('#contact-input').val();
                const contactphone = $('#contactphone-input').val();

                const password = $('#password-input').val();

                    const response = await fetch("{{API_SERVER}}/account/update", {
                        method: "PUT",
                        headers: {
                            "Content-Type": "application/json",
                            Authorization: getCookie("token"),
                        },
                        body: JSON.stringify({ name, inn, ogrn, legaladdress, address, contact, contactphone, password })
                    });
            {{else}}
                const surname = $('#surname-input').val();
                const firstname = $('#firstname-input').val();
                const secondname = $('#secondname-input').val();
                const born = $('#born-input').val();
                const phone = $('#phone-input').val();
                const bornplace = $('#bornplace-input').val();
                const passport = $('#passport-input').val();
                const citizenship = $('#citizenship-input').val();
                const regaddress = $('#regaddress-input').val();
                const realaddress = $('#realaddress-input').val();
                const dms = $('#dms-input').val();

                const password = $('#password-input').val();

                    const response = await fetch("{{API_SERVER}}/account/update", {
                        method: "PUT",
                        headers: {
                            "Content-Type": "application/json",
                            Authorization: getCookie("token"),
                        },
                        body: JSON.stringify({ surname, firstname, secondname, born, phone, bornplace, passport, citizenship, regaddress, realaddress, dms, password })
                    });
            {{/if}}


                    if (response.status === 201) {
                        window.location.href = "/account";
                        $('#update-button').removeClass('inactive');
                    } else {
                        alert("Ошибка обновления данных");
                        $('#update-button').removeClass('inactive');
                    }
        });
    });

</script>
</body>
</html>