<!DOCTYPE html>
<html lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
    <div>Сотрудники</div>
    <div sec:authorize="hasRole('ROLE_ADMIN')">
        <a class="btn btn-success button-fixed"
           onsubmit="openModalEdit()" data-bs-target="#employeeEditModal" data-bs-toggle="modal">
            <i class="fa-solid fa-plus"></i> Добавить
        </a>
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">ID</th>
                <th scope="col">Фамилия</th>
                <th scope="col">Имя</th>
                <th scope="col">Номер телефона</th>
                <th scope="col">Должности</th>
                <th sec:authorize="hasRole('ROLE_ADMIN')" scope="col">Элементы управления</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="employee, iterator: ${employees}">
                <th scope="row" th:text="${iterator.index} + 1"/>
                <td th:text="${employee.id}"/>
                <td th:text="${employee.surname}" />
                <td th:text="${employee.name}" />
                <td th:text="${employee.phoneNumber}" />
                <td th:text="${#strings.listJoin(employee.positions.![name],',')}"></td>
                <td sec:authorize="hasRole('ROLE_ADMIN')" style="width: 10%">
                    <div class="btn-group" role="group" aria-label="Basic example">
                        <a class="btn btn-info button-fixed button-sm" th:data-employee="${employee.id}"
                           data-bs-target="#employeeEditModal" data-bs-toggle="modal"
                           th:onclick="openModalEdit(this.getAttribute('data-employee'))">
                            Изменить
                        </a>
                        <button type="button" class="btn btn-danger button-fixed button-sm"
                                th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${employee.id}').click()|">
                            Удалить
                        </button>
                    </div>
                    <form th:action="@{/employee/delete/{id}(id=${employee.id})}" method="post">
                        <button th:id="'remove-' + ${employee.id}" type="submit" style="display: none">
                            Удалить
                        </button>
                    </form>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="modal" id="employeeEditModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <form id="form-edit-employee">
                        <input type="hidden" id="employeeId" name="id"/>
                        <div class="mb-3">
                            <label for="surname" class="form-label">Фамилия</label>
                            <input type="text" class="form-control" id="surname" required="true">
                        </div>
                        <div class="mb-3">
                            <label for="name" class="form-label">Имя</label>
                            <input type="text" class="form-control" id="name" required="true">
                        </div>
                        <div class="mb-3">
                            <label for="phoneNumber" class="form-label">Номер телефона</label>
                            <input type="text" class="form-control" id="phoneNumber" required="true">
                        </div>
                        <div class="mb-3">
                            <button type="submit" class="btn btn-primary button-fixed">
                                <span th:if="${id == null}">Добавить</span>
                                <span th:if="${id != null}">Обновить</span>
                            </button>
                            <a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
                                Назад
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<th:block layout:fragment="scripts">
    <script th:inline="javascript">
        function openModalEdit(id) {
            var employees = [[${employees}]];
            var employee = employees.find(x => x.id + '' === id);
            if (employee !== 'undefined') {
                $('#employeeId').val(id);
                $('#surname').val(employee.surname);
                $('#name').val(employee.name);
                $('#phoneNumber').val(employee.phoneNumber);
            }
        }

        $(document).on('submit', '#form-edit-employee', function (e) {
              e.preventDefault();
              var idInput = document.getElementById('employeeId');
              var urlEmployee = 'http://localhost:8080/api/employee';
              let employee = {surname: $('#surname').val(),
                              name: $('#name').val(),
                              phoneNumber: $('#phoneNumber').val()};
              var method = 'POST';
              if (idInput.value !== '') {
                 method = 'PUT';
                 urlEmployee = urlEmployee + '/' + idInput.value;
              }
              $.ajax({
                url: urlEmployee,
                method: method,
                data: JSON.stringify(employee),
                contentType: "application/json;"
              })
              .done(function() {
                location.reload();
              })
              .fail((err) => {
                alert(err);
              });
            });
    </script>
</th:block>
</html>