<div id="loading"></div>
<?php
// parameters
$src = '';
if ($logo === 'yes') {
    $path = '../' . TENANT_URL . '/images/company/logo.jpg';
    if (is_file($path)) {
        $imageData = base64_encode(file_get_contents($path));
        $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>
function initMdbOverlays(container = document) {
  // Tooltips
  container.querySelectorAll('[data-mdb-toggle="tooltip"],[data-mdb-tooltip-init]').forEach(el => {
    const inst = mdb.Tooltip.getInstance(el);
    if (inst) inst.dispose();
    new mdb.Tooltip(el);
  });

  // Popovers
  container.querySelectorAll('[data-mdb-toggle="popover"],[data-mdb-popover-init]').forEach(el => {
    const inst = mdb.Popover.getInstance(el);
    if (inst) inst.dispose();
    new mdb.Popover(el);
  });
}


$('#<?= $table ?>').DataTable({
    processing: true,
    keys: true,
    order: [
        [<?= $dateTarget ?>, "asc"] // Set default order to descending
    ],
    columnDefs: [{
            targets: <?= $dateTarget ?>,
            type: 'num', // Change type to 'num' for numeric sorting
            render: function(data, type, row) {
                // Convert date to pure numeric format for sorting
                if (type === 'sort' || type === 'type') {
                    var date = moment(data, "DD-MM-YYYY", true);
                    return date.isValid() ? parseInt(date.format("YYYYMMDD")) : 0;
                }
                // Return the original date format for display
                var displayDate = moment(data, "DD-MM-YYYY", true);
                return displayDate.isValid() ? displayDate.format("DD-MM-YYYY") : data;
            }
        },
        <?php if (!empty($sortCell)) { ?> {
            orderable: false,
            className: 'select-checkbox selectable me3',
            targets: <?= $sortTarget ?>
        }
        <?php } ?>
    ],

    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: [
        {
        extend: 'selectAll',
        text: 'Select All',
        action: function (e, dt) {
          // clear previous selections across all pages
          dt.rows({ page: 'all' }).deselect();
          // select only current page + current filter
          const idx = dt.rows({ search: 'applied', page: 'current' }).indexes();
          dt.rows(idx).select();
        }
      },
      {
        extend: 'selectNone',
        text: 'Deselect',
        action: function (e, dt) {
          // deselect only current page
          const idx = dt.rows({ selected: true, search: 'applied', page: 'current' }).indexes();
          dt.rows(idx).deselect();
        }
      },
        {
            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(getClientName($_REQUEST['clientnumber'])) ?> Schedule');
            }
        },
        {
            extend: 'csvHtml5',
            title: $('#exportTitle').text(),
            text: '',
            className: 'fad fa-file-excel me-2 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 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)) { ?>
                const logoData = <?= json_encode($src) ?>;
                doc['header'] = (function() {
                    return {
                        columns: [{
                            image: logoData,
                            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];
            }
        }
    ],
    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;
    }
});

// Custom sorting for DD-MM-YYYY date format
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "date-pre": function(a) {
        var date = moment(a, "DD-MM-YYYY", true); // Use strict parsing to include year correctly
        return date.isValid() ? parseInt(date.format('YYYYMMDD')) :
            0; // Return formatted date as an integer 'YYYYMMDD' for sorting
    },
    "date-asc": function(a, b) {
        return a - b;
    },
    "date-desc": function(a, b) {
        return b - a;
    }
});

// Other functions remain the same
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 > 1) {
        $('#massReport').css('display', 'inline-block');
        $('#massReport').attr("onclick", "massReport('" + selectedRowsIDs.join(',') + "')");
        $('#massUnlink').css('display', 'inline-block');
        $('#massUnlink').attr("onclick", "massUnlink('" + selectedRowsIDs.join(',') + "')");

    }

});
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 < 2) {
        $('#massReport').css('display', 'none');
        $('#massReport').attr('onclick', '');
        $('#massUnlink').css('display', 'none');
        $('#massUnlink').attr('onclick', '');

    }

});


const $tbl = $('#<?= $table ?>');
$tbl.on('init.dt draw.dt', function () {
  initMdbOverlays(this);
});


// 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;
    }
}

const mqSmOnly = window.matchMedia('(min-width: 576px) and (max-width: 767.98px)');

function applySmOnly() {
    const nodes = document.querySelectorAll('.dt-search');
    nodes.forEach(el => {
        if (mqSmOnly.matches) el.classList.add('mt-sm-2');
        else el.classList.remove('mt-sm-2');
    });
}

// run whenever tables render new toolbars
const obscheck = new MutationObserver(() => applySmOnly());
obscheck.observe(document.body, {
    childList: true,
    subtree: true
});

// initial + on breakpoint change
document.addEventListener('DOMContentLoaded', applySmOnly);
(mqSmOnly.addEventListener ? mqSmOnly.addEventListener('change', applySmOnly) :
    mqSmOnly.addListener(applySmOnly));
    
</script>
<div id="tableWrapper" class="d-none"></div>