<?php
function checkMode()
{
    $recall = mysqli_query($GLOBALS['con'], "SELECT `systemMode` FROM `clientdetails` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'");
    $result = mysqli_fetch_assoc($recall);
    if ($result['systemMode'] == 1) { ?>
<Script>
location.href = 'index.php?t=includes/master&p=elec.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>'
</Script>

<?php die();
    }
}
checkMode();

function getRenewal($client)
{
    $lcheck = mysqli_query($GLOBALS['con'], "SELECT `renewal_date` FROM `clientdetails` WHERE `clientnumber`='" . $client . "'");
    $ln = mysqli_fetch_array($lcheck);
    $renewal = $ln['renewal_date'];
    if (is_numeric($renewal)) {
        $now = new \DateTime();
        $renewal_date = date('d-m-Y', $renewal);
        $current_date = $now->format('d-m-Y');
        $onemonth = $now->sub(new \DateInterval('P1M'));
        //$twomonth = $now->sub(new \DateInterval('P2M'));
        $om = $onemonth->format('d-m-Y');
        //$tm=$twomonth->format('d-m-Y');

        $datetime1 = new \DateTime($current_date);
        $datetime2 = new \DateTime($renewal_date);
        $difference = $datetime1->diff($datetime2);

        $days = $difference->format("%r%a");
        if (strpos($days, '-') !== false) {
            $day = $difference->format("%a") . ' days ago';
        } else {
            $day = 'in ' . $days . ' days';
        }

        if ($days == 0 && (date('m', $renewal) == date("m"))) {
            $ret = '<div class="alert alert-success success-color-dark text-light text-center m-0" style="padding:3px">Renewal due today (' . $renewal_date . ')' . $om . '</div>';
        } elseif (($days < 30 && $days > 0) && (date('m', $renewal) == date("m"))) {
            $ret = '<div class="alert alert-warning warning-color-dark text-light text-center m-0" style="padding:3px">Renewal due ' . $day . ' (' . $renewal_date . ')</div>';
        } elseif (date('m-Y', $renewal) == date("m-Y")) {
            $ret = '<div class="alert alert-danger danger-color-dark text-light text-center m-0" style="padding:3px">Renewal due ' . $day . ' (' . $renewal_date . ')</div>';
        } else {
            $ret = '';
        }
    }
    return $ret;
}

$sites = getsites($_REQUEST['clientnumber'], ''); ?>
<style>
.selected td,
.selected td a :not(.btn, i) {
  color: #fff !important;
}

.selected td .btn {
  color: #000 !important;
}
</style>
<div id="infoRow" class="row bg-light mt-n4 pt-3 ms-lg-n3" style="position:fixed; width:100%; z-index:10">
    <div class=" col-12 col-md-3">
        <?= getRenewal($_REQUEST['clientnumber']) ?>
    </div>

    <div id="exportTitle" style="display:none; background-color:#353b50; color:#ffffff">
        <p style="font-size:12px"><a href="">Client List</a> : <a
                href=""><?= getClientName($_REQUEST['clientnumber']) ?></a> : <a href="">Schedule</a> : <a
                href="">Active Items</a></p>
    </div>

    <div id="mainToolbar" class="col-12 col-md-9 text-center text-md-end mb-sm-0">
        <?php if ($_REQUEST['filter'] == "" || $_REQUEST['filter'] == "current") { ?>

        <a href="javascript:void(0)"
            onclick="loadModalContent('<?= ROOT_URL ?>/includes/client/client-plant.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=<?= TENANT_URL ?>','popupBox', 'modal-xl', 1060, 'true','Plant Summary','close')"
            style="z-index:999" class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="Client plant summary"><i class="fa-duotone fa-clipboard-list"></i></a>

        <a href="javascript:void(0)"
            onclick="printSchedule('<?= ROOT_URL ?>/functions/print_schedule.php', 'Schedule','<?= $_REQUEST['clientnumber'] ?>')"
            class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="Pretty print schedule"><i class="fad fa-print"></i></a>

        <a href="index.php?t=includes/client&p=client_schedule_print.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>"
            class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="Custom Print"><i class="fad fa-cog"></i> <i class="fad fa-print"></i></a>

        <a id="newAsset" href="javascript:void(0)" class="btn btn-sm btn-secondary formButton mb-3"
            data-values="<?= $_REQUEST['clientnumber'] ?>|<?= $ld['locnumber'] ?>|<?= $id['itemnumber'] ?>"
            data-href="<?= ROOT_URL ?>/includes/master/formnew.php" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="Register Asset"><i class="fad fa-plus" aria-hidden="true"></i> New
            Asset</a>

        <a id="newSite"
            href="index.php?t=includes/master&p=locations.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&clientname=<?= getClientName($_REQUEST['clientnumber']) ?>&view=new&ref=asset"
            class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="New Location"><i class="fad fa-building" aria-hidden="true"></i> New
            Location</a>
        <?php if ($_SESSION['delivery'] != 0) { ?>
        <a href="index.php?t=includes/master&p=delivery.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>"
            class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="Report Delivery"><i class="fad fa-share-square" aria-hidden="true"></i>
            Deliver Reports</a>
        <?php } ?>

        <?php if (checkTemp($_REQUEST['clientnumber']) == 1) { ?>
        <a href="index.php?t=includes/master&p=items.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=incomplete"
            class="btn btn-sm btn-info mb-3" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Report Delivery"><i class="fad fa-hourglass-half  fa-spin"></i>&nbsp;&nbsp;Incomplete Reports</a>
        <?php } ?>

        <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=asset&filter=archive"
            class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="View Archived Assets"><i class="fad fa-archive" aria-hidden="true"></i>
            View Archived Items</a>


        <?php if ($_SESSION['access'] == 1 || $_SESSION['access'] == 2 || $_SESSION['access'] == 999) { ?>
        <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=edit"
            class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="View Client Details"><i class="fad fa-info-circle"></i></a>
        <?php } else { ?>
        <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=load"
            class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="View Client Details"><i class="fad fa-info-circle"></i></a>
        <?php } ?>



        <script>
        document.getElementById('navBox').innerHTML =
            '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=edit"><?= addslashes(getClientName($_REQUEST['clientnumber'])) ?></a><i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Schedule: Active Items</li>';
        </script>
        <?php }
        if ($_REQUEST['filter'] == "archive") { ?>

        <div id="exportTitle" style="display:none">
            <p style="font-size:12px"><a href="">Client List</a> : <a
                    href=""><?= getClientName($_REQUEST['clientnumber']) ?></a> : <a href="">Schedule</a> : <a
                    href="">Archived Items</a></p>
        </div>

        <a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=asset&filter=current"
            class="btn btn-secondary btn-sm"><i class="fad fa-upload" aria-hidden="true"></i> View Active
            Items</a>
        <script>
        document.getElementById('navBox').innerHTML =
            '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=load"><?= getClientName($_REQUEST['clientnumber']) ?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item active">Schedule: Archive Items</li>';
        </script>
        <?php } ?>
        <a id="lightmode" href="javascript:void(0)" onclick="scheduleMode('light')"
            class="btn btn-secondary btn-sm mb-3" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="Light Mode"><i class="fa-duotone fa-feather"></i></a>
    </div>

    <div id="massToolbar" class="col-12 col-md-9 text-center text-md-end" style="display:none">
        <a id="massMigrate" href="javascript:void(0)" onclick="massMigrate()" class="btn btn-sm btn-info mb-3"
            data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" title="Mass Item move"><i
                class="fad fa-grid"></i> Item move</a>

        <a id="massArchive" href="javascript:void(0)" onclick="massArchive()" class="btn btn-sm btn-info mb-3"
            data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" title="Mass Item archive"><i
                class="fad fa-file-archive"></i> Item Archive</a>

        <a id="massChain" href="javascript:void(0)" onclick="massChain()" class="btn btn-sm btn-info mb-3"
            data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" title="Mass Chain Items"><i
                class="fad fa-link-horizontal"></i> Chain Items</a>

        <a id="massMoveChain" href="javascript:void(0)" onclick="massMoveChain()" class="btn btn-sm btn-info mb-3"
            data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" title="Move Chain Items"><i
                class="fad fa-link-horizontal"></i> Move/Remove Chain Items</a>

        <a id="massCode" href="javascript:void(0)" onclick="massCode()" class="btn btn-sm btn-info mb-3"
            data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" title="Mass Item Code Change"><i
                class="fad fa-square-terminal"></i> Code Change</a>

        <a id="massPNA" href="javascript:void(0)" onclick="massPNA()" class="btn btn-sm btn-dark mb-3"
            data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" title="Mass Item Code Change"><i
                class="fad fa-subtitles-slash"></i> PNA Items</a>
    </div>
</div>



<?php
if ($_REQUEST['filter'] == "archive") {
    $status = 0;
} else {
    $status = 1;
}

$lcheck = mysqli_query($GLOBALS['con'], "SELECT `locnumber` FROM `locations` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
$ln = mysqli_num_rows($lcheck);

$icheck = mysqli_query($GLOBALS['con'], "SELECT `itemnumber` FROM `itemdetails` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
$in = mysqli_num_rows($icheck);

$origincheck = $ln + $in;

if ($ln == 0 || $in == 0) { ?>

<div id="pageAlert" class="d-block mt-5"></div>
<div class="container pt-5 my-5 z-depth-1">
    <section class="p-md-3 mx-md-5 text-lg-left">
        <div class="row text-center d-flex justify-content-center mt-4">
            <div id="S1" class="col-lg-4 col-md-6 mb-5">
                <i class="fad fa-building indigo-text fa-3x mb-4"></i>
                <h4 class="font-weight-bold mb-4">Define At least One location</h4>
                <p class="text-muted px-2 mb-lg-0">All schedules require a location, this can also be the same as the
                    client address.</p>
            </div>
            <div id="S2" class="col-lg-4 col-md-6 mb-5">
                <i class="fad fa-starship-freighter green-text fa-3x mb-4"></i>
                <h4 class="font-weight-bold mb-4">Add Assets</h4>
                <p class="text-muted px-2 mb-lg-0">Once you have defined a location, begin adding your assets.</p>
            </div>
            <div id="S3" class="col-lg-4 col-md-6 mb-5">
                <i class="fad fa-search blue-text fa-3x mb-4"></i>
                <h4 class="font-weight-bold mb-4">Inspect</h4>
                <p class="text-muted px-2 mb-md-0">You have your location, registered assets. Now you can inspect.</p>
            </div>
        </div>
    </section>
</div>
<script>
<?php if ($ln < 1) { ?>
// Apply styles to #S2 and #S3
applyGrayscaleOpacity('S2');
applyGrayscaleOpacity('S3');

// Set the page alert message
const pageAlert = document.getElementById('pageAlert');
if (pageAlert) {
    pageAlert.innerHTML =
        '<div class="col-md-12 alert alert-warning text-center mt-5"><b>You have no locations defined for this client</b></div>';
}

// Update the newSite button's styling
updateButtonStyling('newSite', 'btn-info', '#ffffff');
<?php } else { ?>
// Apply styles to #S1 and #S3
applyGrayscaleOpacity('S1');
applyGrayscaleOpacity('S3');

// Set the page alert message
const pageAlert = document.getElementById('pageAlert');
if (pageAlert) {
    pageAlert.innerHTML =
        '<div class="col-md-12 alert alert-warning text-center mt-5"><b>You have no assets defined for this client</b></div>';
}

// Update the newAsset button's styling
updateButtonStyling('newAsset', 'btn-info', '#ffffff');

// Hide elements with class 'remove'
const removeElements = document.querySelectorAll('.remove');
removeElements.forEach(element => {
    element.style.display = 'none';
});
<?php } ?>

// Helper functions for applying styles
function applyGrayscaleOpacity(elementId) {

    const element = document.getElementById(elementId);
    if (element) {
        element.style.opacity = '0.3';
        element.style.filter = 'grayscale(100%)';
        element.style.WebkitFilter = 'grayscale(100%)'; // For older browsers
    }
}

function updateButtonStyling(buttonId, addClass, color) {
    const button = document.getElementById(buttonId);
    if (button) {
        console.log(`Updating button: ${buttonId}`); // Debugging log
        button.classList.remove('btn-secondary');
        button.classList.add(addClass);
        button.style.color = color;
    } else {
        console.warn(`Button with ID "${buttonId}" not found.`);
    }
}

document.addEventListener('DOMContentLoaded', function() {

    document.body.addEventListener('click', function(event) { // Event delegation on body
        if (event.target.classList.contains('formButton') ||
            event.target.classList.contains('transferButton') ||
            event.target.classList.contains('archiveButton')) {

            const target = event.target.dataset.href;
            const string = event.target.dataset.values;
            const dest = encodeURI(target + "?data=" + string + "&tenant=" +
                TENANT_URL); // Assuming TENANT_URL is defined globally

            loadModalContent(dest, "popupBox", "modal-xxl", 1060, "true", "New Item");
        }
    });

    // Hide elements with class 'remove'
    const removeElements = document.querySelectorAll('.remove');
    removeElements.forEach(element => {
        element.style.display = 'none';
    });

});
</script>
<?php } else { ?>
<div id="loadingObject">
    <h1 class="text-center"><i class="fad fa-flux-capacitor fa-spin fa-3x fa-fw"
            style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Loading Schedule <br><small>Please
            wait</small>
    </h1>
</div>
<?php

    $stmt = $GLOBALS['con']->prepare("SELECT 
        a.itemnumber, a.locnumber, a.desc, a.subloc, a.code, a.currdate, a.plantnumber, a.lastReport, a.serialnumber, a.model, a.dateofmanf, a.manf, a.swl, a.duedate, a.linked, a.itemnotes, a.statuslive, 
        b.locnumber, b.locname, b.locaddress1, b.locaddress2, b.locaddress3, b.locaddress4, b.locnotes, b.postcode      
        
        FROM itemdetails a 
        INNER JOIN locations b ON (b.locnumber=a.locnumber)            
        WHERE a.clientnumber='" . $_REQUEST['clientnumber'] . "' AND a.statuslive='" . $status . "'") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $ic = $stmt->get_result();
    $stmt->close();
    $c = 1;

    ?>
<div style="height:70px" class="d-block d-lg-none"></div>
<div id="pageAlert" class="mt-5"></div>

<div class="row mt-sm-5">
    <div class="col-md-6 mb-3 text-center text-md-start">
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Filter Overdue inspections" class="btn danger-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Overdue','assetTable')">&nbsp;Overdue&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Filter Pending inspections" class="btn warning-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Pending','assetTable')">&nbsp;Pending&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Filter inspections not due" class="btn success-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Not_Due','assetTable')">&nbsp;Not
            Due&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Reset filters" class="btn color bg-white filterButtons btn-sm"
            onClick="clearSearch('assetTable')">&nbsp;<i class="fad fa-refresh" aria-hidden="true"></i>
            Reset Filters&nbsp;</button>

    </div>
</div>

<div id="selectedItems" style="display:none"></div>
<div class="row mt-4">
    <div class="col-12">
        <table id="assetTable" class="dt-print-table table table-striped table-sm table-bordered table-hover responsive"
            width="100%" style="width:100%;">
            <thead>
                <tr>
                    <th class="no-sort noExport text-center p-0 text-hidden" width="10px"></th>
                    <th class="no-sort noExport" style="width:30px"></th>
                    </th>
                    <th>Item ID</th>
                    <th>Description</th>
                    <th>Plant Number</th>
                    <th>Serial Number</th>
                    <th>Location</th>
                    <th>Postcode</th>
                    <th class="date-uk">Due Date</th>
                    <th>Result</th>
                    <th class="no-sort noExport"></th>
                </tr>
            </thead>
            <tbody>
                <?php
                    $assignments = array();
                    $SurveyorFilterArray = array();



                    if ($_SESSION['usertype'] == "surveyor" && $_SESSION['access'] == 3 && $_REQUEST['view'] == "asset") {

                        $status = "1";

                        // Get assignments
                        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `surveyor_assignments` WHERE `surveyor` = ? AND `client_id` = ? AND `status` = '1'");
                        $stmt->bind_param("ss", $_SESSION['userid'], $_REQUEST['clientnumber']);
                        $stmt->execute();
                        $ac = $stmt->get_result();
                        $stmt->close();

                        while ($ds = mysqli_fetch_array($ac)) {
                            $assignments[] = $ds;
                        }

                        foreach ($assignments as $assign) {
                            if ($assign['asset_id'] == "0") {
                                $query = "SELECT `itemnumber` FROM `itemdetails` WHERE `clientnumber` = ? AND `locnumber` = ? AND `statuslive` = ?";
                                $itemAssign = $GLOBALS['con']->prepare($query);
                                $itemAssign->bind_param("iii", $assign['client_id'], $assign['site_id'], $status);
                                $itemAssign->execute();
                                $itemAssign->bind_result($itemnumber);
                                $tempArray = [];
                                while ($itemAssign->fetch()) {
                                    $tempArray[] = $itemnumber;
                                }
                                $itemAssign->close();
                                $SurveyorFilterArray = array_merge($SurveyorFilterArray, $tempArray);
                            } else {
                                $SurveyorFilterArray[] = $assign['asset_id'];
                            }
                        }
                    }

                    while ($id = mysqli_fetch_assoc($ic)) {
                        if (!in_array($id['itemnumber'], $SurveyorFilterArray) && $_SESSION['access'] == 3) {
                        } else {
                            
                            if ($id['locnotes'] != "") {
                                $locNoteAlert = '<a href="javascript:void(0)" class="btn btn-secondary noprint me-2" data-mdb-tooltip-init data-mdb-trigger="hover"  data-mdb-placement="top" title="Location notes Detected" onclick="loadModalContent(\'' . ROOT_URL . '/includes/master/notes.php?type=locations&locnumber=' . $id['locnumber'] . '&tenant=' . TENANT_URL . '\',\'locationBox\', \'modal-xl\', 1060, \'true\',\'Location Notes\',\'close\')"><i class="fad fa-location-question"></i>s</a>';
                            } else {
                                $locNoteAlert = '';
                            }

                            if ($id['itemnotes'] != "") {
                                $itemNoteAlert = '<a href="javascript:void(0)" class="btn unique-color-dark noprint me-2" data-mdb-tooltip-init data-mdb-trigger="hover"  data-mdb-placement="top" title="Item notes Detected" onclick="loadModalContent(\'' . ROOT_URL . '/includes/master/notes.php?type=itemdetails&itemnumber=' . $id['itemnumber'] . '&tenant=' . TENANT_URL . '\',\'itemBox\', \'modal-xl\', 1060, \'true\',\'Item Notes\',\'close\')"><i class="fad fa-file-exclamation"></i></a>';
                            } else {
                                $itemNoteAlert = '';
                            }

                            if ($id['lastReport'] == "DEFECTS") {
                                $col = " warning-color-dark";
                                $tag = "DEFECTS";
                                $resultTitle = "DEFECTS";
                                $resultText = $id['bdefect'];
                            }
                            if ($id['lastReport'] == "URGENT") {
                                $col = " danger-color-dark";
                                $tag = "URGENT";
                                $resultTitle = "URGENT";
                                $resultText = $id['adefect'];
                            }
                            if ($id['lastReport'] == "PASS") {
                                $col = " success-color-dark";
                                $tag = "PASS";
                                $resultTitle = "PASS";
                                $resultText = "The item passed examination<br>";
                            }
                            if ($id['lastReport'] == "OBS") {
                                $col = " special-color";
                                $tag = "OBS";
                                $resultTitle = "OBS";
                                $resultText = $id['obs'];
                            }
                            if ($id['lastReport'] == "PNA") {
                                $col = " stylish-color-dark";
                                $tag = "PNA";
                                $resultTitle = "PNA";
                                $resultText = $id['pnareason'];
                            }
                            if ($id['lastReport'] == "") {
                                $col = " secondary-color";
                                $tag = "P2UD";
                                $resultTitle = "NULL";
                                $resultText = "No report or report is prior to update<br>";
                            }


                            if ($id['duedate'] < strtotime('now')) {
                                $stat = "status_colour danger-color-dark";
                                $statTitle = "Overdue";
                            }
                            if ($id['duedate'] > strtotime('now') && $id['duedate'] < strtotime('now +1 month')) {
                                $stat = "status_colour warning-color-dark";
                                $statTitle = "Pending";
                            }
                            if ($id['duedate'] > strtotime('now +1 month')) {
                                $stat = "status_colour success-color-dark";
                                $statTitle = "Not_Due";
                                $statFTitle = "Not Due";
                            }
                            $ws = stripslashes(isWS($id['itemnumber']));
                            $lws = stripslashes(isLWS($id['itemnumber']));
                            if (empty($id['linked']) || $id['linked'] == "[]") {
                                $isLink = "no";
                            } else {
                                $linked = explode(":", $id['linked']);
                                $lcount = $linked[0];
                                $ldesc = $linked[2];
                                $isLink = "yes";
                            }
                            $freq = getFreq($id['code']);
                            $id['model'] = str_replace('"', '&quot;', $id['model']);
                    ?>
                <tr id="<?= $id['itemnumber'] ?>">
                    <td class="<?= $stat ?>" width="20px">
                        <div class="<?= $stat ?>" style="font-size:0px"><?= $statTitle ?></div>
                    </td>

                    <td id="C<?= $id['itemnumber'] ?>" data-value="C<?= $id['itemnumber'] ?>"></td>

                    <td><?= $id['itemnumber'] . $ws . $lws ?></td>

                    <td data-mdb-popover-init data-mdb-trigger="hover" data-mdb-html="true" data-mdb-container="body"
                        data-mdb-placement="right" title="<?= $id['desc'] ?> Information"
                        data-mdb-content="<b>Model:</b> <?= $id['model'] ?><br><b>Manufacturer:</b> <?= $id['manf'] ?><br><b>Date of Manufacture:</b> <?= $id['dateofmanf'] ?><br><b>SWL:</b> <?= $id['swl'] ?>">
                        <a class="sFilter2 " href="javascript:void(0)"
                            onclick="inlineFilter('<?= $id['desc'] ?>')"><?= $id['desc'] ?></a> <span
                            class="float-end no-print badge badge-info noExport" data-mdb-tooltip-init
                            data-mdb-trigger="hover" data-mdb-placement="right"
                            title="Examination Frequency: <?= $freq ?>Mths"><?= $freq ?></span>
                    </td>

                    <td><?= $id['plantnumber'] ?></td>

                    <td><?= $id['serialnumber'] ?></td>

                    <td><a class="sFilter2" href="javascript:void(0)"
                            onclick="inlineFilter('<?= $id['locname'] ?>')"><?= $id['locname'] ?>
                            <?php if ($id['subloc'] != "") {
                                            echo "(" . $id['subloc'] . ")";
                                        } ?></a></td>

                    <td data-mdb-popover-init data-mdb-trigger="hover" data-mdb-html="true" data-mdb-container="body"
                        data-mdb-placement="right" title="Address"
                        data-mdb-content="<?= $id['locaddress1'] ?><br> <?= $id['locaddress2'] ?><br><?= $id['locaddress3'] ?><br><?= $id['locaddress4'] ?><br><?= $id['postcode'] ?>">
                        <a class="sFilter2" href="javascript:void(0)"
                            onclick="inlineFilter('<?= $id['postcode'] ?>')"><?= $id['postcode'] ?></a>
                    </td>

                    <?php if (empty($id['duedate'])) { ?>
                    <td>NDS</td>
                    <?php } else { ?>
                    <td><?= date('d-m-Y', $id['duedate']) ?></td>
                    <?php } ?>
                    <td class="text-center"><a href="javascript:void(0)"
                            class="badge badge-<?= $col ?> text-light"><?= $resultTitle ?></a></td>
                    <td>
                        <div class="d-flex align-items-center" style="float:right">

                            <?= $locNoteAlert ?>

                            <?php if ($isLink == "yes") { ?>
                            <a class="btn btn-secondary noprint me-3 me-xl-2 mb-4 mb-xl-0 d-flex"
                                href="index.php?t=includes/master&p=linked.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&itemnumber=<?= $id['itemnumber'] ?>"
                                data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="top"
                                title="<?= $ldesc ?>"><i class="fad fa-link"></i> C<?= $lcount ?> <span
                                    class="d-xl-none">Chain</span></a>
                            <?php } ?>

                            <a href="javascript:void(0)"
                                class="btn btn-secondary noprint formButton me-3 me-xl-2 mb-4 mb-xl-0"
                                data-values="<?= $_REQUEST['clientnumber'] ?>|<?= $id['locnumber'] ?>|<?= $id['itemnumber'] ?>"
                                data-href="<?= ROOT_URL ?>/includes/master/form.php" data-mdb-tooltip-init
                                data-mdb-trigger="hover" data-mdb-placement="top" title="New Report"><i
                                    class="fad fa-file-alt" aria-hidden="true"></i> <span
                                    class="d-xl-none">New</span></a>

                            <a href="index.php?t=includes/master&p=items.php&data=<?= $_REQUEST['clientnumber'] ?>|<?= $id['locnumber'] ?>|<?= $id['itemnumber'] ?>&view=list"
                                class="btn btn-secondary noprint filesButton me-3 me-xl-2 mb-4 mb-xl-0"
                                data-values="<?= $_REQUEST['clientnumber'] ?>|<?= $id['locnumber'] ?>|<?= $id['itemnumber'] ?>"
                                data-href="<?= ROOT_URL ?>/includes/master/files.php" data-mdb-tooltip-init
                                data-mdb-trigger="hover" data-mdb-placement="top" title="Completed Report"><i
                                    class="fad fa-copy" aria-hidden="true"></i> <span class="d-xl-none">Edit</span></a>

                            <a href="javascript:void(0)"
                                class="btn btn-secondary noprint transferButton me-3 me-xl-2 mb-4 mb-xl-0"
                                data-values="<?= $_REQUEST['clientnumber'] ?>|<?= $id['locnumber'] ?>|<?= $id['itemnumber'] ?>|<?= $id['desc'] ?>"
                                data-href="<?= ROOT_URL ?>/includes/master/transfer.php" data-mdb-tooltip-init
                                data-mdb-trigger="hover" data-mdb-placement="top" title="Transfer Item"><i
                                    class="fad fa-exchange-alt" aria-hidden="true"></i> <span
                                    class="d-xl-none">Move</span></a>

                            <a href="javascript:void(0)"
                                class="btn btn-secondary noprint formButton me-3 me-xl-2 mb-4 mb-xl-0"
                                data-values="<?= $_REQUEST['clientnumber'] ?>|<?= $id['locnumber'] ?>|<?= $id['itemnumber'] ?>|<?= $id['desc'] ?>"
                                data-href="<?= ROOT_URL ?>/includes/master/clone.php" data-mdb-tooltip-init
                                data-mdb-trigger="hover" data-mdb-placement="top" title="Clone Item"><i
                                    class="fad fa-clone" aria-hidden="true"></i> <span
                                    class="d-xl-none">Clone</span></a>

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

                            <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=<?= $_REQUEST['clientnumber'] ?>|<?= $id['locnumber'] ?>|<?= $id['itemnumber'] ?>"
                                class="btn btn-secondary noprint me-3 me-xl-2 mb-4 mb-xl-0" data-mdb-tooltip-init
                                data-mdb-trigger="hover" data-mdb-placement="top" title="Item Details"><i
                                    class="fad fa-info-circle" aria-hidden="true"></i> <span
                                    class="d-xl-none">Info</span></a>

                            <?= $itemNoteAlert ?>

                        </div>
                    </td>

                </tr>
                <?php }
                    } ?>

            </tbody>
        </table>

        <?php
            $table = "assetTable";
            $dateTarget = "8";
            $length = "25";
            $sortTarget = "1";
            $sortCell = "nth-child(2)";
            $logo = "yes";
            $scroller = "";
            require(ROOT_URL . "/includes/tables/asset_table.php");

            ?>
    </div>
</div>
<div class="row mt-4 mt-sm-5">
    <div class="col-12 mt-3 text-center text-md-start">
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Filter Overdue inspections" class="btn danger-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Overdue','assetTable')">&nbsp;Overdue&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Filter Pending inspections" class="btn warning-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Pending','assetTable')">&nbsp;Pending&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Filter inspections not due" class="btn success-color-dark text-light filterButtons btn-sm"
            onClick="addSearch('Not_Due','assetTable')">&nbsp;Not
            Due&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom"
            title="Reset filters" class="btn color bg-white filterButtons btn-sm" onClick="clearSearch()">&nbsp;<i
                class="fad fa-refresh" aria-hidden="true"></i>
            Reset Filters&nbsp;</button>

    </div>
</div>

<div id="detailsBox" class="hidden"></div>

<script>
async function printSchedule(scriptPath, header, client = null) {
    try {
        showLoadingIndicator();
        // Construct the full script path with query parameters if a variable is provided
        const fullUrl =
            `${scriptPath}?clientnumber=${encodeURIComponent(client)}&tenant=${encodeURIComponent(TENANT_URL)}`;

        // Fetch content from the script
        const response = await fetch(fullUrl);
        if (!response.ok) {
            console.error('Failed to fetch content:', response.statusText);
            removeLoadingIndicator();
            return;
        }

        // Get the HTML content from the response
        const contentHtml = await response.text();
        removeLoadingIndicator();
        // Call the printContainer function with the fetched HTML content
        printContainer(contentHtml, {
            orientation: 'landscape', // or 'portrait'
            header: `<p>${header}</p>`,
            footer: `<p>Generated by EnRep Reporting System: ${new Date().toLocaleDateString()}</p>`,
            logoUrl: 'images/company/logo.jpg',
            styles: [
                `${ROOT_URL}/src/css/print.css`,
            ],
        });
    } catch (error) {
        console.error('Error fetching or processing content:', error);
        removeLoadingIndicator();
    }
}

<?php if (!empty($_REQUEST['search'])) { ?>

setTimeout(function() {
    $('#dt-search-0').val('<?= $_REQUEST['search'] ?>')
    $('#dt-search-0').keyup();
}, 500);
<?php } ?>
<?php
        if ($ln < 1) { ?>
$('#pageAlert').html(
    '<div class="col-md-12 alert alert-warning text-center"><b>You have no locations defined for this client</b></div>'
)
$('#newSite').removeClass('btn-secondary').addClass('btn-info').css('color', '#ffffff');
<?php } ?>


document.addEventListener('DOMContentLoaded', function() {
    document.body.addEventListener('click', function(event) {
        if (event.target.classList.contains('formButton') || event.target.classList.contains(
                'transferButton') || event.target.classList.contains('archiveButton')) {
            const popupBox = document.querySelector('#popupBox .modal-body');
            if (popupBox) {
                popupBox.innerHTML = '';
            }

            const target = event.target.getAttribute('data-href');
            const values = event.target.getAttribute('data-values');
            const title = event.target.getAttribute('data-mdb-original-title');
            const encodedDest = encodeURI(`${target}?data=${values}&tenant=${TENANT_URL}`);

            loadModalContent(encodedDest, 'popupBox', 'modal-xxl', 1060, 'true', title);
        }
    });
});


function inlineFilter(i) {
    var table = $('#assetTable').DataTable();
    table.search(i).draw();
};

function massMigrate() {
    var i = $('#selectedItems').text()
    var dest = encodeURI(ROOT_URL +
        '/includes/master/transfer.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=<?= TENANT_URL ?>&mode=mass&items=' +
        i)
    loadModalContent(dest, "transferBox", "modal-xl", 1060, "true", "Mass move items", "cancel");
}

function massArchive() {
    var i = $('#selectedItems').text()
    var dest = encodeURI(ROOT_URL +
        '/includes/master/archive.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=<?= TENANT_URL ?>&mode=mass&items=' +
        i)
    loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", "Mass archive items", "close");
}

function massCode() {
    var i = $('#selectedItems').text()
    var dest = encodeURI(ROOT_URL +
        '/includes/master/codeChange.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=<?= TENANT_URL ?>&mode=mass&items=' +
        i)
    loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", "Mass code change items", "close");
}

function massReinstate() {
    var i = $('#selectedItems').text()
    var dest = encodeURI(ROOT_URL +
        '/includes/master/archive.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=<?= TENANT_URL ?>&mode=reinstate&items=' +
        i)
    loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", "Mass reinstate items", "close");
}

function massChain() {
    var i = $('#selectedItems').text()
    var dest = encodeURI(ROOT_URL +
        '/includes/mass/massChain.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=<?= TENANT_URL ?>&items=' +
        i)
    loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", "Mass chain items", "close");
}

function massMoveChain() {
    var i = $('#selectedItems').text()
    var dest = encodeURI(ROOT_URL +
        '/includes/mass/massMoveChain.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=<?= TENANT_URL ?>&items=' +
        i)
    loadModalContent(dest, "popupBox", "modal-xl", 1060, "true", "Mass move chain items", "close");
}

function massPNA() {
    var i = $('#selectedItems').text()
    var dest = encodeURI(ROOT_URL +
        '/includes/mass/massPna.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&tenant=<?= TENANT_URL ?>&items=' +
        i)
    loadModalContent(dest, "pnaBoxes", "modal-xxl", 1060, "true", "Mass PNA items", "cancelConfirm", 'processPna');
}

//window.addEventListener('scroll', function() {
//    var infoRow = document.getElementById('infoRow');
//    if (window.scrollY > 0) {
//        infoRow.classList.add('scrolled');
//    } else {
//        infoRow.classList.remove('scrolled');
//    }
//});

const mqMdDown = window.matchMedia('(max-width: 1200px)');

function applyMdDown() {
  // dt-search: add mt-sm-2 when <992px
  document.querySelectorAll('.dt-search').forEach(el => {
    if (mqMdDown.matches) el.classList.add('mt-sm-2');
    else el.classList.remove('mt-sm-2');
  });

  // buttons: add btn-sm when <992px
  document.querySelectorAll('.btn').forEach(btn => {
    if (mqMdDown.matches) btn.classList.add('btn-sm');
    else btn.classList.remove('btn-sm');
  });
}

// Re-apply on DOM changes (DataTables toolbar render, etc.)
const obs = new MutationObserver(applyMdDown);
obs.observe(document.body, { childList: true, subtree: true });

// Init + react to breakpoint changes
document.addEventListener('DOMContentLoaded', applyMdDown);
(mqMdDown.addEventListener ? mqMdDown.addEventListener('change', applyMdDown)
                           : mqMdDown.addListener(applyMdDown));
</script>


<?php
}