$(document).ready(function() {
    let currentPage = 1;
    let totalPage = 1;
    const btn = document.getElementById('filterToggleBtn');
    const box = document.getElementById('customFilterBox');
    const icon = btn.querySelector('.rotate-icon');

    btn.addEventListener('click', function () {
        const isOpen = box.classList.toggle('open');
        icon.classList.toggle('rotated', isOpen);
        btn.classList.toggle('expanded', isOpen); // ⬅️ ini tambahan
    });

    let table = $('#empTable').DataTable({
        dom:'t',
        processing: true,
        serverSide: true,
        searching: false,
        lengthChange: false,
        ordering: false,
        info: false,
        ajax: {
            url: tableUrl,
            type: "GET",
            data: function (d) {
                d.keyword = $('#search').val();
                d.page = currentPage;
                d.size = $('#dLength').val();
                d.sort_by = $('#sortBy').val();
                d.sort_dir = $('#sortDir').val();
            }
        },
        pageLength: $('#dLength').val(),
        columns: [
            {
                data: null,
                orderable: false,
                render: function (data, type, row, meta) {
                    var currentPage = meta.settings.json.pagination.current_page;
                    var perPage = meta.settings.json.pagination.per_page;

                    return (currentPage - 1) * perPage + meta.row + 1;
                }
            },
            { data: 'title' },
            {
                data: 'file',
                orderable: false,
                render: function(data) {
                    if (!data) return '-';

                    const url = `/storage/files/sop/${data}`;
                    const ext = data.split('.').pop().toLowerCase();

                    const imageExt = ['jpg','jpeg','png','webp','gif'];

                    if (imageExt.includes(ext)) {
                        return `
                <a href="${url}" target="_blank">
                    <img src="${url}" class="slider-thumb" alt="Slider Image">
                </a>
            `;
                    }

                    if (ext === 'pdf') {
                        return `
                <a href="${url}" target="_blank" class="text-danger fw-semibold">
                    <i class="bi bi-file-earmark-pdf-fill me-1"></i> Lihat PDF
                </a>
            `;
                    }

                    return `
            <a href="${url}" target="_blank" class="text-primary fw-semibold">
                <i class="bi bi-file-earmark-fill me-1"></i> Buka File
            </a>
        `;
                }
            },
            {
                data: 'status',
                orderable: false,
                render: function(data) {
                    if(data === 1) {
                        return `<span class="badge bg-success">Aktif</span>`;
                    } else {
                        return `<span class="badge bg-danger">Nonaktif</span>`;
                    }
                }
            },
            {
                data: 'id',
                orderable: false,
                render: function(id) {

                    return `
        <div class="dropdown text-center">
            <button class="btn btn-sm action-btn action-btn-sm border-0 bg-transparent"
                    data-coreui-toggle="dropdown"
                    aria-expanded="false">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="16" height="16">
                    <circle cx="256" cy="53.333" r="53.333"/>
                    <circle cx="256" cy="256" r="53.333"/>
                    <circle cx="256" cy="458.667" r="53.333"/>
                </svg>
            </button>

            <div class="dropdown-menu dropdown-menu-end shadow-sm">
                <a class="dropdown-item small" href="/application/sop/edit/${id}">
                    <i class="bi bi-pencil-square me-2"></i> Edit
                </a>

                <button class="dropdown-item small text-danger btn-delete" data-id="${id}">
                    <i class="bi bi-trash me-2"></i> Hapus
                </button>
            </div>
        </div>
    `;
                }
            }
        ],
        columnDefs: [
            { targets: 0, className: 'text-start', width: "70px"}, // kolom No
            { targets: 4, className: 'text-center' ,width: "110px"}  // kolom Actions biar tombol rapi
        ],
    });
    $('#empTable tbody').on('click', '.perm-toggle', function () {
        const wrapper = $(this).closest('.perm-wrapper');
        const hidden = wrapper.find('.perm-hidden');

        if (hidden.is(':visible')) {
            hidden.hide();
            $(this).text('+' + hidden.length + ' lagi');
        } else {
            hidden.show();
            $(this).text('Sembunyikan');
        }
    });
    table.on('xhr', function(e, settings, json) {
        if (!json) return;

        console.log(json);

        $('#start').text(json.pagination.from ?? 0);
        $('#end').text(json.pagination.to ?? 0);
        $('#total').text(json.pagination.total ?? 0);

        totalPage = json.pagination.last_page;

        let pagination = $('#custom-pagination');
        pagination.empty();

        let prevClass = json.pagination.current_page == 1 ? 'disabled' : '';
        pagination.append(`<li class="page-item ${prevClass}">
        <a class="page-link" href="#" data-page="prev">Previous</a>
    </li>`);

        for (let i = 1; i <= json.pagination.last_page; i++) {
            let activeClass = json.pagination.current_page == i ? 'active' : '';
            pagination.append(`<li class="page-item ${activeClass}">
            <a class="page-link" href="#" data-page="${i}">${i}</a>
        </li>`);
        }

        let nextClass = json.pagination.current_page == json.pagination.last_page ? 'disabled' : '';
        pagination.append(`<li class="page-item ${nextClass}">
        <a class="page-link" href="#" data-page="next">Next</a>
    </li>`);
    });
    $(document).on('click', '#custom-pagination a', function(e) {
        e.preventDefault();
        let page = $(this).data('page');

        if (page === 'prev' && currentPage > 1) currentPage--;
        else if (page === 'next' && currentPage < totalPage) currentPage++;
        else if (!isNaN(page)) currentPage = parseInt(page);
        else return;

        table.ajax.reload(null, false);
    });

    $('#search').on('keyup', function() {
        table.ajax.reload();
    });

    $('#dLength').on('change', function() {
        table.page.len(this.value).draw();
    });

    $('#sortBy').on('change', function() {
        table.ajax.reload();
    });

    $('#sortDir').on('change', function() {
        table.ajax.reload();
    });

    let deleteId = null;
    let deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

    $(document).on('click', '.btn-delete', function () {
        deleteId = $(this).data('id');
        deleteModal.show();
    });

    $('#confirmDelete').on('click', function () {
        if (!deleteId) return;

        $.ajax({
            url: `/api/web/sop/delete/${deleteId}`,
            type: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (res) {
                const successMessage = res.message || 'Data berhasil dihapus';
                deleteModal.hide();
                table.ajax.reload(null, false);
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000,
                    didOpen: (toast) => {
                        toast.addEventListener('mouseenter', Swal.stopTimer)
                        toast.addEventListener('mouseleave', Swal.resumeTimer)
                    }
                })

                Toast.fire({
                    icon: 'success',
                    title: successMessage
                })
            },
            error: function (xhr) {
                let message = 'Gagal menghapus data';
                if (xhr.responseJSON) {
                    if (xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }
                }

                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000,
                    didOpen: (toast) => {
                        toast.addEventListener('mouseenter', Swal.stopTimer)
                        toast.addEventListener('mouseleave', Swal.resumeTimer)
                    }
                })

                Toast.fire({
                    icon: 'error',
                    title: message
                })
            }
        });
    });
});
