function setupCrudModal(config) {

    const modal = document.getElementById(config.modalId);
    

    if (modal) {
        modal.addEventListener('show.bs.modal', event => {

            const button = event.relatedTarget;

            const id = button.getAttribute('data-id');
            const name = button.getAttribute('data-name');
            const description = button.getAttribute('data-description');
            const level = button.getAttribute('data-level');

            const title = document.getElementById(config.titleId);
            const form = document.getElementById(config.formId);
            const inputId = document.getElementById(config.idInputId);
            const inputName = document.getElementById(config.nameInputId);
            const inputDescription = document.getElementById(config.descriptionInputId);

            const inputLevel = config.levelInputId
                ? document.getElementById(config.levelInputId)
                : null;

            if (id) {

                title.innerHTML = `
                    <i class="bi ${config.icon} me-2"></i>
                    Edit ${config.entityName}
                `;

                form.action = `${config.baseUrl}/edit/${id}`;

                inputId.value = id;
                inputName.value = name;
                inputDescription.value = description ?? '';

                if (inputLevel) {
                    inputLevel.value = level ?? '';
                }

            } else {

                title.innerHTML = `
                    <i class="bi ${config.icon} me-2"></i>
                    Tambah ${config.entityName}
                `;

                form.action = `${config.baseUrl}/tambah`;

                inputId.value = '';
                inputName.value = '';
                inputDescription.value = '';

                if (inputLevel) {
                    inputLevel.value = '';
                }
            }
        });
    }

    const deleteModal = document.getElementById(config.deleteModalId);

    if (deleteModal) {
        deleteModal.addEventListener('show.bs.modal', event => {

            const button = event.relatedTarget;

            document.getElementById(config.deleteIdInputId).value =
                button.dataset.id;

            document.getElementById(config.deleteNameId).textContent =
                button.dataset.name;
        });
    }
}


document.addEventListener('DOMContentLoaded', () => {


    

    // ===========================
    // DIVISI
    // ===========================

    setupCrudModal({
        entityName: 'Divisi',
        icon: 'bi-building',

        baseUrl: `${BASE_URL}/admin/pengaturan/divisi`,

        modalId: 'divisionModal',
        formId: 'divisionForm',
        titleId: 'divisionModalLabel',

        idInputId: 'id',
        nameInputId: 'namaDivisi',
        descriptionInputId: 'deskripsi',

        deleteModalId: 'divisionDeleteConfirmationModal',
        deleteIdInputId: 'deleteDivisionId',
        deleteNameId: 'deleteDivisionName'
    });

    // ===========================
    // KATEGORI
    // ===========================

    setupCrudModal({
        entityName: 'Kategori',
        icon: 'bi-tags',

        baseUrl: `${BASE_URL}/admin/pengaturan/kategori-tiket`,

        modalId: 'categoryModal',
        formId: 'categoryForm',
        titleId: 'categoryModalLabel',

        idInputId: 'id',
        nameInputId: 'namaKategori',
        descriptionInputId: 'deskripsi',

        deleteModalId: 'categoryDeleteConfirmationModal',
        deleteIdInputId: 'deleteCategoryId',
        deleteNameId: 'deleteCategoryName'
    });

    // ===========================
    // PRIORITAS TIKET
    // ===========================
    setupCrudModal({
        entityName: 'Prioritas',
        icon: 'bi-flag',

        baseUrl: `${BASE_URL}/admin/pengaturan/prioritas-tiket`,

        modalId: 'priorityModal',
        formId: 'priorityForm',
        titleId: 'priorityModalLabel',

        idInputId: 'id',
        nameInputId: 'namaPrioritas',
        levelInputId: 'level',
        descriptionInputId: 'deskripsi'
    });

});

document.addEventListener('DOMContentLoaded', () => {

    const slaModal = document.getElementById('slaModal');

    if (slaModal) {

        slaModal.addEventListener('show.bs.modal', event => {

            const button = event.relatedTarget;

            const id = button.getAttribute('data-id');
            const namaSla = button.getAttribute('data-name');
            const waktuRespon = button.getAttribute('data-response');
            const waktuPenyelesaian = button.getAttribute('data-resolution');
            const deskripsi = button.getAttribute('data-description');

            const title = document.getElementById('slaModalLabel');
            const form = document.getElementById('slaForm');

            const inputId = document.getElementById('id');
            const inputNama = document.getElementById('namaSla');
            const inputWaktuRespon = document.getElementById('waktuResponJam');
            const inputWaktuPenyelesaian = document.getElementById('waktuPenyelesaianJam');
            const inputDeskripsi = document.getElementById('deskripsi');

            if (id) {

                // Mode Edit
                title.innerHTML = `
                    <i class="bi bi-stopwatch me-2"></i>
                    Edit SLA
                `;

                form.action = `${BASE_URL}/admin/pengaturan/sla/edit/${id}`;

                inputId.value = id;
                inputNama.value = namaSla;
                inputWaktuRespon.value = waktuRespon;
                inputWaktuPenyelesaian.value = waktuPenyelesaian;
                inputDeskripsi.value = deskripsi ?? '';

            } else {

                // Mode Tambah
                title.innerHTML = `
                    <i class="bi bi-stopwatch me-2"></i>
                    Tambah SLA
                `;

                form.action = `${BASE_URL}/admin/pengaturan/sla/tambah`;

                inputId.value = '';
                inputNama.value = '';
                inputWaktuRespon.value = '';
                inputWaktuPenyelesaian.value = '';
                inputDeskripsi.value = '';

            }

        });

    }

    const slaDeleteConfirmationModal = document.getElementById(
        'slaDeleteConfirmationModal'
    );

    if (slaDeleteConfirmationModal) {

        slaDeleteConfirmationModal.addEventListener(
            'show.bs.modal',
            function (event) {

                const button = event.relatedTarget;

                if (!button) return;


                const id = button.dataset.id;
                const name = button.dataset.name;


                const deleteSlaId = document.getElementById('deleteSlaId');
                const deleteSlaName = document.getElementById('deleteSlaName');


                if (deleteSlaId) {
                    deleteSlaId.value = id;
                }


                if (deleteSlaName) {
                    deleteSlaName.textContent = name;
                }

            }
        );

    }

});

document.addEventListener('DOMContentLoaded', () => {

    const modal = document.getElementById('statusModal');

    if (!modal) return;

    modal.addEventListener('show.bs.modal', event => {

        const button = event.relatedTarget;

        document.getElementById('statusModalLabel').innerHTML = `
            <i class="bi bi-kanban me-2"></i>
            Edit Status Ticket
        `;

        document.getElementById('statusForm').action = `${BASE_URL}/admin/pengaturan/status-tiket/edit/${button.dataset.id}`;

        document.getElementById('id').value =
            button.dataset.id;

        document.getElementById('namaStatus').value =
            button.dataset.name;

        document.getElementById('urutan').value =
            button.dataset.order;

        document.getElementById('deskripsi').value =
            button.dataset.description ?? '';
    });

});


document.addEventListener("DOMContentLoaded", () => {

    const input = document.getElementById("attachments");
    const preview = document.getElementById("attachmentPreview");

    if (!input || !preview) return;

    const dataTransfer = new DataTransfer();

    input.addEventListener("change", function () {

        // Tambahkan file baru ke DataTransfer
        Array.from(this.files).forEach(file => {

            const exists = Array.from(dataTransfer.files).some(f =>
                f.name === file.name &&
                f.size === file.size &&
                f.lastModified === file.lastModified
            );

            if (!exists) {
                dataTransfer.items.add(file);
            }

        });

        input.files = dataTransfer.files;

        renderFiles();
    });

    function renderFiles() {

        preview.innerHTML = "";

        if (input.files.length === 0) {
            return;
        }

        Array.from(input.files).forEach((file, index) => {

            const size =
                file.size >= 1024 * 1024
                    ? (file.size / 1024 / 1024).toFixed(2) + " MB"
                    : (file.size / 1024).toFixed(0) + " KB";

            let icon = "bi-file-earmark";

            if (file.type.startsWith("image/")) {
                icon = "bi-file-earmark-image";
            } else if (file.type === "application/pdf") {
                icon = "bi-file-earmark-pdf";
            } else if (
                file.name.endsWith(".doc") ||
                file.name.endsWith(".docx")
            ) {
                icon = "bi-file-earmark-word";
            } else if (
                file.name.endsWith(".xls") ||
                file.name.endsWith(".xlsx")
            ) {
                icon = "bi-file-earmark-excel";
            }

            preview.insertAdjacentHTML(
                "beforeend",
                `
                <div class="card mb-2 shadow-sm">

                    <div class="card-body py-2">

                        <div class="d-flex justify-content-between align-items-center">

                            <div class="d-flex align-items-center">

                                <i class="bi ${icon} fs-4 text-primary me-3"></i>

                                <div>

                                    <div class="fw-semibold">
                                        ${file.name}
                                    </div>

                                    <small class="text-muted">
                                        ${size}
                                    </small>

                                </div>

                            </div>

                            <button
                                type="button"
                                class="btn btn-sm btn-outline-danger"
                                onclick="removeAttachment(${index})">

                                <i class="bi bi-x-lg"></i>

                            </button>

                        </div>

                    </div>

                </div>
                `
            );
        });
    }

    window.removeAttachment = function (index) {

        const newTransfer = new DataTransfer();

        Array.from(input.files).forEach((file, i) => {

            if (i !== index) {
                newTransfer.items.add(file);
            }

        });

        input.files = newTransfer.files;

        dataTransfer.items.clear();

        Array.from(newTransfer.files).forEach(file => {
            dataTransfer.items.add(file);
        });

        renderFiles();
    };

});

document.addEventListener("DOMContentLoaded", () => {

    // Saat halaman dibuka
    const hash = window.location.hash;

    if (hash) {
        const trigger = document.querySelector(
            `[data-bs-target="${hash}"]`
        );

        if (trigger) {
            bootstrap.Tab.getOrCreateInstance(trigger).show();
        }
    }

    // Saat user pindah tab
    document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {

        tab.addEventListener("shown.bs.tab", function (e) {

            const hash = e.target.dataset.bsTarget;

            history.replaceState(null, null, hash);

        });

    });

});

document.querySelectorAll('.btn-atur-sla').forEach(button => {
  button.addEventListener('click', function () {
    document.querySelector('[name="id_ticket"]').value = this.dataset.id;
  });
});