<style>
#new input[type="checkbox"]:checked+label:before {
    border-right: 2px solid #fff;
    border-bottom: 2px solid #fff;
}
</style>

<div id="loadingObject" style="position: fixed; top:50%; width:100%">
    <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 Data <br><small>Please
            wait</small>
    </h1>
</div>

<div id="data" style=" width: 100%">
    <?php

    require_once(ROOT_URL . '/includes/asset/asset_functions.php');

    function getSurveyorNameForm($esname)
    {
        $stmt = $GLOBALS['con']->prepare("SELECT `surname`,`forename` FROM `surveyor` WHERE `id`=?") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $esname);
        $stmt->execute();
        $rc = $stmt->get_result();
        $stmt->close();
        $cd = mysqli_fetch_array($rc);
        return $cd['forename'] . " " . $cd['surname'];
    }
    $_SESSION['returnLanding'] = 'index.php?t=includes/master&p=linked.php&clientnumber=' . $_REQUEST['clientnumber'] . '&itemnumber=' . $_REQUEST['itemnumber'];

    $stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc`,`linked` FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $_REQUEST['itemnumber']);
    $stmt->execute();
    $i = $stmt->get_result();
    $stmt->close();
    $id = mysqli_fetch_array($i);
    $set = explode(":", $id['linked']);
    $cur = array();

    $c = mysqli_query($GLOBALS['con'], "SELECT * FROM `rapid_history` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "' AND `chain`='" . $set[0] . "'") or die($e = "CHAECK FAILURE: " . mysqli_error($GLOBALS['con']));
    $n = mysqli_num_rows($c);
    if ($n == 0) {
    } else {
        $sd = mysqli_fetch_array($c);
        $storedItems = json_decode($sd['reps']);
        $storedCount = count($storedItems);
        $repRewind = '<a id="repidRewind" href="javascript:void(0)" onclick="repidRewind()" class="btn btn-info" data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover" title="there are ' . $storedCount . ' reports stored for recovery. Stored on ' . date('d-m-Y', $sd['date']) . '" ><i class="fad fa-history"></i> Report Rewind</a>';
    }

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



    $now = strtotime('now');
    $limiter = getCompanyDetails('rapid');
    $limiterDate = strtotime("+" . $limiter . " day");

    while ($itemData = mysqli_fetch_array($itemCall)) {

        $stmt2 = $GLOBALS['con']->prepare("SELECT `repnumber`,`reptype`,`insdate`,`adefect`,`bdefect`,`obs` FROM `reportitems` WHERE `itemnumber`='" . $itemData['itemnumber'] . "' ORDER BY abs(repitem) DESC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt2->execute();
        $idx = $stmt2->get_result();
        $stmt2->close();
        $idc = mysqli_num_rows($idx);
        $ids = mysqli_fetch_array($idx);
        if (is_numeric($itemData['duedate'])) {
            $dDate = date('d-m-Y', $itemData['duedate']);
        } else {
            $dDate = 'NDS';
        }
        if ($idc == 0) {
            $rMode = "initial";
        } else {
            $rMode = "reload";
        }

        if ($itemData['duedate'] < strtotime('now')) {
            $stat = "status_colour color danger-color-dark";
            $statTitle = "Overdue";
            $disabled = "0";
        }
        if ($itemData['duedate'] > strtotime('now') && $id['duedate'] < strtotime('now +1 month')) {
            $stat = "status_colour color warning-color-dark";
            $statTitle = "Pending";
            $disabled = "0";
        }
        if ($itemData['duedate'] > strtotime('now +1 month')) {
            $stat = "status_colour color success-color-dark";
            $statTitle = "Not_Due";
            $statFTitle = "Not Due";
            $disabled = "0";
        }
        if ($itemData['duedate'] < $limiterDate) {
            $disabled = "0";
        }
        
         if ($itemData['lastReport'] == "DEFECTS") {
                                $col = " warning-color-dark";
                                $tag = "DEFECTS";
                                $resultTitle = "DEFECTS";
                                $resultText = $id['bdefect'];
                            }
                            if ($itemData['lastReport'] == "URGENT") {
                                $col = " danger-color-dark";
                                $tag = "URGENT";
                                $resultTitle = "URGENT";
                                $resultText = $id['adefect'];
                            }
                            if ($itemData['lastReport'] == "PASS") {
                                $col = " success-color-dark";
                                $tag = "PASS";
                                $resultTitle = "PASS";
                                $resultText = "The item passed examination<br>";
                            }
                            if ($itemData['lastReport'] == "OBS") {
                                $col = " special-color";
                                $tag = "OBS";
                                $resultTitle = "OBS";
                                $resultText = $id['obs'];
                            }
                            if ($itemData['lastReport'] == "PNA") {
                                $col = " stylish-color-dark";
                                $tag = "PNA";
                                $resultTitle = "PNA";
                                $resultText = $id['pnareason'];
                            }
                            if ($itemData['lastReport'] == "") {
                                $col = " secondary-color";
                                $tag = "P2UD";
                                $resultTitle = "NULL";
                                $resultText = "No report or report is prior to update<br>";
                            }
                            
                            

        $table .= '
        <tr id="' . $itemData['itemnumber'] . '|' . $rMode . '|' . $ids['reptype'] . '">
        <td class="' . $stat . '" width="20px">
                        <div class="' . $stat . '" style="font-size:0px">' . $statTitle . '</div>
                    </td>
        <td width="20px"></td>
        <td>' . $itemData['itemnumber'] . '
        <div class="detail noExport" style=" height:140px; width:90%; display:none;background-color:#fff;">
        <div class="row" style="position:absolute; width:95%; height:140px; background-color:#fff; z-index:999">
        <div class="col-12 lead">' . $itemData['desc'] . ' | ' . $itemData['plantnumber'] . ' | ' . $itemData['serialnumber'] . '</div>
        <div class="col-4"><p class="border-bottom border-left border-right p-1 border border-danger"><b>A Defect</b></p><p class="border-bottom border-left border-right p-1">' . $ids['adefect'] . '</p></div>
        <div class="col-4"><p class="border-bottom border-left border-right p-1 border border-warning"><b>B Defect</b></p><p class="border-bottom border-left border-right p-1">' . $ids['bdefect'] . '</p></div>
        <div class="col-4"><p class="border-bottom border-left border-right bg-red p-1 border border-dark"><b>Observations</b></p><p class="border-bottom border-left border-right p-1">' . $ids['obs'] . '</p></div>
        </div>
        </div>
        </td>
           <td class="position-relative" data-mdb-popover-init data-mdb-trigger="hover" data-mdb-html="true" data-mdb-container="body"
                        data-mdb-placement="right" title="'.$itemData['desc']  .' Information"
                        data-mdb-content="<b>Model:</b> '.$itemData['model']  .'<br><b>Manufacturer:</b> '.$itemData['manf']  .'<br><b>Date of Manufacture:</b> '.$itemData['dateofmanf']  .'<br><b>SWL:</b> '.$itemData['swl'] .'">
                        <a class="sFilter2" href="javascript:void(0)"
                            onclick="inlineFilter(\''.$itemData['desc']  .'\')">'.$itemData['desc'] .'</a> <span
                            class=" d-sm-none position-absolute top-50 start-100 translate-middle no-print btn btn-floating btn-info noExport" data-mdb-tooltip-init
                            data-mdb-trigger="hover" data-mdb-placement="right"
                            title="Examination Frequency: '.$freq  .'Mths">'.$freq  .'</span>
                    </td>
        <td>' . $itemData['plantnumber'] . '</td>
        <td>' . $itemData['serialnumber'] . '</td>
        <td>' . $itemData['swl'] . '</td>
        <td>' . $itemData['locname'] . '</td>
        <td>' . $dDate . '</td>
        <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">

                            <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'].'|'.$itemData['locnumber'].'|'.$itemData['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'].'|'.$itemData['locnumber'].'|'.$itemData['itemnumber'].'&view=list"
                                class="btn btn-secondary noprint filesButton me-3 me-xl-2 mb-4 mb-xl-0"
                                data-values="'.$_REQUEST['clientnumber'].'|'.$itemData['locnumber'].'|'.$itemData['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'].'|'.$itemData['locnumber'].'|'.$itemData['itemnumber'].'|'.$itemData['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'].'|'.$itemData['locnumber'].'|'.$itemData['itemnumber'].'|'.$itemData['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>

                             <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'].'|'.$itemData['locnumber'].'|'.$itemData['itemnumber'].'|archive"
                                data-href="'.ROOT_URL.'/includes/master/archive.php" data-mdb-tooltip-init
                                data-mdb-trigger="hover" data-mdb-placement="top" title="Archive"><i
                                    class="fad fa-archive" aria-hidden="true"></i> <span
                                    class="d-xl-none">Archive</span></a>

                            <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data='.$_REQUEST['clientnumber'].'|'.$itemData['locnumber'].'|'.$itemData['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>';

                            $tag = "secondary";
        if ($ids['result'] == "") {
            $show = 'style="display:none"';
        }
        if ($ids['result'] == "URGENT") {
            $class = "litRed";
        }
        if ($ids['result'] == "DEFECTS") {
            $class = "litAmber";
        }
        if ($ids['result'] == "PASS") {
            $class = "litGreen";
        }
        if ($ids['result'] == "PNA" || $ids['result'] == "OBS") {
            $class = "litBlack";
        }

        $table .= '<a href="javascript:(0)" onclick="showNotes(\'' . $d['adefect'] . '|' . $d['bdefect'] . '|' . $d['obs'] . '|' . $d['repnumber'] . '|' . $d['desc'] . ' - ' . $d['plantnumber'] . ' / ' . $d['serialnumber'] . '\')" class="btn btn-secondar ' . $class . ' noprint" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Item Notes" ' . $show . '"><i class="fad fa-clipboard"></i></a>


                        </div>

       

       </td>
        </tr>';
        
      
    } ?>
    <style>
    #linkTable>tbody>tr>td,
    #linkTable>tbody>tr>th {
        vertical-align: middle
    }

    .filterButtons {
        display: none
    }

    .morpheus-den-gradient {
        background: linear-gradient(112deg, rgba(2, 0, 36, 1) 0%, rgba(0, 0, 0, 1) 51%, rgba(255, 0, 0, 1) 51%, rgba(135, 8, 8, 1) 100%, rgba(0, 212, 255, 1) 100%);
    }
    </style>
    <div id="exportTitle" style="display:none">
        <p style="font-size:14px; font-weight:bold">EnRep Reporting System</p>
        <p style="font-size:12px"><?= getClientName($_REQUEST['clientnumber']) ?> : Schedule : Linked Items</p>
    </div>

    <div class="row">
        <div class="col-12 col-md-6 mb-3 text-center text-md-start">
            <h3 class="lead"><a href="javascript:void(0)"><i class="fad fa-link"></i> C<?= $set[0] ?>: <?= $set[2] ?> -
                </a> Viewing <?= $id['desc'] ?> and its linkages</h3>
        </div>
        <div class="col-12 col-md-6  text-center text-md-end">
            <a id="detailButton" href="javascript:void(0)" onclick="" class="btn btn-secondary" data-mdb-tooltip-init
                data-mdb-placement="bottom" data-mdb-trigger="hover" title="Show Item results"><i id="detailIcon"
                    class="fad fa-bars me-2"></i> View
                Details</a>

            <?= $repRewind ?>

            <a id="massReport" style="display: none" href="javascript:void(0)" onclick="" class="btn btn-secondary"
                data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
                title="Rapid Report Selected Items"><i class="fad fa-copy"></i>
                Rapid Report</a>

            <a id="massUnlink" style="display: none" href="javascript:void(0)" onclick="" class="btn btn-secondary"
                data-mdb-tooltip-init data-mdb-placement="bottom" data-mdb-trigger="hover"
                title="Mass Unlink Selected Items"><i class="fad fa-unlink "></i> Mass Unlink</a>


        </div>
        <div class="col-12 col-md-6 mb-3">
            <p class="blockquote"><small>Items listed here can untilise the <span class="indigo-text">RapidRep</span>
                    feature only when their <i>due date</i> is less than <?= $limiter ?> days from today.</small></p>

        </div>
    </div>

    <div class="row mt-4">
    <div class="col-12">
        <table id="linkTable" class="dt-print-table table table-striped table-bordered table-hover responsive table-sm"
            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>Item ID</th>
                        <th>Description</th>
                        <th>Plant Number</th>
                        <th>Serial Number</th>
                        <th>Safe working load</th>
                        <th>Location</th>
                         <th class="date-uk">Due Date</th>
                         <th>Result</th>
                         <th class="no-sort noExport"></th>
                    </tr>
                </thead>
                <tbody>
                    <?= $table ?>
                </tbody>
            </table>
            <?php
            $table = "linkTable";
            $dateTarget = "8";
            $length = "25";
            $sortTarget = "1";
            $sortCell = "nth-child(2)";
            $logo = "yes";
            $scroller = "";
            require(ROOT_URL . "/includes/tables/linked_table.php");
            ?>
        </div>
    </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','linkTable')">&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','linkTable')">&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','linkTable')">&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('linkTable')">&nbsp;<i class="fad fa-refresh" aria-hidden="true"></i>
            Reset Filters&nbsp;</button>

    </div>
</div>

    <div class="row">
        <div id="selectedItems" style="display:none"></div>
    </div>

</div>

<script>
// Function to handle setting alternating background colors for visible table rows
function setRowColors() {
    const rows = document.querySelectorAll('#linkTable tbody tr');
    rows.forEach((row, index) => {
        if (row.style.display !== 'none') {
            if (index % 2 === 0) {
                row.style.backgroundColor = 'rgba(255,255,255,.05)'; // Even rows
            } else {
                row.style.backgroundColor = 'rgba(0,0,0,.05)'; // Odd rows
            }
        }
    });
}


document.getElementById('detailButton').addEventListener('click', function() {
    const details = document.querySelectorAll('.detail');
    const detailIcon = document.getElementById('detailIcon');

    // Toggle display of all elements with the class 'detail'
    details.forEach(detail => {
        detail.style.display = (detail.style.display === 'none' || !detail.style.display) ?
            'table-row' : 'none';
    });

    // Check if any of the details are visible
    const anyVisible = Array.from(details).some(detail => detail.style.display === 'table-row');

    // Rotate the icon if details are visible
    if (anyVisible) {
        detailIcon.classList.add('fa-rotate-90');
    } else {
        detailIcon.classList.remove('fa-rotate-90');
    }

    // Reset row background colors after toggling
    setRowColors();
});

// Initial call to set the row colors
setRowColors();

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"><?= getClientName($_REQUEST['clientnumber']) ?><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=asset">Schedule</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item active"><?= $id['desc'] ?>: Linked Items</li>'







var initialAr = ''
var reloadAr = ''
var Ar500 = ''
var ArN500 = ''
var icount = 0
var rcount = 0
var count500 = 0
var countN500 = 0

function massReport(i) {
    initialAr = [];
    reloadAr = [];
    Ar500 = [];
    ArN500 = [];
    icount = 0;
    rcount = 0;
    count500 = 0;
    countN500 = 0;
    let process = 0;
    let header = '';
    let content = '';
    let footer = '';

    if (i.length === 0) {
        header += '<a href="javascript:void(0)" class="sa">RapidRep</a>';
        content +=
            '<div class="col-12 alert alert-warning text-center p-0" style="font-size:18px"><p class="pt-2 pb-2 m-0">There are no items selected</p></div>';
    } else {
        let items = i.length === 1 ? i : i.split(',');

        items.forEach(item => {
            let ite = item.split('|');
            if (ite[1] === 'initial') {
                initialAr.push(ite[0]);
            } else {
                if (["500", "502", "503", "504", "506", "900", "511", "512", "513", "514", "515", "516", "517",
                        "518"
                    ].includes(ite[2])) {
                    reloadAr.push(ite[0]);
                } else {
                    ArN500.push(ite[0]);
                }
            }
        });

        icount = initialAr.length;
        rcount = reloadAr.length;
        count500 = reloadAr.length;
        countN500 = ArN500.length;

        if (countN500 > 0) {
            header = `
            <div id="mHeader" class="col-12 alert alert-danger alert-sm text-center p-0 mb-1">
                <p class="pt-2 pb-2 m-0" style="font-size: 14px;">There are <b>${countN500}</b> items selected that cannot be processed</p>
            </div>`;
        }

        content = `
    <div id="start">
        ${icount > 0 ? `
            <div id="new" class="bg-info text-light p-2">
                <div class="col-12 alert alert-warning alert-sm text-center p-0 mb-1">
                    <p class="pt-2 pb-2 m-0" style="font-size: 14px;">You are confirming that <b class="text-dark">${icount}</b> items have been examined for the <b class="text-dark">FIRST TIME</b>. All reports will have the same data as entered in the fields below.</p>
                </div>
                <div class="row mb-2 p-2">
                    <div class="col-9 mb-2">
                        <textarea class="md-textarea form-control" name="cdefectAdd" id="cdefectAdd" rows="3">None</textarea>
                        <label id="cdefectAddLabel" for="cdefectAdd" class="form-label">Observations</label>
                    </div>
                    <div class="col-3 mb-2">
                        <div class="form-check align-bottom">
                            <input type="checkbox" class="form-check-input" id="cDefectNewObs" value="true">
                            <label class="form-check-label" for="cDefectNewObs">Add Observations</label>
                        </div>
                        <div class="mt-4">
                            <select id="initialReptype" class="form-select" onchange="changeLabel()">
                                <option value="">SELECT FORMTYPE</option>
                                <option value="500">LOLER Report</option>
                                <option value="502">Partial Report</option>
                                <option value="503">Plant Not Available</option>
                                <option value="504">None Stat</option>
                                <option value="506">PUWER Report</option>
                                <option value="900">PAT Report</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>` : ''}
        ${count500 > 0 ? `
            <div id="renew" class="border p-2">
                <div class="col-12 alert alert-warning alert-sm text-center p-0 mb-1">
                    <p class="pt-2 pb-2 m-0" style="font-size: 14px;"><b>Warning:</b> You are confirming that <b class="text-dark">${count500}</b> items have been examined and <b class="text-dark">NO CHANGES</b> to previous reports have been recorded.</p>
                </div>
                <div class="row mb-2 p-2">
                    <div class="col-9 mb-2">
                        <textarea class="md-textarea form-control" name="cDefectReload" id="cDefectReload" rows="3">None</textarea>
                        <label id="cdefectLabel" for="cDefectReload" class="form-label">Observations</label>
                    </div>
                    <div class="col-3 mb-2">
                        <div class="form-check align-bottom">
                            <input type="checkbox" class="form-check-input" id="cDefectReloadObs">
                            <label class="form-check-label" for="cDefectReloadObs">Add Observations</label>
                        </div>
                        <!--<div class="form-check align-bottom">
                            <input type="checkbox" class="form-check-input" id="nirReload" onclick="changeLabelReload()">
                            <label class="form-check-label" for="nirReload">Set PNA</label>-->
                        </div>
                    </div>
                </div>
            </div>` : ''}
        <div class=" p-2">
            <div class="row mb-3 p-2">
                
                <div class="col-md-3 datepicker" data-mdb-input-init data-mdb-toggle-button="false">
                 <label class="form-label" for="date">Date of examination</label>
                    <input id="date" class="form-control" data-mdb-toggle="datepicker">
                </div>
                
                <?php if ($_SESSION['usertype'] == "surveyor") { ?>
                     <div class="col-md-3"><label class="form-label" for="surveyor">Surveyor</label><br>
                <input type="hidden" class="form-control" name="surveyor" id="surveyor" value="<?= $_SESSION['userid'] ?>" readonly>
                <span class="text-dark"><?= getSurveyorNameForm($_SESSION['userid']) ?></span>
                  </div>
                <?php } else { ?>

                <div class="col-md-3" data-mdb-select-init>
                <label class="form-label" for="surveyor">Surveyor</label>
                    <?= listSurveyor($cd['surveyor'], 'surveyor', 'select') ?>
                   
                </div>
                <?php } ?>
            </div>
        </div>
    </div>
    <div id="process" style="display: none;">
        <div class="col-12 text-center">
            <h1>
                <i class="fad fa-spinner fa-spin fa-3x" style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i>
                <br>Registering Inspections                
            </h1>
           <p>Please wait, this can take up to 60 seconds depending on number of reports to register<br><br><br></p>
        </div>
    </div>
    <div id="mFooter" class="col-12 text-center">
        <div id="confirmBox" class="form-check form-check-inline">
            <input type="checkbox" class="form-check-input" id="confirmCheck" onchange="check()">
            <label class="form-check-label" for="confirmCheck">I confirm all items have been inspected to statutory requirements</label>
        </div>
        <a id="confirmButton" class="btn btn-success" style="display:none;" onclick="massRep('${initialAr}', '${reloadAr}')">Proceed</a>
    </div>`;

        loadModalContent(header + content, 'rapidBox', 'modal-xl', 1060, 'true', 'Rapid Reporting');

        setTimeout(() => {
            const modalContent = document.getElementById('rapidBox');
            initializeDatepickers(modalContent);
            <?php if ($_SESSION['usertype'] == "surveyor") {
                } else { ?>
            initialiseSelects();
            <?php } ?>
        }, 800);
    }
}

function initialiseSelects() {
    var mySelect = new mdb.Select(document.getElementById('surveyor'), {
        filter: true,
        container: "#rapidBox"
    });
}

function changeLabel() {
    var select = document.getElementById('initialReptype').value;
    var cdefectAddLabel = document.getElementById('cdefectAddLabel');

    if (select === "503") {
        cdefectAddLabel.innerHTML = 'Reason for None Inspection';
    } else {
        cdefectAddLabel.innerHTML = 'Observations';
    }
}

function changeLabelReload() {
    var nirReloadChecked = document.getElementById('nirReload').checked;
    var cdefectLabel = document.getElementById('cdefectLabel');
    var cDefectReload = document.getElementById('cDefectReload');
    var cdefectTitle = document.getElementById('cdefectTitle');

    if (nirReloadChecked) {
        cdefectLabel.textContent = 'Reason for None Inspection';
        cDefectReload.textContent = 'Item not presented for examination.';
        cdefectTitle.innerHTML = 'and will be recorded as <b class="text-dark">PLANT NOT AVAILABLE</b>';
    } else {
        cdefectLabel.textContent = 'Observations';
        cdefectTitle.innerHTML = 'and <b class="text-dark">NO CHANGES</b> to previous reports have been recorded.';
    }
}



function massRep(i, reloadAr) {

    // Check if surveyor and date fields exist, otherwise set them to default values
    var s = document.getElementById('surveyor') ? document.getElementById('surveyor').value : '';
    var d = document.getElementById('date') ? document.getElementById('date').value : '';
    var nd = document.getElementById('dateNext') ? document.getElementById('dateNext').value : '';
    var et = document.getElementById('initialReptype') ? document.getElementById('initialReptype').value : '';

    // Safely check if cDefectNewObs exists and is checked
    var newObs = document.getElementById('cDefectNewObs') && document.getElementById('cDefectNewObs').checked ?
        document.getElementById('cdefectAdd').value :
        'None';

    // Safely check if cDefectNewObs exists and is checked
    var reloadObs = document.getElementById('cDefectReloadObs') && document.getElementById('cDefectReloadObs').checked ?
        document.getElementById('cDefectReload').value :
        'None';

    // Safely check if nirReload exists and is checked
    var nirReload = document.getElementById('nirReload') && document.getElementById('nirReload').checked ?
        'yes' :
        '';
    console.log("New Obs:", newObs);;
    console.log("NIR Reload:", nirReload);
    if (s === 'NULL' || d === '') {
        showResponse('warning', 'You must set a <b>DATE</b> and <b>SURVEYOR</b> before proceeding');
        if (s === 'NULL') {
            document.getElementById('surveyor').classList.add('border', 'border-danger');
            document.getElementById('surveyor').focus();
        }
        if (d === '') {
            document.getElementById('date').classList.add('border', 'border-danger');
            document.getElementById('date').focus();
        }



    } else {

        document.getElementById('start').style.display = 'none';
        document.getElementById('mFooter').style.display = 'none';
        document.getElementById('process').style.display = 'block';

        if (icount === 0 && count500 > 0) {

            fetch(ROOT_URL + '/functions/rapidrep.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        itemset: reloadAr,
                        surveyor: s,
                        date: d,
                        nextDate: nd,
                        obs: reloadObs,
                        nir: nirReload,
                        clientnumber: '<?= $_REQUEST['clientnumber'] ?>',
                        tenant: TENANT_URL
                    })
                })
                .then(response => response.text())
                .then(ret => {

                    //debug(ret)
                    window.location.href =
                        "index.php?t=includes/master&p=linked.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&itemnumber=<?= $_REQUEST['itemnumber'] ?>";
                });
        }

        if (icount > 0 && count500 === 0) {
            //alert('2')
            if (et === "") {
                showResponse('warning', 'You must set a <b>FORMTYPE</b> before proceeding');
                document.getElementById('start').style.display = 'block';
                document.getElementById('mFooter').style.display = 'block';
                document.getElementById('process').style.display = 'none';
                document.getElementById('initialReptype').classList.add('border', 'border-danger');
                document.getElementById('initialReptype').focus();
            } else {
                //alert('newmode:' + newObs)
                fetch(ROOT_URL + '/functions/rapidrepNew.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: new URLSearchParams({
                            itemset: initialAr,
                            surveyor: s,
                            date: d,
                            nextDate: nd,
                            examType: et,
                            obs: newObs,
                            clientnumber: '<?= $_REQUEST['clientnumber'] ?>',
                            tenant: TENANT_URL
                        })
                    })
                    .then(response => response.text())
                    .then(ret => {
                        //debug(ret)
                        window.location.href =
                            "index.php?t=includes/master&p=linked.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&itemnumber=<?= $_REQUEST['itemnumber'] ?>";
                    });
            }
        }

        if (icount > 0 && count500 > 0) {
            //alert('3')
            if (et === "") {
                showResponse('warning', 'You must set a <b>FORMTYPE</b> before proceeding');
                document.getElementById('start').style.display = 'block';
                document.getElementById('mFooter').style.display = 'block';
                document.getElementById('process').style.display = 'none';
                document.getElementById('initialReptype').classList.add('border', 'border-danger');
                document.getElementById('initialReptype').focus();
            } else {

                fetch(ROOT_URL + '/functions/rapidrepNew.php', {

                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: new URLSearchParams({
                            itemset: initialAr,
                            surveyor: s,
                            date: d,
                            nextDate: nd,
                            examType: et,
                            obs: newObs,
                            clientnumber: '<?= $_REQUEST['clientnumber'] ?>',
                            tenant: TENANT_URL
                        })
                    })
                    .then(response => response.text())
                    .then(() => {
                        fetch(ROOT_URL + '/functions/rapidrep.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                },
                                body: new URLSearchParams({
                                    itemset: reloadAr,
                                    surveyor: s,
                                    date: d,
                                    nextDate: nd,
                                    obs: newObs,
                                    nir: nirReload,
                                    clientnumber: '<?= $_REQUEST['clientnumber'] ?>',
                                    tenant: TENANT_URL
                                })
                            })
                            .then(response => response.text())
                            .then(ret => {
                                //debug(ret)
                                window.location.href =
                                    "index.php?t=includes/master&p=linked.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&itemnumber=<?= $_REQUEST['itemnumber'] ?>";
                            });
                    });
            }
        }
    }
}



// Helper function to send POST requests
function sendPostRequest(url, data, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    var params = new URLSearchParams();
    for (var key in data) {
        if (data.hasOwnProperty(key)) {
            params.append(key, data[key]);
        }
    }

    xhr.onload = function() {
        if (xhr.status === 200 && callback) {
            callback(xhr.responseText);
        }
    };
    xhr.send(params.toString());
}


function check() {
    var confirmCheck = document.getElementById('confirmCheck');
    var confirmBox = document.getElementById('confirmBox');
    var confirmButton = document.getElementById('confirmButton');

    if (confirmCheck.checked) {
        confirmBox.style.display = 'none';
        confirmButton.style.display = 'block';
    }
}

function showNotes(i) {
    var data = i.split('|');
    var content = '';

    content += '<div class="row mb-3">';
    content += '<div class="col-12 alert alert-info">' + data[4] + '</div>';
    content += '</div>';
    content += '<div class="row mb-3">';
    content += '<div class="col-3 lead">A defect</div><div class="col-6">' + data[0] + '</div>';
    content += '</div>';
    content += '<div class="row mb-3">';
    content += '<div class="col-3 lead">B defect</div><div class="col-6">' + data[1] + '</div>';
    content += '</div>';
    content += '<div class="row mb-3">';
    content += '<div class="col-3 lead">Observations</div><div class="col-6">' + data[2] + '</div>';
    content += '</div>';

    loadModalContent(content, "popupBox", "modal-xl", 1060, "true");
}

document.addEventListener('DOMContentLoaded', function() {
    var linkTable = document.getElementById('linkTable');

    linkTable.querySelector('tbody').addEventListener('click', function(event) {
        var target = event.target.closest('.formButton, .transferButton, .archiveButton');

        if (target) {
            var href = target.getAttribute('data-href');
            var values = target.getAttribute('data-values');
            var title = target.getAttribute('data-mdb-original-title');
            var dest = encodeURI(href + "?data=" + values + "&tenant=<?= $systemUser ?>");
            loadModalContent(dest, "popupBox", "modal-xxl", 1060, "true", title, "close");
        }
    });

    document.getElementById('loadingObject').style.display = 'none';
    document.getElementById('data').style.display = 'block';
});

function repidRewind() {
    var content = '';
    content += '<div class="row mb-3">';
    content +=
        '<div class="col-12 lead text-center">Are you sure you wish to restore the <?= $storedCount ?> files reported on <?= date('d-m-Y', $sd['date']) ?>?</div>';
    content += '<div class="col-12 text-center">This cannot be undone</div>';
    content += '</div>';

    loadModalContent(content, "popupBox", "modal-xxl", 1060, "true", "Rapid Rewind", "cancelConfirm", rewind);
}

function rewind() {
    showLoadingIndicator('Rewinding Reports...', 'fa-clock-rotate-left');
    killModal('popupBox')

    var items = '<?= $sd['reps'] ?>';
    var xhr = new XMLHttpRequest();
    xhr.open('POST', `${ROOT_URL}/functions/rapidRewind.php`, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    xhr.onload = function() {
        if (xhr.status === 200) {
            // Log the response to the console for debugging
            console.log(xhr.responseText);

            if (xhr.responseText.trim() === 'done') {
                window.location.href =
                    "index.php?t=includes/master&p=linked.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&itemnumber=<?= $_REQUEST['itemnumber'] ?>";
            } else {
                // Log any PHP errors or unexpected output
                //debug(xhr.responseText);
            }
        } else {
            // Log non-200 status codes as errors
            console.error(`Error: ${xhr.status}`);
        }
    };

    xhr.onerror = function() {
        // Log any network errors
        console.error('Network error occurred while making the request.');
    };

    xhr.send('items=' + encodeURIComponent(items) +
        '&clientnumber=<?= $_REQUEST['clientnumber'] ?>&entry=<?= $sd['id'] ?>&tenant=' + encodeURIComponent(
            TENANT_URL));
}


document.addEventListener('DOMContentLoaded', function() {
    var linkTable = document.getElementById('linkTable');
    var rows = linkTable.querySelectorAll("tbody tr:not([hidden])");

    rows.forEach(function(row, index) {
        if (index % 2 === 0) {
            row.style.backgroundColor = 'rgba(255,255,255,.05)'; // Even rows
        } else {
            row.style.backgroundColor = 'rgba(0,0,0,.05)'; // Odd rows
        }
    });
});

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>