"use strict";

let endpoint = {
    form: "modeleForm",
    set: "modeleSet",
    get: "modeleGet",
    delete: "modeleDelete",
};

// Datatable
let datatable = "modeleDataTableID";

// Variable for the main page
let modal = {
    modal: "modeleModalID",
    content: "modeleContentModalID",
};

// Variable for the form
let form = "modeleFormID";
let button = {
    save: "modeleSaveData",
    close: "modeleCloseForm",
    add: "modeleADD",
    delete: "modeleDELETE",
    fresh: "modeleFresh",
};

// Class definition
var ModeleDatatableServerSide = (function () {
    // Shared variables
    var dt;

    // Private functions
    var initDatatable = function () {
        dt = $(`#${datatable}`).DataTable({
            language: {
                info: "Affichage de _START_ - _END_ sur _TOTAL_",
                infoEmpty: "Aucune donnée disponible",
                search: "Rechercher:",
                processing: "Chargement...",
                paginate: {
                    first: "Premier",
                    last: "Dernier",
                    next: "Suivant",
                    previous: "Précédent",
                },
                zeroRecords: "Aucun enregistrement trouvé",
                loadingRecords: "Chargement...",
                buttons: {
                    colvis: "Visibilité",
                },
            },
            searchDelay: 500,
            processing: true,
            serverSide: true,
            order: [[1, "desc"]],
            stateSave: true,
            select: {
                style: "multi",
                selector: 'td:first-child input[type="checkbox"]',
                className: "row-selected",
            },
            ajax: {
                type: "POST",
                // data: function(d) {
                //     d.status = statusID;
                // },
                url: hostUrl + 'general/' + endpoint.get,
                dataType: "json",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                        "content"
                    ),
                },
            },
            columns: [
                { data: "name" }, 
                { data: "brand" }, 
                { data: null }],
            columnDefs: [
                {
                    targets: 0,
                    orderable: false,
                    render: function (data, type, row) {
                        return `<a href="javascript:;" class="text-primary text-uppercase ${button.add}" data-row="${row.id}" data-bs-toggle="modal" data-bs-target="#${modal.modal}">${data}</a>`;
                    },
                },
                {
                    targets: 1,
                    orderable: false,
                    render: function (data, type, row) {
                        return `<a href="javascript:;" class="text-dark text-uppercase ">${data.name}</a>`;
                    },
                },
                {
                    targets: -1,
                    data: null,
                    orderable: false,
                    className: "text-center",
                    render: function (data, type, row) {
                        return `
                        <a href="#" class="" data-kt-menu-trigger="click" data-kt-menu-placement="bottom-end" data-kt-menu-flip="top-end">
                        <i class="ki-duotone ki-text-align-center text-danger fs-3">
                        <span class="path1"></span>
                        <span class="path2"></span>
                        <span class="path3"></span>
                        <span class="path4"></span>
                        </i>
                        </a>
                        <!--begin::Menu-->
                        <div class="menu menu-sub menu-sub-dropdown menu-column menu-rounded menu-gray-600 menu-state-bg-light-primary fw-bold fs-7 w-125px py-4" data-kt-menu="true">
                            <!--begin::Menu item-->
                            <div class="menu-item px-3">
                                <a href="#" class="menu-link px-3 fw-light ${button.add}" data-row="${data.id}" data-bs-toggle="modal" data-bs-target="#${modal.modal}">
                                    Modifier
                                </a>
                            </div>
                            <!--end::Menu item-->

                            <!--begin::Menu item-->
                            <div class="menu-item px-3">
                                <a href="#" class="menu-link px-3 fw-light ${button.delete}" data-row="${data.id}">
                                    Supprimer
                                </a>
                            </div>
                            <!--end::Menu item-->
                        </div>
                        <!--end::Menu-->
                        `;
                    },
                },
            ]
        });

        // Re-init functions on every table re-draw -- more info: https://datatables.net/reference/event/draw
        dt.on("draw", function () {
            KTMenu.createInstances();
        });
    };

    // Search Datatable --- official docs reference: https://datatables.net/reference/api/search()
    var handleSearchDatatable = function () {
        const filterSearch = document.querySelector(
            '[data-kt-docs-table-filter="search"]'
        );
        filterSearch.addEventListener("keyup", function (e) {
            dt.search(e.target.value).draw();
        });
    };

    // Get form dat
    let initPostAjaxRequest = () => {
        // Set block up
        var target = document.querySelector(`#${form}`);
        var blockUI = new KTBlockUI(target, {
            message:
                '<div class="blockui-message text-primary text-uppercase fw-light"><span class="spinner-border"></span> Chargement...</div>',
        });
        blockUI.block();

        // Set ajax request
        var formData = new FormData(document.querySelector(`#${form}`));
        $.ajax({
            type: "POST",
            url: hostUrl + 'general/' + endpoint.set,
            data: formData,
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            },
            cache: false,
            contentType: false,
            processData: false,
            success: (data) => {
                // console.log(data);
                let responseJSON = JSON.parse(data);

                // Unblock
                blockUI.release();
                blockUI.destroy();

                if (responseJSON.success) {
                    // hide modal
                    $(`#${modal.modal}`).modal("hide");

                    // return message
                    toastr.success(responseJSON.message);

                    // reload
                    dt.draw();
                } // end if
                else {
                    $.each(responseJSON.response, function (value) {
                        toastr.error(value);
                    });
                }
            },
            error: function (data) {
                /* unlock bloc ui*/
                blockUI.release();
                blockUI.destroy();

                /* Set error messages */
                let responseJSON = JSON.parse(data.responseText);
                let errors = responseJSON.errors;

                // console.log(errors);
                $.each(errors, function (key, value) {
                    toastr.error(value);
                });
            },
        });
    };

    // Refresh data table
    $(document).on("click", `.${button.fresh}`, function (e) {
        // Prevent event
        e.preventDefault();

        // reload
        dt.draw();
    });

    // load the form content into the modal by clicking on the button
    $(document).on("click", `.${button.add}`, function () {
        // Try to get the clicked row rowID
        let rowID = $(this).attr("data-row");

        // ajax request
        $.ajax({
            url: hostUrl + 'general/' + endpoint.form,
            type: "POST",
            data: {
                rowID: rowID,
            },
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
            },
            // datatype: "json",
            success: function (data) {
                $(`#${modal.modal} #${modal.content}`).html(data);

                // Init select2
                $(`#${modal.modal} #${modal.content} #select`).select2();
                $(`#${modal.modal} #${modal.content} #equipmenttype`).select2();
            },
        });
    });

    // Submit data if user click on submit btn
    $(document).on("click", `#${button.save}`, function (e) {
        e.preventDefault();
        initPostAjaxRequest();
    });

    // Submit data if user tape enter to submit
    $(document).on("submit", `#${form}`, function (e) {
        e.preventDefault();
        initPostAjaxRequest();
    });

    $(document).on("click", `.${button.delete}`, function (e) {
        // preventDefault
        e.preventDefault();

        // obtain the value of the first column to be delete
        const o = e.target.closest("tr"),
            n = o.querySelectorAll("td")[0].innerText;

        // Get row ID
        let rowID = $(this).attr("data-row");

        //  init Swal
        Swal.fire({
            text: "Confirmez-vous votre intention de supprimer " + n + " ?",
            icon: "warning",
            showCancelButton: !0,
            buttonsStyling: !1,
            confirmButtonText: "Oui, je confirme !",
            cancelButtonText: "Non, annuler",
            customClass: {
                confirmButton: "btn fw-bold btn-danger",
                cancelButton: "btn fw-bold btn-light-primary",
            },
        }).then(function (e) {
            e.value
                ? $.ajax({
                      url: hostUrl + 'general/' + endpoint.delete,

                      data: {
                          rowID: rowID,
                      },
                      type: "POST",
                      // CSRF verification
                      headers: {
                          "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
                              "content"
                          ),
                      },
                      success: function (response) {
                          var data = JSON.parse(response);
                          if (data.success) {
                              // display success message
                              toastr.success(data.message);

                              // draw datatable
                              dt.draw();
                          } // end if
                          else {
                              toastr.error(data.message);
                          }
                      },
                      error: function (xhr, status, error) {},
                  })
                : "cancel" === e.dismiss &&
                  Swal.fire({
                      text: n + " n'a pas été supprimé.",
                      icon: "error",
                      buttonsStyling: !1,
                      confirmButtonText: "Ok, j'ai compris !",
                      customClass: { confirmButton: "btn fw-bold btn-primary" },
                  });
        });
    });

    // Hook export buttons
    var exportButtons = () => {
        const documentTitle = "Criticité";
        var buttons = new $.fn.dataTable.Buttons(dt, {
            buttons: [
                {
                    extend: "copyHtml5",
                    title: documentTitle,
                },
                {
                    extend: "excelHtml5",
                    title: documentTitle,
                },
                {
                    extend: "csvHtml5",
                    title: documentTitle,
                },
                {
                    extend: "pdfHtml5",
                    title: documentTitle,
                },
            ],
        })
            .container()
            .appendTo($("#kt_datatable_example_buttons"));

        // Hook dropdown menu click event to datatable export buttons
        const exportButtons = document.querySelectorAll(
            "#kt_datatable_example_export_menu [data-kt-export]"
        );
        exportButtons.forEach((exportButton) => {
            exportButton.addEventListener("click", (e) => {
                e.preventDefault();

                // Get clicked export value
                const exportValue = e.target.getAttribute("data-kt-export");
                const target = document.querySelector(
                    ".dt-buttons .buttons-" + exportValue
                );

                // Trigger click event on hidden datatable export buttons
                target.click();
            });
        });
    };

    var columnsVisibility = () => {
        new $.fn.dataTable.Buttons(dt, {
            // buttons: [
            buttons: [
                {
                    extend: "colvis",
                    className: "btn-theme-light-primary",
                    text: `<span class="svg-icon svg-icon-1">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none"
                            xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M3 2H10C10.6 2 11 2.4 11 3V10C11 10.6 10.6 11 10 11H3C2.4 11 2 10.6 2 10V3C2 2.4 2.4 2 3 2Z"
                                fill="currentColor" />
                            <path opatax-type="0.3"
                                d="M14 2H21C21.6 2 22 2.4 22 3V10C22 10.6 21.6 11 21 11H14C13.4 11 13 10.6 13 10V3C13 2.4 13.4 2 14 2Z"
                                fill="currentColor" />
                            <path opatax-type="0.3"
                                d="M3 13H10C10.6 13 11 13.4 11 14V21C11 21.6 10.6 22 10 22H3C2.4 22 2 21.6 2 21V14C2 13.4 2.4 13 3 13Z"
                                fill="currentColor" />
                            <path opatax-type="0.3"
                                d="M14 13H21C21.6 13 22 13.4 22 14V21C22 21.6 21.6 22 21 22H14C13.4 22 13 21.6 13 21V14C13 13.4 13.4 13 14 13Z"
                                fill="currentColor" />

                        </svg>
                    </span>`,
                },
            ],
        }).container().appendTo($("div.column-visibility"));

        $(document).on("click", "#test-colvis", function (e) {
            e.preventDefault();

            // Get clicked export value
            const target = document.querySelector(
                ".buttons-collection.buttons-colvis"
            );

            // Trigger click event on hidden datatable export buttons
            target.click();
        });
    };

    // Public methods
    return {
        init: function () {
            initDatatable();
            handleSearchDatatable();
            exportButtons();
            columnsVisibility();
        },
    };
})();

// On document ready
KTUtil.onDOMContentLoaded(function () {
    ModeleDatatableServerSide.init();
});
