<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#subjectModal" onclick="openCreateSubjectModal()">Добавить предмет</button>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#subjectAssignTeacherModal" onclick="openCreateSubjectModal()">Привязать предмет к учителю</button>

<div class="modal fade" id="subjectModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="subjectForm" method="post">
                <div class="modal-header">
                    <h5 class="modal-title" id="subjectModalTitle">Добавить предмет</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">

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

                    <div class="mb-3">
                        <label for="subject" class="form-label">Название предмета *</label>
                        <input type="text" name="subject" id="subject" class="form-control" placeholder="">
                        <div class="text-danger small" id="error-subject"></div>
                    </div>

                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{$lang.general.close}</button>
                    <button type="submit" class="btn btn-primary" id="subjectSubmitBtn">{$lang.general.save}</button>
                </div>
            </form>
        </div>
    </div>
</div>


<div class="modal fade" id="subjectAssignTeacherModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="subjectAssignTeacherForm" method="post">
                <div class="modal-header">
                    <h5 class="modal-title" id="subjectAssignTeacherModalTitle">Добавить предмет</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">

                    <input type="hidden" id="subjectAssignTeacher_id" name="id">
                    <div class="mb-3">
                        <label for="selected_subject" class="form-label">Subject *</label>
                        <select name="selected_subject" class="form-select">
                            <option value="" disabled selected>{$lang.general.select_class}</option>
                            {foreach $subjects as $subject}
                                <option value="{$subject.id}">{$subject.subject}</option>
                            {/foreach}
                        </select>
                        <div class="text-danger small" id="1-error-selected_subject"></div>

                    </div>
                    <div class="mb-3">
                        <label class="form-label">{$lang.education.teacher_list} *</label>
                        <select name="selected_teacher" class="form-select">
                            <option value="" disabled selected>{$lang.general.select_teacher}</option>
                            {foreach $teachers as $teacher}
                                <option value="{$teacher.id}">{$teacher.name}</option>
                            {/foreach}
                        </select>
                        <div class="text-danger small" id="1-error-selected_teacher"></div>

                    </div>

                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{$lang.general.close}</button>
                    <button type="submit" class="btn btn-primary" id="subjectSubmitBtn">{$lang.general.save}</button>
                </div>
            </form>
        </div>
    </div>
</div>


<div class="col-12">
    {include file='main/datatable.tpl' tableTitle="Все предметы"
    theads=["id", $lang.datatable.name, $lang.datatable.actions]
    data=$subjects }
</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/education/subjects/delete_subject.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/education/subjects/get_subject_data.php',
                    type: 'POST',
                    dataType: 'json',
                    data: {literal}{id: dataId} {/literal},
                    success: function (response) {

                        if (response) {
                            openEditSubjectModal(response)
                        }

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

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

            let formData = $(this).serialize();
            let id = $("#class_id").val();
            let url = id ? "engine/ajax/lib/education/update_school_class.php" : "engine/ajax/lib/education/subjects/attach_teacher_subject.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) {
                            $("#1-error-" + field).text(msg);
                        });
                    }
                }
            });
        });


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

            let formData = $(this).serialize();
            let id = $("#subject_id").val();
            let url = id ? "engine/ajax/lib/education/subjects/update_subject.php" : "engine/ajax/lib/education/subjects/create_subject.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 openEditSubjectModal(school_class) {
            $("#subjectModalTitle").text("Редактировать предмет");

            $("#subject_id").val(school_class.id);
            $("#subject").val(school_class.subject);

            $(".text-danger.small").text("");
            $("#subjectModal").modal("show");
        }
    });
    function openCreateTeacherModal() {
        $("#subjectModalTitle").text("Создать предмет");
        $("#subjectForm")[0].reset();
        $("#subject_id").val("");
        $(".text-danger.small").text("");
        $("#subjectModal").modal("show");
    }
</script>