<!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="#companyEditModal" 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 sec:authorize="hasRole('ROLE_ADMIN')" scope="col">Элементы управления</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="company, iterator: ${companies}">
                <th scope="row" th:text="${iterator.index} + 1"/>
                <td th:text="${company.id}"/>
                <td style="width: 60%"><a th:href="@{/company/one/{id}(id=${company.id})}" th:text="${company.name}"></a></td>
                <td th:text="${#arrays.length(company.employees.toArray())}" style="width: 60%"/>
                <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-company="${company.id}"
                            data-bs-target="#companyEditModal" data-bs-toggle="modal"
                           th:onclick="openModalEdit(this.getAttribute('data-company'))">Изменить</a>
                        <button type="button" class="btn btn-danger button-fixed button-sm"
                                th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${company.id}').click()|">
                            Удалить
                        </button>
                    </div>
                    <form th:action="@{/company/delete/{id}(id=${company.id})}" method="post">
                        <button th:id="'remove-' + ${company.id}" type="submit" style="display: none">
                            Удалить
                        </button>
                    </form>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    <!-- Modal -->
    <div class="modal" id="companyModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Выбор компании</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form action="/company/redirect" method="post">
                        <div class="mb-3">
                            <label class="form-label"  for="companySelect">Компания</label>
                            <select class="form-select"  id="companySelect" name="companyId" required>
                                <option selected disabled>Выберите компанию</option>
                                <option th:each="company, iterator: ${companies}" th:value="${company.id}" th:text="${company.name}">
                                </option>
                            </select>
                        </div>

                        <button class="btn btn-primary" type="submit">Перейти</button>
                        <a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
                            Назад
                        </a>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="companyEditModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <form id="form-edit-company">
                        <input type="hidden" id="companyId" name="id"/>
                        <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">
                            <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 companies = [[${companies}]];
            var company = companies.find(x => x.id + '' === id);
            if (company !== 'undefined') {
                $('#companyId').val(id);
                $('#name').val(company.name);
            }
        }

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