new SlimSelect({
    select: '#location'
})
$(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.search = $('#search').val();
                d.page = currentPage;
                d.type_report = $('#type_report').val();
                d.location = $('#location').val();
                d.title_medical = $('#title_medical').val();
                d.start_date = $('#start_date').val();
                d.end_date = $('#end_date').val();
                d.status = $('#status').val();
                d.sort_by = $('#sortBy').val();
                d.sort_dir = $('#sortDir').val();
                d.size = $('#dLength').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: 'status',
                orderable: false,
                render: function(data) {
                    if(data === 1) {
                        return `<span class="status-new">Baru</span>`;
                    } else if (data === 3) {
                        return `<span class="status-process">Diproses</span>`;
                    } else if (data === 2) {
                        return `<span class="status-verification">Verifikasi</span>`;
                    } else if (data === 4) {
                        return `<span class="status-finish">Selesai</span>`;
                    } else {
                        return `<span class="status-reject">Ditolak</span>`;
                    }
                }
            },
            {
                data: 'type_report',
                orderable: false,
                render: function(data, type, row) {
                    if (data === 1) {
                        return `
                <div class="">Pelanggaran SOP</div>
                <small class="text-muted">Kepatuhan Prosedur</small>
            `;
                    } else if (data === 2) {
                        let detailInsiden = row.title_medical ? row.title_medical.name : '';
                        return `
                <div class="">Insiden Keselamatan Petugas</div>
                <div class="badge bg-danger-subtle text-danger p-1" style="font-size: 0.75rem;">
                    <i class="bi bi-info-circle me-1"></i>${detailInsiden}
                </div>
            `;
                    } else if (data === 3) {
                        const haisMap = {
                            1: 'HAP',
                            2: 'VAP',
                            3: 'SSI',
                            4: 'IADP',
                            5: 'CAUTI'
                        };

                        let namaHais = haisMap[row.type_hais] || 'Lainnya';

                        return `
                <div class="">Kejadian HAIS</div>
                <div class="badge bg-warning-subtle text-warning p-1" style="font-size: 0.75rem;">
                    <i class="bi bi-virus me-1"></i>${namaHais}
                </div>
            `;
                    }
                    return '';
                }
            },
            {
                data: 'location.title',
                name: 'location.title',
                render: function(data, type, row) {
                    if (data === 0 || data === "0" || !data) {
                        return `<span class="">${row.other_location}</span>`;
                    }
                    return data;
                }
            },
            {
                data: 'date_formatted',
                render: function(data, type, row) {
                    return `
            <div class="">${data}</div>
            <small class="text-muted">${row.time_formatted} WIB</small>
        `;
                }
            },
            {
                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="/report/detail/${id}" target="_blank" rel="noopener noreferrer">
                    <i class="bi bi-pencil-square me-2"></i> Detail
                </a>


            </div>
        </div>
    `;
                }
            }
        ],
        columnDefs: [
            { targets: 0, className: 'text-start', width: "70px"},
            { targets: 4, className: 'text-start'},
            { targets: 5, className: 'text-center' ,width: "110px"}
        ],
    });
    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.data.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.data.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);
    });

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

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

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

    $('#location').on('change', function() {
        currentPage = 1;
        table.ajax.reload();
    });

    $('#title').on('change', function() {
        currentPage = 1;
        table.ajax.reload();
    });

    $('#type_report').on('change', function() {
        currentPage = 1;
        table.ajax.reload();
    });

    $('#status').on('change', function() {
        currentPage = 1;
        table.ajax.reload();
    });

    $('#start_date').on('change', function() {
        currentPage = 1;
        table.ajax.reload();
    });

    $('#end_date').on('change', function() {
        currentPage = 1;
        table.ajax.reload();
    })
    $('#clearDate').on('click', function() {
        $('#start_date').val('')
        $('#end_date').val('')
        table.ajax.reload();
    })
    $('#search').on('keyup', function() {
        currentPage = 1;
        table.ajax.reload();
    });
});

$('#exportBtn').on('click', function () {
    $.ajax({
        url: `/api/web/report/export`,
        type: 'GET',
        data: {
            keyword : $('#search').val(),
            type_report : $('#type_report').val(),
            location : $('#location').val(),
            title_medical : $('#title_medical').val(),
            start_date : $('#start_date').val(),
            end_date : $('#end_date').val(),
            status : $('#status').val(),
            sort_by : $('#sortBy').val(),
            sort_dir : $('#sortDir').val(),
            size : $('#dLength').val(),
        },
        xhrFields: {
            responseType: 'blob'
        },
        success: function (data, status, xhr) {
            var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "laporan-report.xlsx";
            link.click();
        },
        error: function (xhr) {

            var reader = new FileReader();
            reader.onload = function() {
                let message = 'Gagal mengekspor data';
                try {

                    const response = JSON.parse(reader.result);
                    message = response.message || message;
                } catch (e) {

                }

                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000
                });

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

            if (xhr.response instanceof Blob) {
                reader.readAsText(xhr.response);
            } else {
            }
        }
    });
});
