<?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();
$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
$filter       = $_REQUEST['filter'] ?? 'live';
$status       = ($filter === 'archive') ? 0 : 1;
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'));
        $om = $onemonth->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'], ''); ?>

<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="ImportAsset" 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/asset/asset_import.php" data-mdb-tooltip-init data-mdb-trigger="hover"
            data-mdb-placement="bottom" title="Import Assets"><i class="fad fa-plus" aria-hidden="true"></i> Import
            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('default')"
            class="btn btn-info btn-sm m-0 px-3 mb-3" data-mdb-tooltip-init data-mdb-placement="bottom"
            data-mdb-trigger="hover" totitle="hover" title="Default Mode"><i class="fad fa-weight-scale"></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) {
        button.classList.remove('btn-secondary');
        button.classList.add(addClass);
        button.style.color = color;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    document.body.addEventListener('click', function(event) {
        if (event.target.closest('.formButton, .transferButton, .archiveButton')) {
            const button = event.target.closest('.formButton, .transferButton, .archiveButton');
            const target = button.dataset.href;
            const string = button.dataset.values;
            const dest = encodeURI(`${target}?data=${string}&tenant=${TENANT_URL}`);
            loadModalContent(dest, "popupBox", "modal-xxl", 1060, "true", "New Item");
        }
    });
});
</script>
<?php } else { ?>

<div id="loadingOverlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.8); z-index: 9999; display: flex; align-items: center; justify-content: center;">
    <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>

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

    <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" class="btn danger-color-dark text-light filterButtons" onclick="addSearch('Overdue','assetTable')" data-mdb-original-title="Filter Overdue inspections" >&nbsp;Overdue&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" class="btn warning-color-dark text-light filterButtons" onclick="addSearch('Pending','assetTable')" data-mdb-original-title="Filter Pending inspections" >&nbsp;Pending&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" class="btn success-color-dark text-light filterButtons" onclick="addSearch('Not_Due','assetTable')" data-mdb-original-title="Filter inspections not due" >&nbsp;Not
            Due&nbsp;</button>
        <button type="button" data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="bottom" class="btn color bg-white filterButtons" onclick="clearSearch('assetTable')" data-mdb-original-title="Reset filters" >&nbsp;<i class="fad fa-refresh" aria-hidden="true"></i>
            Reset Filters&nbsp;</button>

    </div>

    <table id="assetTable" class="table table-striped table-bordered table-hover table-sm" style="width:100%">
        <thead>
            <tr>
                <th class="status-col"></th>
                <th></th>
                <th>Description</th>
                <th>Plant No.</th>
                <th>Serial</th>
                <th>Location</th>
                <th>Sub-location</th>
                <th>Post Code</th>
                <th class="text-center">Result</th>
                <th>Due</th>
                <th class="text-center">Actions</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<div id="selectedItems" style="display:none"></div>
<style>
.selected td,
.selected td a :not(.btn, i) {
  color: #fff !important;
}

.selected td .btn {
  color: #000 !important;
}
    #assetTable > thead > tr > th:first-child,
    #assetTable > tbody > tr > td:first-child {
        width: 10px !important;
        min-width: 10px !important;
        max-width: 10px !important;
        padding: 0 !important;
    }
    .btn-secondary span {
    pointer-events: auto;
}
</style>

<script>
function statusTitle(row){
  const now = Math.floor(Date.now()/1000);
  const due = Number(row.duedate || 0);
  if (!due) return 'Status Unknown';
  if (due < now) return 'Overdue';
  if (due < now + 30*24*3600) return 'Pending';
  return 'Not Due';
}

$(document).ready(function () {
  const selectedRowsIDs = [];

  const table = $('#assetTable').DataTable({
    rowId: 'itemnumber',
    serverSide: true,
    processing: true,
    stateSave: true,
    deferRender: true,
    responsive: { details: { type: 'column', target: 2 } }, // description now col 3 (index 2)
    pageLength: 25,
    autoWidth: false,
    rowId: row => String(row.itemnumber),
    createdRow: (row, data) => {
      row.id = String(data.itemnumber);
      row.setAttribute('data-itemnumber', data.itemnumber);
    },
    dom: 'lBfrtipB',
    buttons: [
      {
        extend: 'selectAll',
        text: 'Select All',
        action: function (e, dt) {
          dt.rows({ page: 'all' }).deselect();
          const idx = dt.rows({ search: 'applied', page: 'current' }).indexes();
          dt.rows(idx).select();
          syncCheckboxes();
        }
      },
      {
        extend: 'selectNone',
        text: 'Deselect',
        action: function (e, dt) {
          const idx = dt.rows({ selected: true, search: 'applied', page: 'current' }).indexes();
          dt.rows(idx).deselect();
          syncCheckboxes();
        }
      }
    ],

    // selection only via the checkbox column
    select: {
      style: 'multi',
      selector: 'td.select-col input.row-select'
    },

    ajax: {
      url: ROOT_URL + '/includes/asset/asset_table_data.php',
      type: 'POST',
      data: d => {
        d.tenant = TENANT_URL;
        d.clientnumber = <?= (int)$clientnumber ?>;
        d.status = <?= (int)$status ?>;
      }
    },

    columns: [
      // 0) colour/status strip (keeps searchable status text hidden visually)
      {
        data: function(row){ return statusTitle(row); },
        orderable: false,
        searchable: true,
        render: function(data, type){
          if (type === 'display') return '<div style="font-size:0">' + data + '</div>';
          return data;
        },
        createdCell: function(td, data){
          let cls = 'secondary-color';
          if (data === 'Overdue') cls = 'danger-color-dark';
          else if (data === 'Pending') cls = 'warning-color-dark';
          else if (data === 'Not Due') cls = 'success-color-dark';
          td.classList.add('status_colour', cls);
          td.title = data;
        }
      },

      // 1) checkbox select column
      {
        data: null,
        orderable: false,
        searchable: false,
        className: 'select-col text-center',
        render: () => `<input type="checkbox" class="form-check-input row-select" aria-label="Select row">`
      },

      // 2) description (will get dtr-control on mobile)
      {
  data: null,
  orderable: true,
  searchable: true,
  render: function (_data, type, row) {
    if (type !== 'display') return row.description || '';

    const esc = s => String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;')
                                    .replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');

    const model = esc(row.model || '0');
    const manufacturer = esc(row.manf || '0');
    const dom = esc(row.dateofmanf || '0');
    const swl = esc(row.swl || '0');
    const desc = esc(row.description || '');
    const freq = row.frequency ? esc(row.frequency) : '';

    const popoverContent =
      `&lt;b&gt;Model:&lt;/b&gt; ${model}&lt;br&gt;` +
      `&lt;b&gt;Manufacturer:&lt;/b&gt; ${manufacturer}&lt;br&gt;` +
      `&lt;b&gt;Date of Manufacture:&lt;/b&gt; ${dom}&lt;br&gt;` +
      `&lt;b&gt;SWL:&lt;/b&gt; ${swl}`;

    const freqBadge = freq
      ? `<span class="float-end no-print badge badge-info noExport p-1 mt-n1" style="min-width:20px!important" >${freq}</span>`
      : '';

    return `
      <div class="position-relative"
           data-mdb-popover-init
           data-mdb-trigger="hover"
           data-mdb-html="true"
           data-mdb-container="body"
           data-mdb-placement="right"
           data-mdb-content="${popoverContent}">
        <a class="sFilter2" href="javascript:void(0)"
           onclick="inlineFilter(this.dataset.desc)" data-desc="${desc}">${desc}</a>
        ${freqBadge}
      </div>
    `;
  }
},

      { data: 'plantnumber' },
      { data: 'serialnumber' },
      {
  data: 'locname',
  render: function (data, type, row) {
    if (type !== 'display') return data || '';
    const val = String(data || '').replace(/"/g, '&quot;');
    return `<a class="sFilter2" href="javascript:void(0)" 
               onclick="inlineFilter(this.dataset.loc)" data-loc="${val}">${val}</a>`;
  }
},
         {
  data: 'subloc',
  render: function (data, type, row) {
    if (type !== 'display') return data || '';
    const val = String(data || '').replace(/"/g, '&quot;');
    return `<a class="sFilter2" href="javascript:void(0)" 
               onclick="inlineFilter(this.dataset.postcode)" data-postcode="${val}">${val}</a>`;
  }
},

      {
  data: 'postcode',
  render: function (data, type, row) {
    if (type !== 'display') return data || '';
    const val = String(data || '').replace(/"/g, '&quot;');
    return `<a class="sFilter2" href="javascript:void(0)" 
               onclick="inlineFilter(this.dataset.postcode)" data-postcode="${val}">${val}</a>`;
  }
},

      {
  data: 'lastReport',
  className: 'text-center',
  render: (data, type) => {
    const map = {
      PASS:['success-color-dark','PASS'],
      URGENT:['danger-color-dark','URGENT'],
      DEFECTS:['warning-color-dark','DEFECTS'],
      PNA:['stylish-color-dark','PNA'],
      DEFAULT:['secondary-color','N/A']
    };
    const k = String(data || '').trim().toUpperCase();
    const [cls, title] = map[k] || map.DEFAULT;

    if (type !== 'display') return data || '';

    const val = (k && map[k]) ? k : 'N/A';
    return `
      <a class="sFilter2" href="javascript:void(0)"
         onclick="inlineFilter(this.dataset.result)" data-result="${val}">
        <span class="badge ${cls} text-light">${title}</span>
      </a>
    `;
  }
},
      {
  data: 'duedate',
  render: function (data, type, row) {
    if (type !== 'display') return data || '';
    if (!data || !/^\d+$/.test(String(data))) return '';
    const d = new Date(Number(data) * 1000);
    const p = n => String(n).padStart(2, '0');
    const formatted = `${p(d.getDate())}-${p(d.getMonth() + 1)}-${d.getFullYear()}`;
    const val = formatted.replace(/"/g, '&quot;');
    return `<a class="sFilter2" href="javascript:void(0)" 
               onclick="inlineFilter(this.dataset.due)" data-due="${val}">${val}</a>`;
  }
},

      // 10) actions
      {
        data: null,
        className: 'text-end',
        orderable: false,
        searchable: false,
        render: (data, type, row) => {
          const c = row.clientnumber, i = row.itemnumber, ln = row.locnumber;
          const desc = String(row.description || '').replace(/"/g, '&quot;');
          const armode = '<?= ($filter === "archive") ? "activate" : "archive" ?>';
          const aricon = '<?= ($filter === "archive") ? "fad fa-upload" : "fad fa-archive" ?>';
          const artitle = '<?= ($filter === "archive") ? "Reinstate" : "Archive" ?>';

          const hasLocNotes  = !!String(row.locnotes || '').trim();
          const hasItemNotes = !!String(row.itemnotes || '').trim();

          let chainBtn = '';
          const linkedStr = String(row.linked || '');
          if (linkedStr) {
            const parts = linkedStr.split(':');
            const lcount = parseInt(parts[0], 10) || 0;
            const ldesc  = (parts[2] || '').replace(/"/g, '&quot;');
            if (lcount > 0) {
              chainBtn = `
                <a class="btn btn-secondary noprint me-3 me-xl-2 mb-2 d-inline-flex"
                   href="index.php?t=includes/master&p=linked.php&clientnumber=${c}&itemnumber=${i}"
                   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>`;
            }
          }

          const locNoteBtn = hasLocNotes ? `
            <a href="javascript:void(0)"
               class="btn btn-secondary noprint me-3 ms-3 mb-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=${ln}&tenant=${TENANT_URL}','locationBox','modal-xl',1060,'true','Location Notes','close')">
               <i class="fad fa-location-question"></i>
            </a>` : '';

          const itemNoteBtn = hasItemNotes ? `
            <a href="javascript:void(0)"
               class="btn unique-color-dark noprint ms-3 mb-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=${i}&tenant=${TENANT_URL}','ntoesBox','modal-xl',1060,'true','Item Notes','close')">
               <i class="fad fa-file-exclamation"></i>
            </a>` : '';

          return `
            <div style="white-space:nowrap;">
              ${locNoteBtn}
              ${chainBtn}

              <a href="javascript:void(0)" class="btn btn-secondary me-3 mb-2 formButton"
                 data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="top" title="New Report"
                 data-values="${c}|${ln}|${i}" data-href="${ROOT_URL}/includes/master/form.php">
                 <i class="fad fa-file-alt"></i> <span class="d-xl-none">New Report</span>
              </a>

              <a href="index.php?t=includes/master&p=items.php&data=${c}|${ln}|${i}&view=list"
                 class="btn btn-secondary me-3 mb-2"
                 data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="top" title="Complete Reports">
                 <i class="fad fa-copy"></i> <span class="d-xl-none">Complete Reports</span>
              </a>

              <a href="javascript:void(0)" class="btn btn-secondary me-3 mb-2 transferButton"
                 data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="top" title="Move"
                 data-values="${c}|${ln}|${i}|${desc}" data-href="${ROOT_URL}/includes/master/transfer.php">
                 <i class="fad fa-exchange-alt"></i> <span class="d-xl-none">Move</span>
              </a>

              <a href="javascript:void(0)" class="btn btn-secondary me-3 mb-2 archiveButton"
                 data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="top" title="${artitle}"
                 data-values="${c}|${ln}|${i}|${armode}" data-href="${ROOT_URL}/includes/master/archive.php">
                 <i class="${aricon}"></i> <span class="d-xl-none">archive</span>
              </a>

              <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=${c}|${ln}|${i}"
                 class="btn btn-secondary mb-2"
                 data-mdb-tooltip-init data-mdb-trigger="hover" data-mdb-placement="top" title="Edit">
                 <i class="fad fa-info-circle"></i> <span class="d-xl-none">Edit</span>
              </a>

              ${itemNoteBtn}
            </div>`;
        }
      }
    ],

    columnDefs: [
      { responsivePriority: 1, targets: 2 },      // description (control on mobile)
      { responsivePriority: 2, targets: 0 },      // colour strip
      { responsivePriority: 10000, targets: 10 }, // actions last
      { orderable: false, targets: [0,1,10] },
      { searchable: false, targets: [0,1,10] }
    ],

    initComplete: function () {
      $('#loadingOverlay').hide();
      $('#assetTableContainer').css('visibility', 'visible');
      toggleControlClass();
      // reselect persisted selections if returning
      table.rows().every(function () {
        if (selectedRowsIDs.includes(this.id())) this.select();
      });
      syncCheckboxes();
      updateToolbars();
    },

    drawCallback: function () {
      toggleControlClass();
      // keep selection across paging/filter
      table.rows({ page: 'current' }).every(function () {
        if (selectedRowsIDs.includes(this.id())) this.select(); else this.deselect();
      });
      syncCheckboxes();
      updateToolbars();
      if (window.mdb && typeof mdb.Tooltip !== 'undefined') {
        $(this.api().table().body()).find('[data-mdb-tooltip-init]').each(function () {
          if (!mdb.Tooltip.getInstance(this)) { new mdb.Tooltip(this); }
        });
      }
    }
  });

  // checkbox click -> select/deselect row
  $('#assetTable tbody').on('change', 'td.select-col input.row-select', function () {
    const tr = $(this).closest('tr');
    const row = table.row(tr);
    if (this.checked) row.select(); else row.deselect();
  });

  // keep checkboxes synced with selection state
  function syncCheckboxes() {
    table.rows({ page: 'current' }).every(function () {
      const isSelected = $(this.node()).hasClass('selected');
      $(this.node()).find('td.select-col input.row-select').prop('checked', isSelected);
      const id = this.id();
      if (isSelected) {
        if (!selectedRowsIDs.includes(id)) selectedRowsIDs.push(id);
      } else {
        const idx = selectedRowsIDs.indexOf(id);
        if (idx > -1) selectedRowsIDs.splice(idx, 1);
      }
    });
  }

  // viewport-controlled control class on DESCRIPTION column (now 3rd col)
  function toggleControlClass() {
    const isDesktop = window.matchMedia('(min-width: 992px)').matches;
    $('#assetTable tbody tr td:nth-child(3)').each(function () {
      if (isDesktop) $(this).removeClass('dtr-control'); else $(this).addClass('dtr-control');
    });
  }
  $(window).on('resize', toggleControlClass);

  // selection events
  table.on('select', function (e, dt, type, indexes) {
    const ids = dt.rows(indexes).ids().toArray();
    ids.forEach(id => { if (!selectedRowsIDs.includes(id)) selectedRowsIDs.push(id); });
    syncCheckboxes();
    updateToolbars();
  });

  table.on('deselect', function (e, dt, type, indexes) {
    const ids = dt.rows(indexes).ids().toArray();
    ids.forEach(id => {
      const idx = selectedRowsIDs.indexOf(id);
      if (idx > -1) selectedRowsIDs.splice(idx, 1);
    });
    syncCheckboxes();
    updateToolbars();
  });

  function updateToolbars() {
    $('#selectedItems').text(selectedRowsIDs.join(', '));
    const any = selectedRowsIDs.length > 0;
    if ($('#massToolbar').length && $('#mainToolbar').length) {
      if (any) {
        $('#mainToolbar').stop(true, true).fadeOut(200, () => $('#massToolbar').fadeIn(200));
      } else {
        $('#massToolbar').stop(true, true).fadeOut(200, () => $('#mainToolbar').fadeIn(200));
      }
    }
    if ($('#assignAsset').length) $('#assignAsset').css('display', any ? 'inline-block' : 'none');
  }

  // optional: clear selection helper
  window.clearTableSelection = function () {
    selectedRowsIDs.length = 0;
    table.rows().deselect();
    syncCheckboxes();
    updateToolbars();
  };
});



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('#transferBox .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, 'transferBox', 'modal-md', 1060, 'true', title);
        }
    });
});


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

$('#assetTable').on('draw.dt', function(){
  if (window.mdb) {
    document.querySelectorAll('[data-mdb-tooltip-init]').forEach(el => { if (!el._mdbTooltip) new mdb.Tooltip(el); });
    document.querySelectorAll('[data-mdb-popover-init]').forEach(el => { if (!el._mdbPopover) new mdb.Popover(el); });
  }
});

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));
                           
                           document.addEventListener('click', function (e) {
  const btn = e.target.closest('.filterButtons');
  if (!btn) return;
  document.querySelectorAll('[data-mdb-tooltip-init]').forEach(el => {
    const tt = mdb.Tooltip.getInstance(el) || new mdb.Tooltip(el);
    tt.hide();
  });
});
</script>
<?php }?>
