<div id="loading"></div>
<?php
//parameters
if($logo==="yes"){
    $img = file_get_contents('images/company/logo.jpg');
    $image = 'images/company/logo.jpg';
    $imageData = base64_encode($img);
    $src = 'data: image/jpeg;base64,'.$imageData; 
}

 if(empty($length)){$length=10;}
 if(empty($showFilter)){$filter=1;}else{$filter=0;}
 if(!empty($scroll)){
$scroller='
scrollY:'.$scroll.',
deferRender:    true,
scroller:       true,
';}
?>

<!-- Include libraries -->
<link href='<?=ROOT_URL?>/packages/font-awesome/css/all.min.css?7' rel='stylesheet'>


<!-- Begin table generation -->
<script>
$('#<?= $table?>').dataTable({
    processing: true,
    keys: true,
    columnDefs: [{
        target: <?= $dateTarget?>,
        render: DataTable.render.date(),
    }, ],
    "order": [
        [<?= $dateTarget?>, "asc"]
    ],
    "columnDefs": [<?php if(empty($sortCell)){}
    else{?> {
        orderable: false,
        className: 'select-checkbox selectable me3',
        targets: <?=$sortTarget?>,

    }, <?php }?> {
        orderable: true,
        className: 'dateField',
        "type": "uk_date",
        targets: <?= $dateTarget?>,
        "destroy": false,
        "render": function(data, type, row, meta) {
            // Format the date using Moment.js and return it
            if (type === 'sort' || type === 'type') {
                return moment(data, "DD/MM/YYYY").format("DD/MM/YYYY");
            }
            return moment(data, "DD/MM/YYYY").format("DD/MM/YYYY");
        }
    }],

    pageLength: <?= $length?>,
    responsive: true,
    lengthMenu: [
        [10, 25, 50, 100, 150, 200, 500, -1],
        [10, 25, 50, 100, 150, 200, 500, "All"]
    ],
    <?php if(empty($sortCell)){}
    else{?>
    select: {
        style: 'multi',
        selector: 'td:<?=$sortCell?>'
    },
    <?php }?>
    dom: 'lBfrtipB',
    fixedHeader: false,
    initComplete: function(settings, json) {
        $('#loadingObject').css('display', 'none');
        $('#<?= $table?>').css('display', 'table');
        <?php if($popup=="true"){?>

        // Popovers
        var popoverElements = document.querySelectorAll('[data-mdb-popover-init]');
        popoverElements.forEach(function(element) {
            new mdb.Popover(element, {
                trigger: 'hover', // Set the trigger to hover

            });
        })

        // Tooltips
        var tooltipElements = document.querySelectorAll('[data-mdb-tooltip-init]');
        for (var i = 0; i < tooltipElements.length; ++i) {
            new mdb.Tooltip(tooltipElements[i], {
                trigger: 'hover' // Add the hover trigger option
            });
        }

        <?php }?>


    },
    drawCallback: function(settings) {

    },
    language: {
        searchPanes: {
            clearMessage: 'Clear filters',
            collapse: {
                0: 'Search Options',
                _: 'Custom Filter (%d)'
            }
        }
    },
    buttons: [
        'selectAll',
        'selectNone',


        {
            text: '<i class="fad fa-print fa-1x me-3 duoBlue"></i>',

            action: function(e, dt, node, config) {
                // Capture the HTML content for printing
                //const content = generatePrintContent(dt);
                const content = generatePrintContent(dt);
                insertContentIntoWrapper(content);

                function printContent(target, header) {
                    printContainer(target, {
                        orientation: 'landscape', // or 'Portrait'
                        header: '<p>' + header + '</p>',
                        footer: '<p>Generated by EnRep Reporting System: <?= date('d-m-Y')?></p>',
                        logoUrl: 'images/company/logo.jpg',
                        styles: [
                            ROOT_URL + '/src/css/print.css'
                        ],
                    });
                }

                printContent('tableWrapper', 'Custom Print')

            },

            customize: function(win) {

                $(win.document.body).css({
                    'font-size': '10pt',
                    'color': '#ffffff'
                }).prepend('<img src="/images/company/logo_thumb.jpg" style="position:absolute; top:-20px" /><span style="float:right">' + $('#exportTitle').html() +
                    '</span><br><br>');
                $(win.document.body).find('table').addClass('table').addClass('table-sm').addClass('compact').css({
                    'page-break-after': 'avoid',
                    'font-size': '10px',
                    'width': '100%'
                }).css('font-size', '10px');
                $(win.document.body).find('table th').attr('style', 'background-color:#353b50; color:#ffffff')

                $(win.document.body).append('Generated by EnRep Reporting System: <?= date('d-m-Y')?>');
                var last = null;
                var current = null;
                var bod = [];

                var css = '@page { size: landscape; }',
                    head = win.document.head || win.document.getElementsByTagName('head')[0],
                    style = win.document.createElement('style');

                style.type = 'text/css';
                style.media = 'print';

                if (style.styleSheet) {
                    style.styleSheet.cssText = css;
                } else {
                    style.appendChild(win.document.createTextNode(css));
                }

                head.appendChild(style);
            }
        },

        {
            extend: 'csvHtml5',
            title: $('#exportTitle').text(),
            text: '',
            className: 'fad fa-file-excel fa-1x me-3 duoGreen',
            exportOptions: {
                columns: "thead th:not(.noExport)",
                modifier: {
                    page: 'current'
                }
            },
        },
        {
            extend: 'pdfHtml5',
            footer: true,
            title: $('#exportTitle').text(),
            filename: $('#exportTitle').text().replace(/ /g, ""),
            text: '',
            orientation: 'landscape',
            pageSize: 'A4',
            className: 'fad fa-file-pdf fa-1x duoRed',
            exportOptions: {
                columns: "thead th:not(.noExport)",
                modifier: {
                    page: 'current',
                    orthogonal: 'export'
                }
            },

            customize: function(doc) {
                doc.pageMargins = [20, 20, 80, 20];
                doc.defaultStyle.alignment = 'left';
                doc.defaultStyle.padding = '10px';
                doc.styles.tableHeader.alignment = 'left';
                doc.styles.tableHeader.padding = '10';
                doc.styles.tableBody = {
                    padding: '10'
                };
                <?php
                if(!empty($logo)){?>
                doc['header'] = (function() {
                    return {
                        columns: [{
                            image: '<?= $src?>',
                            width: 150
                        }],
                        margin: 10
                    }
                });
                doc['footer'] = (function(page, pages) {
                    return {
                        columns: [{
                            alignment: 'left',
                            text: ['Generated by EnRep Reporting System: <?= date('d-m-Y')?>']
                        }],
                        margin: [10, 0]
                    }
                });
                <?php }?>

                doc.styles.tableHeader.alignment = 'left';
                doc.content[1].table.widths = [98, 98, 98, 98, 90, 90, 90, 90];
            }
        }

        <?= $scroller?>
        <?= $selector?>
    ],
    layout: {
        topStart: {
            buttons: ['createState', 'savedStates']
        }
    },
    searchPanes: {
        cascadePanes: true,
        layout: 'columns-4',
        viewTotal: true
    },
    "stateSave": true,
    "stateSaveParams": function(settings, data) {
        delete data.select;
    },
    "stateLoadParams": function(settings, data) {
        delete data.select;
    },

    fixedHeader: true

});
// $('#<?= $table?>').DataTable().searchPanes.rebuildPane();
function clearSearcher(n) {
    var table = $('#<?= $table?>').dataTable().api();
    $.fn.dataTable.ext.search.pop()
    table.search('').draw();
    $("#siteList").val(null).trigger("change");
}



var table = $('#<?= $table?>').DataTable();

var selectedRowsIDs = []; // To keep track of selected row IDs

table.on('select', function(e, dt, type, indexes) {
    var rows = table.rows(indexes).data().toArray();

    for (var i = 0; i < rows.length; i++) {
        var rowID = table.row(indexes[i]).id();

        // Add the ID to the array if it's not already present
        if (!selectedRowsIDs.includes(rowID)) {
            selectedRowsIDs.push(rowID);
        }
    }

    console.log(selectedRowsIDs);
    $('#selectedItems').text(selectedRowsIDs);

    if (selectedRowsIDs.length > 0) {
        $('#massMigrate').css('display', 'inline-block');
        $('#massArchive').css('display', 'inline-block');
        $('#massCode').css('display', 'inline-block');
        $('#assignAsset').css('display', 'inline-block');
        // $('#selectedItems').text(v)
    }
});
table.on('draw.dt', function() {

});
// Handle the row deselection event
table.on('deselect', function(e, dt, type, indexes) {
    var rows = table.rows(indexes).data().toArray();

    for (var i = 0; i < rows.length; i++) {
        var rowID = table.row(indexes[i]).id();

        // Remove the ID from the array
        var index = selectedRowsIDs.indexOf(rowID);
        if (index > -1) {
            selectedRowsIDs.splice(index, 1);
        }
    }

    console.log(selectedRowsIDs);
    $('#selectedItems').text(selectedRowsIDs)
    if (selectedRowsIDs.length === 0) {
        $('#massMigrate').css('display', 'none');
        $('#massArchive').css('display', 'none');
        $('#massCode').css('display', 'none');
        $('#assignAsset').css('display', 'none');
        // $('#selectedItems').text('')
    }

});

var data = table
    .rows()
    .data();

if (data.length == 0) {}

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "uk_date-pre": function(a) {
        var ukDate = moment(a, "DD/MM/YYYY");
        return ukDate.isValid() ? ukDate.unix() : -1;
    },

    "uk_date-asc": function(a, b) {
        return a - b;
    },

    "uk_date-desc": function(a, b) {
        return b - a;
    }
});

$('.dt-buttons').find('.btn').each(function() {
    $(this).addClass('btn-sm').addClass('me-3').removeClass('btn-light').addClass('btn-secondary')
});

function generatePrintContent(dt) {
    const tableData = dt.buttons.exportData({
        columns: ':visible'
    });

    let content = '<table class="table table-striped table-sm table-bordered table-hover responsive" style="width:100%"><thead><tr>';

    tableData.header.forEach(function(header) {
        content += '<th>' + header + '</th>';
    });

    content += '</tr></thead><tbody>';

    tableData.body.forEach(function(row) {
        content += '<tr>';
        row.forEach(function(cell) {
            content += '<td>' + cell + '</td>';
        });
        content += '</tr>';
    });

    content += '</tbody></table>';

    return content;
}

// Function to insert the generated content into #tableWrapper
function insertContentIntoWrapper(content) {
    const wrapper = document.getElementById('tableWrapper');
    if (wrapper) {
        wrapper.innerHTML = content;
    }
}
</script>