<div id="loading"></div>

<?php
if (!empty($logo)) {
    $img = file_get_contents('../../../..' . TENANT_URL . '/images/company/logo.jpg');
    $image = '../../../..' . TENANT_URL . '/images/company/logo.jpg';
    // Read image path, convert to base64 encoding
    $imageData = base64_encode(file_get_contents($image));

    // Format the image SRC:  data:{mime};base64,{data};
    $src = 'data: image/jpeg;base64,' . $imageData;
}

?>

<?php if (empty($length)) {
    $length = 10;
} ?>
<?php if (empty($showFilter)) {
    $filter = 1;
} else {
    $filter = 0;
} ?>
<?php 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'>


<script>
DataTable.datetime('DD-MM-YYYY');
$('#<?= $table ?>').dataTable({
    <?= $scroller ?>
    <?= $selector ?>
    //keys: true,
    pageLength: <?= $length ?>,
    responsive: true,
    lengthMenu: [
        [10, 25, 50, 100, 150, 200, 500, -1],
        [10, 25, 50, 100, 150, 200, 500, "All"]
    ],

    dom: 'lfrtipB',
    fixedHeader: false,
    initComplete: function(settings, json) {
        $('#loadingObject').css('display', 'none');
        $('#<?= $table ?>').css('display', 'table')
    },

    drawCallback: function(settings) {

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


        {
            text: '<i class="fad fa-print duoBlue"></i>',
            className: 'me-2',
            action: function(e, dt, node, config) {
                // Capture the HTML content for printing
                var content = generatePrintContent(dt);
                insertContentIntoWrapper(content);

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

                printContent('tableWrapper',
                    '<?= addslashes($pageTitle) ?> ');
            }
        },

        {
            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 ?>
    ],
    searchPanes: {
        cascadePanes: true,
        layout: 'columns-4',
        viewTotal: true
    },
    stateSave: true,
    "columnDefs": [{
        "targets": 'no-sort',
        "orderable": false,
        "destroy": true
    }],
    "aaSorting": [],
    fixedHeader: false

});
// $('#<?= $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 data = table
    .rows()
    .data();

if (data.length == 0) {}
</script>
<?php if ($filter == 1) { ?>
<div class="row remove">
    <div class="col-md-6 remove">

        <button type="button" class="btn color bg-white filterButtons btn-sm remove mt-3"
            onClick="clearSearcher()">&nbsp;<i class="fad fa-refresh" aria-hidden="true"></i> Reset
            Filters&nbsp;</button>

    </div>
</div>
<?php } ?>

<script>
$('.dtsp-panesContainer').find('.btn').each(function() {
    $(this).addClass('p-0').removeClass('btn-light').addClass('btn-secondary')
});

// Print functions remain the same
function generatePrintContent(dt) {
    var tableData = dt.buttons.exportData({
        columns: function(idx, data, node) {
            return !$(node).hasClass('noExport');
        }
    });

    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 insertContentIntoWrapper(content) {
    const wrapper = document.getElementById('tableWrapper');
    if (wrapper) {
        wrapper.innerHTML = content;
    }
}
</script>
<div id="tableWrapper" class="d-none"></div>