<link href="https://cdn.datatables.net/v/bs4/jszip-3.10.1/dt-1.13.6/b-2.4.2/b-html5-2.4.2/b-print-2.4.2/fh-3.4.0/r-2.5.0/sc-2.2.0/sb-1.6.0/sp-2.2.0/sl-1.7.0/sr-1.3.0/datatables.min.css" rel="stylesheet">

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/v/bs4/jszip-3.10.1/dt-1.13.6/b-2.4.2/b-html5-2.4.2/b-print-2.4.2/fh-3.4.0/r-2.5.0/sc-2.2.0/sb-1.6.0/sp-2.2.0/sl-1.7.0/sr-1.3.0/datatables.min.js"></script>

<script type="text/javascript" src="packages/dfinance/moment.js"></script>

<style>
.success-color-dark {
    background-color: #28a745;
}

.warning-color-dark {
    background-color: #ffc107;
}

.danger-color-dark {
    background-color: #dc3545;
}

.success-color-dark,
.warning-color-dark,
.danger-color-dark {
    width: 5px !important;
    /* Set the width */
    height: 100%;
    /* Set the height to fill the entire cell */
    border-radius: 5px;
    /* Optional: Add rounded corners */
    padding: 0 !important;
}

/* Remove text content from the cell */
td.success-color-dark,
td.warning-color-dark,
td.danger-color-dark {
    color: transparent;
    font-size: 0 !important
}
</style>
<table class="table" id="dataTable"></table>
<?php  $table="assetTable";
    $dateTarget="8";
    $sortTarget="1";
    $sortCell="nth-child(2)";
    $logo="yes";
    $length="10";?>
<script>
var table = $('#dataTable').DataTable({
    serverSide: true,
    processing: true,
    ajax: {
        url: 'includes/client/client-asset_server-data.php',
        type: 'POST',
        data: function(d) {
            d.clientNumber = <?= $_REQUEST['clientnumber'] ?>;
        },

    },
    columns: [
        // Status (colored based on "duedate")
        {
            title: '',
            data: 'duedate',
            sorting: false,
            paging: true,
            createdCell: function(td, cellData, rowData, row, col) {
                var dueDate = new Date(cellData * 1000); // Convert Unix timestamp to milliseconds
                var today = moment().startOf('day');
                var statusClass = '';

                if (dueDate < today) {
                    statusClass = 'danger-color-dark'; // Past due (dark color)
                } else if (dueDate <= today.clone().add(30, 'days')) {
                    statusClass = 'warning-color-dark'; // Within 30 days (warning color)
                } else {
                    statusClass = 'success-color-dark'; // Over 30 days (success color)
                }

                $(td).addClass(statusClass);
            }
        },
        // Select checkbox
        {
            data: null,
            className: 'select-checkbox',
            orderable: false,
            width: '10px',
            render: function(data, type, row) {
                return '';
            }
        },
        // Item ID
        {
            title: 'Item ID',
            data: 'itemnumber'
        },
        // Description
        {
            title: 'Description',
            data: 'desc'
        },
        // Plantnumber
        {
            title: 'Plant Number',
            data: 'plantnumber'
        },
        // Serialnumber
        {
            title: 'Serial Number',
            data: 'serialnumber'
        },
        // Location
        {
            title: 'Location',
            data: 'locname'
        },
        // Post Code
        {
            title: 'Postcode',
            data: 'postcode'
        },
        // Due date (UK formatted and sortable)
        {
            title: 'Duedate',
            data: 'duedate',
            render: function(data, type, row) {
                var dueDate = new Date(data * 1000);
                var ukFormattedDate = moment(dueDate).format('DD/MM/YYYY');
                return `<span data-order="${data}">${ukFormattedDate}</span>`;
            }
        },
        // Result
        {
            title: 'Result',
            data: 'latest_report_result'
        },
        // Column with buttons
        {
            data: null,
            render: function(data, type, row) {
                var buttonGroupHtml = `
                <div class="btn-group" role="group" style="float:right">

<?= $locNoteAlert?>

<?php if($isLink=="yes"){?>
<a href="index.php?t=includes/master&p=linked.php&clientnumber=${row.clientnumber}&itemnumber=${row.itemnumber}" class="btn btn-secondary noprint me-2" data-toggle="tooltip"
   data-placement="top" title="<?= $ldesc?>"><i class="fad fa-link"></i> C<?= $lcount?></a>
<?php }?>

<a href="javascript:void(0)" class="btn btn-secondary noprint formButton me-2 " data-values="${row.clientnumber}|${row.locnumber}|${row.itemnumber}"
   data-href="includes/master/form.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="New Report"><i class="fad fa-file-alt" aria-hidden="true"></i></a>

<a href="index.php?t=includes/master&p=items.php&data=${row.clientnumber}|${row.locnumber}|${row.itemnumber}&view=list" class="btn btn-secondary noprint filesButton me-2"
   data-values="${row.clientnumber}|${row.locnumber}|${row.itemnumber}" data-href="includes/master/files.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" 
   title="Completed Report"><i class="fad fa-copy" aria-hidden="true"></i></a>

<a href="javascript:void(0)" class="btn btn-secondary noprint transferButton me-2"
   data-values="${row.clientnumber}|${row.locnumber}|${row.itemnumber}|${row.desc}" data-href="includes/master/transfer.php" data-toggle="tooltip"
   data-placement="top" title="Transfer Item"><i class="fad fa-exchange-alt" aria-hidden="true"></i></a>

<a href="javascript:void(0)" class="btn btn-secondary noprint formButton me-2" data-values="${row.clientnumber}|${row.locnumber}|${row.itemnumber}|${row.desc}"
   data-href="includes/master/clone.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Clone Item"><i class="fad fa-clone" aria-hidden="true"></i></a>

<?php if($_REQUEST['filter']=="archive"){$armode="activate"; $aricon="fad fa-upload"; $artitle="Reinstate Item";}
else{$armode="archive"; $aricon="fad fa-archive"; $artitle="Archive Item";}?>
<a href="javascript:void(0)" class="btn btn-secondary noprint archiveButton me-2" data-values="${row.clientnumber}|${row.locnumber}|${row.itemnumber}|<?= $armode?>"
   data-href="includes/master/archive.php" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="<?= $artitle?>"><i class="<?= $aricon?>" aria-hidden="true"></i></a>

<a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=${row.clientnumber}|${row.locnumber}|${row.itemnumber}" class="btn btn-secondary noprint me-2"
   data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Item Details"><i class="fad fa-info-circle" aria-hidden="true"></i></a>

<?= $itemNoteAlert?>

</div>
                `;
                return buttonGroupHtml;
            }
        },

    ],
    pageLength: <?= $length?>,
    responsive: true,
    lengthMenu: [
        [10, 25, 50, 100, 150, 200, 500, -1],
        [10, 25, 50, 100, 150, 200, 500, "All"]
    ],

    select: {
        style: 'multi',
        selector: 'td:<?=$sortCell?>'
    },
    dom: 'lBfrtipB',
    fixedHeader: true,
    initComplete: function(settings, json) {
        $('#loadingObject').css('display', 'none');
        $('#<?= $table?>').css('display', 'table')
    },
    drawCallback: function(settings) {
        $(".renewDatepicker").pickadate({
            format: "dd-mm-yyyy",
            formatSubmit: "dd-mm-yyyy",
            selectMonths: true,
        });
        $('[data-toggle="tooltip"]').tooltip({
            trigger: 'hover'
        }), $('[data-toggle="popover"]').popover({
            trigger: 'hover',
            html: true
        })

    },

    buttons: [
        'selectAll',
        'selectNone',

        {

            extend: 'print',
            title: '',
            text: '',
            orientation: 'landscape',
            pageSize: 'A4',
            header: true,
            footer: true,
            className: 'fad fa-print fa-2x  me-3 duoBlue',
            exportOptions: {
                columns: "thead th:not(.noExport),span:not(.noExport)",
                orientation: 'landscape',
                pageSize: 'A4',
                orthogonal: 'export',
                stripHtml: false,
                modifier: {
                    page: 'current'
                }
            },
            repeatingHead: {
                logo: 'images/company/logo_thumb.jpg',
                logoPosition: 'left',
                logoStyle: '',
                orientation: 'landscape',
                pageSize: 'A4',
                title: $('#exportTitle').text()
            },
            customize: function(win) {

                $(win.document.body).css('font-size', '10pt').prepend('<img src="../../images/company/logo_thumb.jpg" style="position:absolute; top:0; left:0;" />');
                $(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:#353b50')
                $(win.document.body).find('table th:nth-child(5)').attr('style', 'width:20%;color:#353b50')
                $(win.document.body).find('table th:nth-child(6)').attr('style', 'width:20%;color:#353b50')
                $(win.document.body).find('table th:nth-child(7)').attr('style', 'width:20%;color:#353b50')
                $(win.document.body).append('<br><br>Generated by EnRep Reporting System: <?= date('d-m-Y')?>');

            }
        },

        {
            extend: 'csvHtml5',
            title: $('#exportTitle').text(),
            text: '',
            className: 'fad fa-file-excel fa-2x 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-2x 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];
            }
        }

    ],

    "stateSave": true,
    "stateSaveParams": function(settings, data) {
        delete data.select;
    },
    "stateLoadParams": function(settings, data) {
        delete data.select;
    },



});

// Enable DataTables Select feature


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

$(function() {
    $('[data-toggle="tooltip"]').tooltip({
        trigger: 'hover'
    })

})

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

// 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;
    }
});
</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" onClick="clearSearcher()">&nbsp;<i class="fad fa-refresh" aria-hidden="true"></i> Reset Filters&nbsp;</button>

    </div>
</div>
<?php }?>
<style>
.dtsp-nameButton {
    display: none
}

.dtsp-countButton {
    display: none
}

.dtsp-collapseButton {
    display: none
}

.dtsp-showAll {
    display: none
}

.dtsp-collapseAll {
    display: none
}

@media print {

    html,
    body {
        height: auto;
    }

    .dt-print-table,
    .dt-print-table thead,
    .dt-print-table th,
    .dt-print-table tr {
        border: 0 none !important;
    }

    .dt-print-table td a {
        border: 0 none !important;
        text-decoration: none !important;
    }
}
</style>
<script>
$('.dt-buttons').find('.btn').each(function() {
    $(this).addClass('btn-sm').addClass('me-3').removeClass('btn-light').addClass('btn-secondary')
});
</script>