<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.3.0/exceljs.min.js"></script>

<script>
    $(document).ready(function () {
        $('.excel-btn').click(async function (e) {
            e.preventDefault();

            let skipExportColumns = "<%= skipExportColumns %>".split(',');
            let data = [];
            let cols = [];
            let columnIndexesToSkip = [];

            // Get table headers and determine columns to skip
            $('.table thead th').each(function (index) {
                let columnName = $(this).text().trim();
                if (skipExportColumns.includes(columnName) || $(this).find('input[type="checkbox"]').length > 0) {
                    columnIndexesToSkip.push(index);
                } else {
                    cols.push(columnName);
                }
            });
            data.push(cols);

            // Get table data
            $('.table tbody tr').each(function () {
                let row = [];
                $(this).find('td').each(function (index) {
                    if (columnIndexesToSkip.includes(index)) return;
                    let text = $(this).text().trim() === "" ? "_" : $(this).text().trim();
                    row.push(text);
                });
                data.push(row);
            });

            // Reverse data if language is Arabic
            if (lang === 'ar') {
                data = data.map(row => row.reverse());
            }

            // Create an Excel workbook and worksheet
            let workbook = new ExcelJS.Workbook();
            let worksheet = workbook.addWorksheet('<%= title %>');

            // Define cell styling
            const cellStyle = {
                alignment: { vertical: 'middle', horizontal: 'center' },
                border: {
                    top: { style: 'thin' },
                    left: { style: 'thin' },
                    bottom: { style: 'thin' },
                    right: { style: 'thin' }
                }
            };

            // Add data and apply styles
            data.forEach((row) => {
                let excelRow = worksheet.addRow(row);
                excelRow.eachCell((cell) => {
                    cell.style = cellStyle;
                });
            });

            // Generate the Excel file
            const buffer = await workbook.xlsx.writeBuffer();
            let blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });

            // Create and trigger download
            let link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = '<%= title %>.xlsx';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });

        // Export All Button
        $('.exportAll-btn').click(async function (e) {
            try {
                var dataRoute = $(this).data('route');
                const response = await fetch(dataRoute.url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.content || ''
                    },
                    body: JSON.stringify(dataRoute)
                });

                if (!response.ok) {
                    Swal.fire({
                        icon: 'error',
                        title: "<%= i18n.__('common.noDataFound') %>",
                        showConfirmButton: false,
                        timer: 1500
                    });
                } else {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `<%=title%>.xlsx`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }
            } catch (error) {
                console.error('Error exporting data:', error);
            }
        });
    });
</script>
