<div id="exportTitle" style="display:none">
    <p style="font-size:14px; font-weight:bold">EnRep Reporting System</p>
    <p style="font-size:12px"><a href="">Surveyor</a> : <a href=""><?= getSurveyorName2($_REQUEST['surveyor']) ?></a> :
        <a href="">Asset List</a></p>
</div>
<div class="row mt-4">
    <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',0)">&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',0)">&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',0)">&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 class="col-12 col-md-6 text-end mb-3">
    <a id="massMigrate" style="display: none" href="javascript:void(0)" onclick="" class="btn btn-secondary"
        data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover"
        title="Mass Item move"><i class="fab fa-buromobelexperte"></i> Mass
        Item move</a>

    <a id="massArchive" style="display: none" href="javascript:void(0)" onclick="" class="btn btn-secondary"
        data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" totitle="hover"
        title="Mass Item archive"><i class="fab fa-buromobelexperte"></i>
        Mass Item Archive</a>
</div>


<div id="loadingObject">
    <h1 class="text-center"><i class="fad fa-file-archive fa-spin fa-3x fa-fw"
            style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Loading
        <?= getSurveyorName2($_REQUEST['id']) ?>'s assigned Assets <br><small>Please
            wait</small></h1>
</div>

<p class="noprint">Surveyor <?= getSurveyorName2($_REQUEST['surveyor']) ?> : Asset List</p>

<table id="assetTable" class="table table-striped table-sm table-bordered table-hover responsive" width="100%"
    style="display: none">
    <thead>
        <tr>
            <th class="no-sort"></th>
            <th class="no-sort"></th>
            <th>Client</th>
            <th>Description</th>
            <th>Plant Number</th>
            <th>Serial Number</th>
            <th>Location</th>
            <th>Due Date</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <?php
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `surveyor_assignments` WHERE `surveyor`=? AND `client_id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('ii', $_REQUEST['surveyor'], $_REQUEST['client_id']);
        $stmt->execute();
        $ic = $stmt->get_result();
        $stmt->close();
        $count = mysqli_num_rows($ic);
        if ($count == 1) {
            $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`itemnumber`,`desc`,`locnumber`,`plantnumber`,`serialnumber`,`duedate` FROM `itemdetails` WHERE `clientnumber`=? AND `statuslive`='1'") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $_REQUEST['client_id']);
            $stmt->execute();
            $ic = $stmt->get_result();
            $stmt->close();
        }



        while ($id = mysqli_fetch_array($ic)) {

            if ($id['duedate'] < strtotime('now')) {
                $stat = "status_colour color danger-color-dark";
                $statTitle = "Overdue";
            }
            if ($id['duedate'] > strtotime('now') && $id['duedate'] < strtotime('now +1 month')) {
                $stat = "status_colour color warning-color-dark";
                $statTitle = "Pending";
            }
            if ($id['duedate'] > strtotime('now +1 month')) {
                $stat = "status_colour color success-color-dark";
                $statTitle = "Not_Due";
                $statFTitle = "Not Due";
            }
        ?>
        <tr>
            <td class="status_colour <?= $stat ?>">
                <div class="<?= $stat ?>" style="font-size:0px"><?= $statTitle ?></div>
            </td>
            <td id="C<?= $id['itemnumber'] ?>" data-value="C<?= $id['itemnumber'] ?>"></td>
            <td><?= getClientName($id['clientnumber'], 'name') ?></td>
            <td><?= $id['desc'] ?></td>
            <td><?= $id['plantnumber'] ?></td>
            <td><?= $id['serialnumber'] ?></td>
            <td><?= getItemLocation($id['itemnumber'], 'name') ?></td>
            <td class="prod_color"><?php if (empty($id['duedate'])) {
                                            echo "No date stored";
                                        } else { ?>
                <span class="hidden"><?= date('Y-m-d', $id['duedate']); ?></span><?= date('d-m-Y', $id['duedate']);
                                                                                    } ?>
            </td>
            <td>
                <div class="btn-group" role="group" style="float:right">

                    <?= $locNoteAlert ?>

                    <?php if ($isLink == "yes") { ?>
                    <a class="btn btn-secondary noprint me-2 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 ?></a>
                    <?php } ?>

                    <a href="javascript:void(0)" class="btn btn-secondary noprint formButton  me-2 "
                        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></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-2"
                        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></a>

                    <a href="javascript:void(0)" class="btn btn-secondary noprint transferButton  me-2"
                        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></a>

                    <a href="javascript:void(0)" class="btn btn-secondary noprint formButton  me-2"
                        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></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="<?= $_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></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-2" 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></a>

                    <?= $itemNoteAlert ?>

                </div>
            </td>
        </tr>

        <?php } ?>
    </tbody>
</table>

<?php

if (!empty($_REQUEST['filter'])) { ?>
<script>
$(document).ready(function() {
    addSearch('<?= $_REQUEST['filter'] ?>', 0);
})
</script>
<?php }
$table = "assetTable";
$dateTarget = "7";
$sortTarget = "1";
$length = "25";
$sortCell = "nth-child(2)";
$logo = "yes";
$scroller = "";
require(ROOT_URL . "/includes/tables/asset_table.php");
?>
<div class="row mt-4">
    <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',0)">&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',0)">&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',0)">&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>

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

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, 'close');
        }
    });
});


setTimeout(function() {
    $('td :checkbox').change(function() {
        var v = new Array()
        $('td :checkbox').each(function() {
            if ($(this).is(":checked")) {
                v.push($(this).val());
            }

        })
        console.log(v)
        if (v.length === 0) {
            //$('#massMigrate').css('display','none');
            //$('#massMigrate').attr('onclick','');
            $('#massArchive').css('display', 'none');
            $('#massArchive').attr('onclick', '');
        }
        if (v.length > 1) {
            //$('#massMigrate').css('display','inline-block')
            //$('#massMigrate').attr("onclick","massMigrate('"+v+"')")
            $('#massArchive').css('display', 'block')
            $('#massArchive').attr("onclick", "massArchive('" + v + "')")
        }
    })
}, 2000);



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


document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=surveyor.php&view=list">Surveyor</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item active"><?= getSurveyorName2($_REQUEST['surveyor']) ?>: Assigned Assets</li>';
</script>