{if $access['roles.manage']}

<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#roleModal" onclick="openCreateRoleModal()">Добавить роль</button>

<div class="modal fade" id="roleModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="roleForm" method="post">
                <div class="modal-header">
                    <h5 class="modal-title" id="roleModalTitle">Добавить роль</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">

                    <input type="hidden" id="role_id" name="id">

                    <div class="mb-3">
                        <label class="form-label">Название роли (на латинском)</label>
                        <input type="text" name="name" id="role_name" class="form-control" placeholder="Director">
                        <div class="text-danger small" id="error-name"></div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Родительская роль</label>
                        <select name="parent_id" id="parent_id" class="form-select">
                            <option value="">Нет</option>
                            {foreach $roles as $role}
                                <option value="{$role.id}">{$role.name}</option>
                            {/foreach}
                        </select>
                        <div class="text-danger small" id="error-parent"></div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Описание</label>
                        <textarea name="description" id="role_description" class="form-control"></textarea>
                    </div>

                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
                    <button type="submit" class="btn btn-primary" id="roleSubmitBtn">Сохранить</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="col-12">
	{include file='main/datatable.tpl' tableTitle="Все роли:"
	theads=["id", "name", "description", "created_at", "actions"]
	data=$roles }
</div>

<script>

	$(document).ready(function() {

		$(document).on("click", ".delete-ico", function (e) {
			e.preventDefault();

			const dataId = $(this).data("id");

			if (!confirm("Вы уверены, что хотите удалить роль?")) {
				return;
			}

			$.ajax({
				url: 'engine/ajax/lib/rolesAndRights/delete_role.php',
				type: 'POST',
				dataType: 'json',
				data: {literal} {id: dataId} {/literal},
				success: function (response) {

					if (response) {
						window.location.reload();
					} else {

					}

				},
				error: function (xhr, status, error) {
					return;
				}
			});
		});

		$(".edit-ico").on("click", function () {
			debugger;

			const dataId = $(this).data("id");

			if (dataId) {
				$.ajax({
					url: 'engine/ajax/lib/rolesAndRights/get_role_data.php',
					type: 'POST',
					dataType: 'json',
					data: {literal}{id: dataId} {/literal},
					success: function (response) {

						if (response) {
							openEditRoleModal(response)
						}

					},
					error: function (xhr, status, error) {
						return;
					}
				});
			}
		});


        $("#roleForm").on("submit", function(e) {
            debugger;
            e.preventDefault();

            let formData = $(this).serialize();
            let id = $("#role_id").val();
            let url = id ? "engine/ajax/lib/rolesAndRights/update_role.php" : "engine/ajax/lib/rolesAndRights/create_role.php";

            $(".text-danger.small").text(""); // сброс ошибок

            $.ajax({
                url: url,
                type: "POST",
                data: formData,
                dataType: "json",
                success: function(response) {
                    if (response.success) {
                        location.reload(); // или обнови таблицу
                    } else if (response.errors) {
                        $.each(response.errors, function(field, msg) {
                            $("#error-" + field).text(msg);
                        });
                    }
                }
            });
        });

        function openEditRoleModal(role) {
            $("#roleModalTitle").text("Редактировать роль");

            $("#role_id").val(role.id);
            $("#role_name").val(role.name);
            $("#parent_id").val(role.parent_id ?? "");
            $("#role_description").val(role.description ?? "");

            $(".text-danger.small").text("");
            $("#roleModal").modal("show");
        }
    });
    function openCreateRoleModal() {
        $("#roleModalTitle").text("Создать роль");
        $("#roleForm")[0].reset();
        $("#role_id").val("");
        $(".text-danger.small").text("");
        $("#roleModal").modal("show");
    }
</script>

    {else}
    <h3>Доступ запрещен</h3>
{/if}
<script>
    var usersSection = document.getElementById('usersSection');
    usersSection.classList.add('active');
    var usersBlock = document.getElementById('usersBlock');
    usersBlock.classList.add('show');
    var currentLink = document.getElementById('allRoles');
    currentLink.classList.add('active');
</script>