$(document).ready(function () {


    $(".container").on("click", ".add-category-button", function () {
        reloadForm("add-category-form");
    });

    $("#delete-category-form").on("click", "#saveBtn-delete-category", function () {

        sendAjaxRequestWithSuccess("delete-category-form", 'delete-category-modal', reloadCategoryTable, ["categories"]);

    });

    // delete category modal
    $('#categories').on('click', ".delete-category", function (event) {
        let category = $(this).closest('tr').find('td:first').text();
        $('#delete-category-modal').find('.modal-body p').text(`Are you sure you want to delete this category? `)
        $('#delete-category-form').attr('data-url', $(this).attr('data-url'))
    });

    // delete category confirmation
    $('.delete-category').on('click', function (event) {
        $('#delete-category-form').attr('action', $(this).attr('data-url'))
    });


    // add category
    $("#add-category-form").on("click", "#saveBtn-add-category", function () {

        let fields = ["name", "description", "icon"];
        sendAjaxRequest("add-category-form", fields, "add-category-confirm", "add-category-error", reloadCategoryTable, ["categories"]);
        // reloadCategoryTable("categories")

        $('#add-category-modal').on('hidden.bs.modal', function () {
            reloadForm("add-category-form");
        });


    });

    $("#add-category-form").on("click", "#cancelBtn-add-category", function () {
        reloadForm("add-category-form");
    });


    $('#categories').on('click', ".edit-category", function () {
        let url = $(this).data('url');

        $.ajax({
            type: "GET",
            url: url,
            success: function (response) {
                $('#edit-category-modal-container').html(response);
                $('#edit-category-modal').modal('show');


                $("#edit-category-form").on("click", "#saveBtn-edit-category", function () {

                    let fields = ["name", "description", "icon"];
                    sendAjaxRequest("edit-category-form", fields, "edit-category-confirm", "edit-category-error", reloadCategoryTable, ["categories"]);
                });

                $("#edit-category-form").on("click", "#cancelBtn-edit-category", function () {
                    reloadForm("edit-category-form");
                });


            },
        });

    });


});
