<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

function getReportDesc($repnumber, $type)
{
    // Prepare the first query to fetch from dd_formtypes
    $stmt1 = $GLOBALS['master']->prepare("SELECT * FROM " . $GLOBALS['path'] . ".dd_formtypes WHERE `formnumber` = ?");
    $stmt1->bind_param("i", $repnumber);
    $stmt1->execute();
    $rx1 = $stmt1->get_result();
    $stmt1->close();

    // Check if a result was found in dd_formtypes
    if ($rx1->num_rows > 0) {
        $cx = mysqli_fetch_array($rx1);
    } else {
        // If no result, try the second query to fetch from dd_groupFormtypes
        $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM dd_groupFormtypes WHERE `formnumber` = ?");
        $stmt2->bind_param("i", $repnumber);
        $stmt2->execute();
        $rx2 = $stmt2->get_result();
        $stmt2->close();

        // Check if a result was found in dd_groupFormtypes
        if ($rx2->num_rows > 0) {
            $cx = mysqli_fetch_array($rx2);
        } else {
            return null;
        }
    }

    if ($type == "formtype") {
        return $cx['formtype'];
    }
    if ($type == "regs") {
        return $cx['regs'];
    }

    return null;
}

if ($_REQUEST['site'] != "") {
    $location = "AND `locnumber`='" . $_REQUEST['site'] . "' ";
} else {
    $location = "";
}

$items = array();
$linked = array();
$filter = array();
$li = array();

if (empty($_REQUEST['items'])) {
    if (!empty($_REQUEST['site'])) {
        $sFilter = "AND b.locnumber='" . $_REQUEST['site'] . "'";
    }
    $stmt = $GLOBALS['con']->prepare("
SELECT 
a.clientnumber, a.repitem, a.itemnumber, a.reptype, a.insdate, b.itemnumber, b.linked, b.locnumber, b.statuslive
FROM reportitems a INNER JOIN itemdetails b 
ON b.itemnumber = a.itemnumber 
WHERE a.clientnumber = '" . $_REQUEST['clientnumber'] . "' AND a.insdate >= '" . strtotime($_REQUEST['start']) . "' AND a.insdate <=  '" . strtotime($_REQUEST['end']) . "' $sFilter AND b.statuslive='1' 
ORDER BY abs(a.repitem) DESC 
") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $ic = $stmt->get_result();
    $stmt->close();
    while ($id = mysqli_fetch_array($ic)) {
        if ($id['repitem'] == "") {
        } else {
            if (in_array($id['itemnumber'], $filter)) {
            } else {
                if ($id['linked'] != "" && $id['linked'] != "[]") {
                    $linked[] = $id['repitem'];
                }
                $items[] = $id['repitem'];
                $filter[] = $id['itemnumber'];
            }
        }
    }
} else {
    $items = $_SESSION['items'];
}

function getWSData($itemnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `id`,`wsnumber` FROM `wsitems` WHERE `itemnumber`=?") or die($error = mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $c = mysqli_num_rows($res);
    $d = mysqli_fetch_array($res);
    if ($c > 0) {
        $stmt = $GLOBALS['con']->prepare("SELECT `description`,`no` FROM `writtenscheme` WHERE `id`=?") or die($error = mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $d['wsnumber']);
        $stmt->execute();
        $res2 = $stmt->get_result();
        $stmt->close();
        $e = mysqli_fetch_array($res2);
        return $e['no'];
    } else {
        return 'None found';
    }
}

function getDeliveryPref($clientnumber)
{
    $stmt = $GLOBALS['con']->prepare("SELECT `delivery_type` FROM `clientdetails` WHERE `clientnumber`=?") or die($error = mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $_REQUEST['clientnumber']);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $d = mysqli_fetch_array($res);
    return $d['delivery_type'];
}
if (empty($items)) { ?>

<div class="container">
    <div class="col-12 text-center mb-5"><i class="fad fa-file-slash fa-10x"></i></div>
    <div class="card" style="height: 120px;">
        <div class="card-body h-100">
            <div class="row h-100 gx-0">
                <div class="col-12 col-md-6 d-flex align-items-center justify-content-center">
                    <div
                        class="alert warning-color-dark text-light text-center m-0 w-100 h-100 d-flex align-items-center justify-content-center shadow-2-strong">
                        No Reports Found In The Date Range <b><?= $_REQUEST['start'] ?> > <?= $_REQUEST['end'] ?></b>
                    </div>
                </div>
                <div class="col-12 col-md-6 d-flex align-items-center justify-content-center">
                    <a class="d-flex align-items-center justify-content-center h-100 w-100 btn btn-secondary btn-lg text-center"
                        href="index.php?t=includes/master&p=delivery.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>">
                        <i class="fad fa-backward"></i> Start Again
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<?php } else { ?>
<style>
.holder {
    position: relative;
    opacity: 0.6;
    filter: grayscale(100%);
}

.itemToggle {
    position: absolute;
    bottom: 35px;
    left: 10px;
}

#linkedSelect {
    display: flex;
    flex-wrap: wrap;
    /* Ensure the items wrap if there isn't enough space */
    gap: 10px;
    /* Optional: add some spacing between the switches */
    justify-content: flex-start;
    /* Align the switches horizontally */
}
</style>
<div class="alert alert-info text-light shadow-4 mt-2 p-0">
    <div class="row align-items-center m-2">
        <div class="col-6 col-lg-3 text-md-start text-center">SELECT REPORTS</div>

        <div class="col-6 col-lg-3 mb-3 mt-3 form-check form-switch">
            <input id="checkAll" class="form-check-input" type="checkbox">
            <label class="form-check-label" for="checkAll">SELECT ALL</label>
        </div>

        <div class="col-6 col-lg-3 form-check form-switch">
            <input id="deCheckAll" class="form-check-input" type="checkbox">
            <label class="form-check-label" for="deCheckAll">DESELECT ALL</label>
        </div>

        <div class="col-6 col-lg-3 form-check form-switch">
            <input id="deCheckDelivered" class="form-check-input" type="checkbox">
            <label class="form-check-label" for="deCheckDelivered">DESELECT DELIVERED</label>
        </div>
    </div>

    <div id="linkedSelect" class="row d-flex justify-content-start ms-4"></div>

    <?php if (!empty($linked)) { ?>
    <div class="text-center position-absolute w-100" style="bottom: -36px; z-index:999">
        <a id="toggleBtn" href="javascript:void(0)" class="btn btn-secondary" onclick="showlink()">
            <i id="btnToggle" class="fad fafa-sort-down"
                style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i> Chained Items
        </a>
    </div>
    <?php } ?>
</div>

<div class="row">
    <div class="col-12 col-md-8 col-lg-10">
        <div class="row">
            <?php
                $repCount = 0;
                foreach ($items as $item) {
                    $stmt = $GLOBALS['con']->prepare("SELECT 
                a.repitem,
                a.repnumber,
                a.reptype,
                a.itemnumber,
                a.insdate,
                a.adefect,
                a.bdefect,
                a.obs,
                a.result,
                a.delivery,
                a.esname,
                b.itemnumber,
                b.plantnumber,
                b.serialnumber,
                b.linked,
                b.desc
                FROM reportitems a JOIN itemdetails b ON a.itemnumber=b.itemnumber 
                WHERE `repitem`=?") or die(mysqli_error($GLOBALS['con']));
                    $stmt->bind_param('i', $item);
                    $stmt->execute();
                    $r = $stmt->get_result();
                    $stmt->close();
                    $dta = mysqli_fetch_array($r);

                    if (in_array($item, $linked)) {
                        $ldesc = explode(":", $dta['linked']);
                        $link = '<span style="font-size:20px; position:absolute; right:10px; top:3px"><span class="badge badge-light"><i class="fad fa-link"></i><span>C' . $ldesc[0] . '</span></span></span>';
                        $dataLink = 'data-link="C' . $ldesc[0] . '"';
                        $isLinked = "yes";
                        $dclass = 'isLinkedItem' . $ldesc[0];
                        $li[] = $ldesc[0] . "|" . $ldesc[2];
                        $linkedItem = 'isLinkedHolder' . $ldesc[0];
                    } else {
                        $linkedItem = "";
                        $link = '';
                        $dclass = '';
                        $isLinked = '';
                        $dataLink = '';
                    }
                    $col = '';
                    $tag = '';
                    $date = date('d-m-Y', $dta['insdate']);
                    $adefect = explode("|", $dta['adefect']);
                    $ldesc = explode(":", $dta['linked']);

                    if ($dta['result'] == "URGENT") {
                        $col = "#e96152";
                        $tag = "URGENT";
                        $title = "URGENT<br>" . $adefect[0];
                        $file = "file-excel";
                    }
                    if ($dta['result'] == "DEFECTS") {
                        $col = "#F4AA09";
                        $tag = "DEFECTS";
                        $title = "DEFECTS<br>" . $dta['bdefect'];
                        $file = "file-exclamation";
                    }
                    if ($dta['result'] == "PASS") {
                        $col = "#007E33";
                        $tag = "PASS";
                        $title = "Pass";
                        $file = "file-powerpoint";
                    }
                    if ($dta['result'] == "OBS") {
                        $col = "#333333";
                        $tag = "OBS";
                        $title = "OBS<br>" . $dta['obs'];
                        $file = "file-alt";
                    }
                    if ($dta['result'] == "PNA") {
                        $col = "#999999";
                        $tag = "PNA";
                        $title = "PNA";
                        $file = "file-minus";
                    }
                    if ($dta['result'] == "") {
                        $col = "#9211E8";
                        $tag = "P2UD";
                        $title = "P2UD";
                        $file = "file";
                    }
                    if ($dta['delivery'] != 0) {
                        $style = "";
                        $class = "delitem";
                    } else {
                        $style = "";
                        $class = "";
                    }
                    if (getWSData($dta['itemnumber']) != "None found") {
                        $wsDetected = 1;
                    }
                    if (getWSData($dta['itemnumber']) != "None found") {
                        $wsIcon = '<span style="font-size:20px; position:absolute; left:10px; top:3px"><span class="badge badge-light"><i class="fad fa-file-word"></i> ' . getWSData($dta['itemnumber']) . '</span></span>';
                    } else {
                        $wsIcon = '';
                    }
                ?>
            <div class="col-12 col-sm-6 col-lg-2 holder <?= $linkedItem ?>" style="margin-bottom:25px; <?= $style ?>">
                <div class="card card-body h-100 fileIcon text-center shadow-3-strong" style="overflow: hidden;">
                    <?php if ($dta['delivery'] != 0) { ?>
                    <div class="arrow-right green-text"><span>Delivered<br><?= date('d-m-Y', $dta['delivery']) ?></span>
                    </div>
                    <?php } else { ?>
                    <div class="arrow-right text-warning"><span>Not Delivered<br>&nbsp;</span></div>
                    <?php } ?>
                    <a class="mb-4" style="font-size: 40px; cursor: default" href="javascript:void(0)"
                        data-mdb-tooltip-init="" data-mdb-trigger="hover" data-mdb-html="true" data-mdb-placement="top"
                        title="<?= $title ?>"><i style="color:<?= $col ?>" class="fad fa-<?= $file ?>"
                            aria-hidden="true"></i><?= $link ?><?= $wsIcon ?>
                        <br />
                        <p class="text-dark">
                            <strong><?= $dta['repnumber'] ?></strong><br><strong><?= $dta['desc'] ?></strong><br><strong><?= $dta['serialnumber'] ?>
                                /
                                <?= $dta['plantnumber'] ?></strong><br><br><?= getReportDesc($dta['reptype'], 'formtype') ?><br><br><?= $date ?>
                        </p>
                    </a>
                    <span class="<?= $tag ?>" style="display:none"><?= $dta['repnumber'] ?></span>

                    <div
                        class="col-md-12 text-center form-check form-switch d-flex align-items-center justify-content-center mb-n4 itemToggle">
                        <input id="R<?= $dta['repnumber'] ?>"
                            class="form-check-input repitem <?= $class ?> <?= $dclass ?>" type="checkbox"
                            <?= $dataLink ?> data-status="<?= $tag ?>"
                            name="<?= $dta['repnumber'] ?>-<?= $dta['itemnumber'] ?>-<?= $dta['reptype'] ?>-<?= $dta['esname'] ?>"
                            style="transform: scale(1.5);">
                        <label class="form-check-label" for="R<?= $dta['repnumber'] ?>"></label>
                    </div>


                </div>
            </div>
            <?php $repCount++;
                } ?>
        </div>
    </div>

    <div id="scroller" class="col-12 col-md-4 col-lg-2">
        <div id="scroller-anchor"></div>
        <div class="card hoverable bg-info text-light">
            <div class="card-header bg-secondary">Delivery Options</div>
            <div class="card-body">
                <div class="row">
                    <span class="hidden">
                        <div class="col-12">Chains</div>
                        <div class="col-6 mb-2">
                            <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                                data-original-title="Merge all chained items into a single ZIP file.">
                                <input type="radio" class="form-check-input" id="mChain" name="chainMode" value="merge"
                                    checked onclick="unlockMulti()">
                                <label class="form-check-label" for="mChain">Merge</label>
                            </div>
                        </div>
                        <div class="col-6 mb-2">
                            <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                                data-original-title="Split all chained items into a separate ZIP files.">
                                <input type="radio" class="form-check-input" id="sChain" name="chainMode" value="split"
                                    onclick="lockMulti()">
                                <label class="form-check-label" for="sChain">Split</label>
                            </div>
                        </div>
                    </span>
                    <div class="col-12">Output</div>
                    <div class="col-6 mb-2">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="Deliver all documents as ZIP file.">
                            <input type="radio" class="form-check-input" id="zOutput" name="outputMode" value="zip"
                                <?php if (getDeliveryPref($_REQUEST['clientnumber']) == "zip") { ?>checked<?php } ?>>
                            <label class="form-check-label" for="zOutput">Zip</label>
                        </div>
                    </div>
                    <div class="col-6 mb-2">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="Deliver all documents as PDF files.">
                            <div class="pdfBtn">
                                <input type="radio" class="form-check-input" id="pOutput" name="outputMode" value="pdf"
                                    <?php if (getDeliveryPref($_REQUEST['clientnumber']) == "pdf") { ?>checked<?php } ?>>
                                <label class="form-check-label" for="pOutput">PDF</label>
                            </div>
                        </div>
                    </div>
                    <hr />
                    <div class="col-12 mt-4">Mode</div>
                    <div class="col-4 mb-2">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="Deliver all documents.">
                            <input type="radio" class="form-check-input" id="repOutput" name="outputType" value="rep"
                                onclick="unlockMulti()" checked>
                            <label class="form-check-label" for="repOutput">Files</label>
                        </div>
                    </div>
                    <div class="col-8 mb-2">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="Deliver only cover sheet.">
                            <div class="coverBtn">
                                <input type="radio" class="form-check-input" id="coverOutput" name="outputType"
                                    value="cover" onclick="lockMulti()">
                                <label class="form-check-label" for="coverOutput">Cover Sheet</label>
                            </div>
                        </div>
                        <hr />
                    </div>

                    <div class="col-12 mb-2 mt-4">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="The system will include the entire client schedule">
                            <input type="checkbox" class="form-check-input" id="schAttach">
                            <label class="form-check-label" for="schAttach">Attach Schedule</label>
                        </div>
                    </div>
                    <hr />
                    <div id="addWS" class="col-12 mb-2" style="display:none">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="The system will add any associated Written Scheme Files">
                            <input type="checkbox" class="form-check-input" id="wsAttach">
                            <label class="form-check-label" for="wsAttach">Attach Written Scheme</label>
                        </div>
                        <hr />
                    </div>

                    <div class="col-12 mb-2">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="The system will recreate all selected reports.<br><span class='text-warning'>This will increase the processing time.">
                            <input type="checkbox" class="form-check-input" id="forceGen">
                            <label class="form-check-label" for="forceGen">Force Regeneration</label>
                        </div>
                        <hr />
                    </div>

                    <div class="col-12 mb-2">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="The system will not update the reports as being delivered.">
                            <input type="checkbox" class="form-check-input" id="bypass">
                            <label class="form-check-label" for="bypass">Bypass Delivery Update</label>
                        </div>
                    </div>

                </div>
            </div>
            <div class="card-footer">
                <div class="col-md-12 text-center">
                    <a id="attachBtn" class="btn btn-secondary mb-3" href="javascript:void(0)"
                        onClick="getChecks()">Attach Selected</a>
                    <?php if ($repCount > 1) { ?>
                    <a id="attachBtn" class="btn btn-secondary multiBtn" href="javascript:void(0)"
                        onClick="getChecksMulti()">Produce Multiform</a>
                </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

</div>
<?php } ?>

<div id="chainedSelects" class="d-none">CHAIN</div>

<script>
let errordel = '';
let hse = '';
let selected = '';
<?php ////////////////////////////////////////////////////////////////////////////////
    // GEN PDF
    require('../deliveryModules/singles.php');
    require('../deliveryModules/multi.php');
    ////////////////////////////////////////////////////////////////////////////////
    // OUTPUT MODE
    require('../deliveryModules/merge.php');
    require('../deliveryModules/split.php');
    ////////////////////////////////////////////////////////////////////////////////
    // OUTPUT MODE
    require('../deliveryModules/outputZip.php');
    require('../deliveryModules/outputPdf.php');
    require('../deliveryModules/outputCover.php');
    ////////////////////////////////////////////////////////////////////////////////
    ?>
<?php
    if ($wsDetected == 1) { ?>
$('#addWS').css('display', 'block')
<?php } ?>

function lockMulti() {
    var elements = document.querySelectorAll('.multiBtn');
    elements.forEach(function(element) {
        element.style.display = 'none';
    });
}


function unlockMulti() {
    var elements = document.querySelectorAll('.multiBtn');
    elements.forEach(function(element) {
        element.style.display = 'block';
    });
}

function lockPdf() {
    var elements = document.querySelectorAll('.pdfBtn');
    elements.forEach(function(element) {
        element.style.display = 'none';
    });
    document.getElementById('zOutput').checked = true;
}

function unlockPdf() {
    var elements = document.querySelectorAll('.pdfBtn');
    elements.forEach(function(element) {
        element.style.display = 'block';
    });
}

function showlink() {
    var toggleBtn = document.getElementById("toggleBtn");
    var btnToggle = document.getElementById("btnToggle");
    toggleBtn.setAttribute('onclick', 'hideLink()');
    btnToggle.classList.remove('fa-sort-down');
    btnToggle.classList.add('fa-sort-up');

    var linkedSelect = document.getElementById('linkedSelect');
    linkedSelect.style.display = 'flex';
    linkedSelect.classList.add('d-flex');
}

function hideLink() {
    var toggleBtn = document.getElementById("toggleBtn");
    var btnToggle = document.getElementById("btnToggle");
    var linkedSelect = document.getElementById('linkedSelect');

    if (toggleBtn) {
        toggleBtn.setAttribute('onclick', 'showlink()');
    }

    if (btnToggle) {
        btnToggle.classList.remove('fa-sort-up');
        btnToggle.classList.add('fa-sort-down');
    }

    if (linkedSelect) {
        linkedSelect.style.display = 'none';
        linkedSelect.classList.remove('d-flex');
    }
}


var chains = [];

function buildSelects() {
    var chains = [];

    <?php if (!empty($li)) {
            $items = array_unique($li);
            sort($items, SORT_NUMERIC);
            foreach ($items as $i) {
                $i = explode('|', $i); ?>
    var linkedSelect = document.getElementById('linkedSelect');
    var newDiv = document.createElement('div');

    newDiv.className = 'col-2 col-md-1 mb-3 mt-3 form-check form-switch';
    newDiv.innerHTML =
        '<input id="checkLinked<?= $i[0] ?>" data-class="isLinkedItem<?= $i[0] ?>" data-id="<?= $i[0] ?>" class="form-check-input chainCheck" type="checkbox">' +
        '<label class="form-check-label" for="checkLinked<?= $i[0] ?>" data-mdb-tooltip-init data-placement="top" data-original-title="<?= htmlspecialchars($i[1], ENT_QUOTES) ?>">' +
        '<span class="badge badge-light"><i class="fad fa-link"></i> C<?= $i[0] ?></span></label>';

    linkedSelect.appendChild(newDiv);

    <?php } ?>
    <?php } ?>

    document.querySelectorAll('.chainCheck').forEach(function(checkLinked) {
        checkLinked.addEventListener('change', function() {
            var dataClass = checkLinked.getAttribute('data-class');
            var dataID = checkLinked.getAttribute('data-id');

            document.querySelectorAll('.chainCheck').forEach(function(otherCheck) {
                if (otherCheck !== checkLinked) {
                    otherCheck.checked = false;
                }
            });

            document.querySelectorAll('.holder').forEach(function(holder) {
                holder.style.display = 'none';
                var repitem = holder.querySelector('.repitem');
                if (repitem) {
                    repitem.checked = false;
                    repitem.dispatchEvent(new Event('change'));
                }
            });

            if (checkLinked.checked) {
                chains = [dataID];

                document.querySelectorAll('.isLinkedHolder' + dataID).forEach(function(holder) {
                    holder.style.display = 'block';
                    var repitem = holder.querySelector('.repitem');
                    if (repitem) {
                        repitem.checked = true;
                        repitem.dispatchEvent(new Event('change'));
                    }
                });
            } else {
                chains = [];
                document.querySelectorAll('.holder').forEach(function(holder) {
                    holder.style.display = 'block';
                });
            }

            document.getElementById('chainedSelects').textContent = chains.join(',');
        });
    });
}

document.querySelectorAll(".repitem").forEach(function(repitem) {
    repitem.addEventListener('change', function(event) {
        var holder = event.target.closest('.holder');
        if (event.target.checked) {
            holder.style.opacity = '1';
            holder.style.filter = 'grayscale(0%)';
        } else {
            holder.style.opacity = '0.6';
            holder.style.filter = 'grayscale(100%)';
        }
    });
});

function hideItems() {
    document.querySelectorAll(".repitem").forEach(function(repitem) {
        if (!repitem.checked) {
            repitem.closest('.holder').style.display = 'none';
        }
    });
}

function showItems() {
    document.querySelectorAll(".repitem").forEach(function(repitem) {
        if (!repitem.checked) {
            repitem.closest('.holder').style.display = 'block';
        }
    });
}

buildSelects();

document.getElementById("deCheckAll").addEventListener('change', function() {
    showItems();
    resetCheckbox('deCheckAll');
    document.querySelectorAll(".chainCheck").forEach(function(chainCheck) {
        chainCheck.checked = false;
    });
    document.querySelectorAll(".repitem").forEach(function(repitem) {
        if (repitem.checked) {
            repitem.click();
        }
    });
});

document.getElementById("deCheckDelivered").addEventListener('change', function() {
    resetCheckbox('deCheckDelivered');
    document.querySelectorAll(".delitem").forEach(function(delitem) {
        if (delitem.checked) {
            delitem.click();
        }
        delitem.closest('.holder').style.display = 'none';
    });
});

document.getElementById("checkAll").addEventListener('change', function() {
    showItems();
    resetCheckbox('checkAll');
    var rcount = 0;
    document.querySelectorAll(".repitem").forEach(function(repitem) {
        if (!repitem.checked) {
            rcount++;
            repitem.click();
        }
    });

    if (rcount > 40) {
        var dest =
            '<p class="text-center">You have exceeded maximum attachment limit for single PDF attachments. If you wish to proceed with multiform PDF, use the override button provided.</p><div class="col-12 text-center"><a class="btn btn-info float-start" onclick="killModal(\'warningBox\')">Accept</a><a class="btn btn-secondary float-end" onclick="killModal(\'warningBox\');unlockPdf()">Override</a></div>'
        loadModalContent(dest, "warningBox", "modal-md", 1070, "true", "Report limit warning", "override",
            unlockPdf);
        lockPdf();
    }
});
var fileset = [];

function manualSort(selected, errordel, hse) {
    var dest = ROOT_URL + '/functions/sortReports.php?selected=' + selected + '&errordel=' + selected + '&hse=' + hse +
        '&tenant=' + TENANT_URL
    loadModalContent(dest, "sortBox", "modal-xl", 1070, "true", "Sort Reports");
}

function manualSortSingle(selected, errordel, forceGen, hse, chainMode) {
    var dest = ROOT_URL + '/functions/sortReportsSingle.php?selected=' + selected + '&errordel=' + selected +
        '&forceGen=' + forceGen + '&chainMode=' + chainMode + '&hse=' + hse + '&tenant=' + TENANT_URL
    loadModalContent(dest, "sortBox", "modal-xl", 1070, "true", "Sort Reports");
}

////////////////////////////////////////////////////////////////////////////////

function genMasterPDF() {
    var multiListContent = document.getElementById('multiList').textContent.trim(); // Get and trim content of multiList
    var itemListContent = document.getElementById('itemList').textContent.trim(); // Get and trim content of itemList

    // If multiList has content, use it, otherwise fallback to itemList
    var str = multiListContent.length > 0 ? multiListContent : itemListContent;
    //alert(str)
    var schAttach = "";
    var wshAttach = "";

    if (parent.document.getElementById('schAttach').checked) {
        schAttach = "attach";
    }
    if (parent.document.getElementById('wsAttach').checked) {
        wshAttach = "attach";
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/functions/generators/genLPDF.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    // Capture full response and log it for debugging
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            //console.log('Server response:', xhr.responseText); // Log full response to console

            if (xhr.status === 200) {
                if (xhr.responseText.trim() === "done") {
                    document.getElementById('printReports').style.display = 'block';
                } else {
                    //console.log('Unexpected server output:', xhr.responseText);
                }
            } else {
                //console.log('Server error:', xhr.statusText);
            }
        }
    };

    xhr.send('files=' + encodeURIComponent(str) +
        '&dest=' + encodeURIComponent('<?= $_REQUEST['clientnumber'] ?>') +
        '&ws=' + encodeURIComponent(wshAttach) +
        '&sched=' + encodeURIComponent(schAttach) +
        '&tenant=' + TENANT_URL);
}





////////////////////////////////////////////////////////////////////////////////

function getDefects() {
    var defect = "";
    var x = 0;
    var urgentElements = document.querySelectorAll(".URGENT");

    urgentElements.forEach(function(element) {
        defect += element.textContent;
        if (x > 0) {
            defect += "|";
        }
        x += 1;
    });

    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/functions/generators/genZIPd.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            document.getElementById('defectList').value = xhr.responseText;
        }
    };
    xhr.send('clientnumber=' + encodeURIComponent('<?= $_REQUEST['clientnumber'] ?>') +
        '&defectList=' + encodeURIComponent(defect));
}

////////////////////////////////////////////////////////////////////////////////

function triggerZip() {
    genZips();
}

hideLink()

function resetCheckbox(id) {
    var checkbox = document.getElementById(id);
    checkbox.addEventListener('change', function() {
        if (checkbox.checked) {
            setTimeout(function() {
                checkbox.checked = false;
            }, 300); // 300ms delay before resetting to unchecked
        }
    });
}
resetCheckbox('checkAll');
resetCheckbox('deCheckAll');
resetCheckbox('deCheckDelivered');
</script>