<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.12/pdfmake.min.js"></script>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.68/vfs_fonts.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.12/vfs_fonts.js"
    integrity="sha512-nNkHPz+lD0Wf0eFGO0ZDxr+lWiFalFutgVeGkPdVgrG4eXDYUnhfEj9Zmg1QkrJFLC0tGs8ZExyU/1mjs4j93w=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>

    $(document).ready(function () {
        let skipExportColumns = "<%= skipExportColumns %>";

        $('.pdf-btn').click(function (e) {
            e.preventDefault();

            let data = [];
            let columns = [];
            let title = "<%=title%>"
            let lang = "<%=lang%>"
            console.log("lang", lang)

            const convertTextToRtl = (text) => {
                return text
                    .split(" ")
                    .reverse()
                    .map(word => {
                        return word
                            .replace(/\(/g, "#open#")
                            .replace(/\)/g, "#close#");
                    })
                    .join("  ")
                    .replace(/#open#/g, ")")
                    .replace(/#close#/g, "(");
            };


            const convertDateToReversed = (text) => {
                let parts = text.split(/[-\/]/);
                parts.reverse();
                let reversedParts = parts.map(part => {
                    return part.split("").reverse().join("");
                });

                return reversedParts.join("/");
            };
            // Extract column headers
            $('.table th').each(function () {

                let columnName = $(this).text().trim() == "" ? "_" : $(this).text().trim();
                console.log("columnName", columnName)

                if (skipExportColumns.includes(columnName) || $(this).find('input[type="checkbox"]').length > 0) return;

                columns.push({ text: lang == 'ar' ? convertTextToRtl(columnName) : columnName, style: 'tableHeader' });
            });

            // Extract table data
            $(' tbody tr').each(function () {
                let row = [];
                $(this).find('td').each(function (index) {
                    let columnName = $(this).closest('table').find('th').eq(index).text().trim()

                    if (skipExportColumns.includes(columnName) || $(this).find('input[type="checkbox"]').length > 0) return;

                    let cellContent = $(this).text().trim() == "" ? "_" : $(this).text().trim();

                    function isArabic(text) {
                        return /[\u0600-\u06FF]/.test(text);
                    }

                    row.push({
                        text:
                            lang === 'ar'
                                ? columnName === "<%= i18n.__('common.date')%>"
                                    ? convertDateToReversed(cellContent)
                                    : isArabic(cellContent)
                                        ? convertTextToRtl(cellContent)
                                        : cellContent
                                : cellContent,
                        style: "tableBody"
                    });

                });
                data.push(row);
            });

            if (lang == 'ar') {
                columns.reverse();
                data = data.map(row => row.reverse());
            }

            console.log("data after collecting", data); // Check the final data array

            let numColumns = data[0].length;
            let titleFontSize = 12;
            let headFontSize = 10;
            let bodyFontSize = 8;
            let percentage;

            ({ percentage, titleFontSize, headFontSize, bodyFontSize } = calculateTableWidthPercentage(numColumns));
            let pageWidth = 595.28; // A4 width in points
            let margin = 20;
            let usableWidth = pageWidth - (2 * margin);
            let tableWidth = usableWidth * percentage;
            let columnWidth = tableWidth / numColumns;

            let docDefinition = {
                content: [
                    // Add a title
                    { text: lang == 'ar' ? convertTextToRtl(title) : title, style: 'title' },

                    // Wrap the table in a stack and align it in the center
                    {
                        stack: [
                            {
                                table: {
                                    widths: new Array(numColumns).fill(columnWidth),
                                    body: [
                                        // First, add the column headers
                                        columns.map(column => ({ text: column.text, style: 'tableHeader' })),

                                        // Then, add the data rows
                                        ...data.map(row => row.map(cell => cell ? { text: cell.text, style: 'tableBody' } : { text: '', style: 'tableBody' }))
                                    ]
                                },
                                layout: {
                                    hLineColor: function (i, node) {
                                        return 'white';
                                    },
                                    vLineColor: function (i, node) {
                                        return 'white';
                                    },
                                    fillColor: function (rowIndex, node, columnIndex) {
                                        if (rowIndex === 0) return '#0e3557'; // Header
                                        return (rowIndex % 2 === 0) ? '#f7f7f7' : 'white'; // Rows
                                    }
                                }
                            }
                        ],
                        alignment: 'center'
                    }
                ],
                styles: {
                    title: {
                        fontSize: titleFontSize,
                        //  margin: [0, 20, 0, 10], // Add some bottom margin to create space between the title and the table
                        alignment: 'center',
                        direction: lang == 'ar' ? "rtl" : "ltr",
                    },
                    tableHeader: {
                        bold: true,
                        fontSize: headFontSize,
                        color: 'black',
                        fillColor: '#0e3557', color: 'white', alignment: 'center',
                        font: 'Cairo',
                        alignment: 'center'
                    },
                    tableBody: {
                        fontSize: bodyFontSize,
                        font: 'Cairo',
                        alignment: 'center',
                        direction: lang == 'ar' ? "rtl" : "ltr",
                    }
                },
                defaultStyle: {
                    font: 'Cairo'
                },
                pageMargins: [margin, margin, margin, margin], // Set the same margin on each side
                dir: 'rtl' // Ensure text direction is set to right-to-left
            };

            // Define the custom fonts
            let customFonts = {
                Cairo: {
                    normal: baseUrl + '/public/admin/app-assets/fonts/Cairo/static/Cairo-Regular.ttf',
                    bold: baseUrl + '/public/admin/app-assets/fonts/Cairo/static/Cairo-Bold.ttf',
                    light: baseUrl + '/public/admin/app-assets/fonts/Cairo/static/Cairo-Light.ttf',
                    black: baseUrl + '/public/admin/app-assets/fonts/Cairo/static/Cairo-Black.ttf'
                }
            };

            // Register the custom fonts
            pdfMake.fonts = customFonts;

            // Generate PDF
            pdfMake.createPdf(docDefinition).download('<%=title%>.pdf');
        });
    });

    function calculateTableWidthPercentage(numColumns) {
        let percentage;
        let titleFontSize;
        let headFontSize;
        let bodyFontSize;

        if (numColumns <= 5) {
            percentage = 0.9; // If there are 5 or fewer columns, set the percentage to 90%
            titleFontSize = 14;
        } else if (numColumns <= 9) {
            percentage = 0.85; // If there are 9 or fewer columns, set the percentage to 85%
            titleFontSize = 11;
            headFontSize = 8;
            bodyFontSize = 6;
        } else if (numColumns <= 15) {
            percentage = 0.8; // If there are up to 18 columns, set the percentage to 80%
            titleFontSize = 10;
            headFontSize = 7;
            bodyFontSize = 5;
        } else {
            percentage = 0.70; // If there are more than 15 columns, set the percentage to 75%
            titleFontSize = 10;
            headFontSize = 5;
            bodyFontSize = 4;
        }

        return { percentage, titleFontSize, headFontSize, bodyFontSize };
    }


</script>