<?php
require_once __DIR__ . '/../security.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}

require_once __DIR__ . '/../../includes/master/form_functions.php';
require_once __DIR__ . '/../delivery/exclusions.php';

enrep_require_user();

$clientnumber = enrep_request_int('clientnumber');
$selectedSiteInt = enrep_request_int('site');
$selectedSite = $selectedSiteInt > 0 ? (string)$selectedSiteInt : '';
$startRaw = enrep_request_string('start', '', 40);
$endRaw = enrep_request_string('end', '', 40);
$startTs = strtotime($startRaw);
$endTs = strtotime($endRaw);

if ($clientnumber < 1) {
    enrep_fail(400, 'Invalid client');
}

if ($startTs === false) {
    $startTs = 0;
}

if ($endTs === false) {
    $endTs = time();
}

$startValue = htmlspecialchars($startRaw, ENT_QUOTES, 'UTF-8');
$endValue = htmlspecialchars($endRaw, ENT_QUOTES, 'UTF-8');
$useSessionItems = enrep_request_string('items', '', 20) !== '';

if (!function_exists('getReportDesc')) {
    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;
    }
}

function deliveryPlantDeliveryExclusionCodes(): array
{
    return delivery_exclusion_codes();
}

function deliveryApplyPlantDeliveryExclusions(array $repitems): array
{
    return delivery_filter_repitems_by_exclusions($repitems);
}

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

if (!$useSessionItems) {
    $sFilter = '';
    if ($selectedSiteInt > 0) {
        $sFilter = "AND b.locnumber=?";
    }

    $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 = ? AND a.insdate >= ? AND a.insdate <= ? $sFilter AND b.statuslive='1' 
ORDER BY abs(a.repitem) DESC 
") or die(mysqli_error($GLOBALS['con']));

    if ($selectedSiteInt > 0) {
        $stmt->bind_param('iiii', $clientnumber, $startTs, $endTs, $selectedSiteInt);
    } else {
        $stmt->bind_param('iii', $clientnumber, $startTs, $endTs);
    }

    $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 = enrep_int_list_from_mixed($_SESSION['items'] ?? []);
}

$items = deliveryApplyPlantDeliveryExclusions($items);
$coverCandidateItems = $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)
{
    $clientnumber = (int)$clientnumber;
    $stmt = $GLOBALS['con']->prepare("SELECT `delivery_type` FROM `clientdetails` WHERE `clientnumber`=?") or die($error = mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $d = mysqli_fetch_array($res);
    return $d['delivery_type'];
}

function deliveryItemTypeOptions(array $repitems)
{
    $repitems = array_values(array_unique(array_filter(array_map('intval', $repitems))));
    if (empty($repitems)) {
        return [];
    }

    $sqlList = implode(',', $repitems);
    $itemTypes = [];
    $itemTypeOptions = [];
    $res = mysqli_query($GLOBALS['con'], "
        SELECT DISTINCT b.`code`
        FROM `reportitems` a
        INNER JOIN `itemdetails` b ON b.`itemnumber` = a.`itemnumber`
        WHERE a.`repitem` IN ($sqlList)
          AND b.`code` IS NOT NULL
          AND b.`code` <> ''
        ORDER BY b.`code` ASC
    ");

    if (!$res) {
        return [];
    }

    while ($row = mysqli_fetch_assoc($res)) {
        $code = trim((string)($row['code'] ?? ''));
        if ($code !== '') {
            $itemTypes[$code] = '';
        }
    }

    if (empty($itemTypes)) {
        return [];
    }

    $quotedCodes = [];
    foreach (array_keys($itemTypes) as $code) {
        $quotedCodes[] = "'" . mysqli_real_escape_string($GLOBALS['con'], $code) . "'";
    }
    $codeList = implode(',', $quotedCodes);

    $tenantTypes = mysqli_query($GLOBALS['con'], "
        SELECT `code`, `description`
        FROM `dd_plant`
        WHERE `code` IN ($codeList)
    ");

    if ($tenantTypes) {
        while ($row = mysqli_fetch_assoc($tenantTypes)) {
            $code = trim((string)($row['code'] ?? ''));
            $title = trim((string)($row['description'] ?? ''));
            if ($code !== '' && $title !== '') {
                $itemTypes[$code] = $title;
            }
        }
    }

    if (isset($GLOBALS['master']) && $GLOBALS['master'] instanceof mysqli) {
        $masterQuotedCodes = [];
        foreach (array_keys($itemTypes) as $code) {
            $masterQuotedCodes[] = "'" . mysqli_real_escape_string($GLOBALS['master'], $code) . "'";
        }
        $masterCodeList = implode(',', $masterQuotedCodes);

        $masterTypes = mysqli_query($GLOBALS['master'], "
            SELECT `code`, `description`
            FROM `dd_plant`
            WHERE `code` IN ($masterCodeList)
        ");

        if ($masterTypes) {
            while ($row = mysqli_fetch_assoc($masterTypes)) {
                $code = trim((string)($row['code'] ?? ''));
                $title = trim((string)($row['description'] ?? ''));
                if ($code !== '' && $title !== '' && $itemTypes[$code] === '') {
                    $itemTypes[$code] = $title;
                }
            }
        }
    }

    foreach ($itemTypes as $code => $title) {
        $itemTypeOptions[$code] = $title !== '' ? $title : $code;
    }

    asort($itemTypeOptions, SORT_NATURAL | SORT_FLAG_CASE);
    return $itemTypeOptions;
}

function deliveryPuwerResultRank($result)
{
    $result = strtoupper(trim((string)$result));
    if ($result === 'URGENT') {
        return 3;
    }
    if ($result === 'DEFECT' || $result === 'DEFECTS') {
        return 2;
    }
    if ($result === 'OBS') {
        return 1;
    }

    return 0;
}

function deliveryPuwerItemSetLookup($clientnumber)
{
    $lookup = [];
    $clientnumber = (int)$clientnumber;
    if ($clientnumber < 1 || !isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
        return $lookup;
    }

    try {
        $stmt = $GLOBALS['con']->prepare("
            SELECT `id`, `itemnumbers_json`
            FROM `puwer_item_sets`
            WHERE `clientnumber` = ?
              AND `status` = 1
        ");
    } catch (mysqli_sql_exception $e) {
        return $lookup;
    }

    if (!$stmt) {
        return $lookup;
    }
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $sets = $stmt->get_result();
    $stmt->close();

    while ($set = mysqli_fetch_array($sets)) {
        $setId = (int)($set['id'] ?? 0);
        $setItems = json_decode((string)($set['itemnumbers_json'] ?? '[]'), true);
        if ($setId < 1 || !is_array($setItems)) {
            continue;
        }

        foreach ($setItems as $itemnumber) {
            $itemnumber = (int)$itemnumber;
            if ($itemnumber > 0) {
                $lookup[$itemnumber] = $setId;
            }
        }
    }

    return $lookup;
}

function deliveryCollapsePuwerReports(array $items, int $clientnumber)
{
    $items = array_values(array_filter(array_map('intval', $items)));
    if (empty($items)) {
        return $items;
    }

    $itemSetLookup = deliveryPuwerItemSetLookup($clientnumber);
    if (empty($itemSetLookup)) {
        return $items;
    }

    $chosenBySet = [];
    $puwerRepitems = [];

    foreach ($items as $position => $repitem) {
        $stmt = $GLOBALS['con']->prepare("
            SELECT `repitem`, `repnumber`, `itemnumber`, `reptype`, `result`
            FROM `reportitems`
            WHERE `repitem` = ?
            LIMIT 1
        ") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $repitem);
        $stmt->execute();
        $res = $stmt->get_result();
        $stmt->close();
        $report = mysqli_fetch_array($res);
        if (!$report) {
            continue;
        }

        $itemnumber = (int)($report['itemnumber'] ?? 0);
        $setId = $itemSetLookup[$itemnumber] ?? 0;
        if ($setId < 1 || (string)($report['reptype'] ?? '') !== '5002') {
            continue;
        }

        $puwerRepitems[$repitem] = $setId;
        $rank = deliveryPuwerResultRank($report['result'] ?? '');
        if (
            !isset($chosenBySet[$setId]) ||
            $rank > $chosenBySet[$setId]['rank']
        ) {
            $chosenBySet[$setId] = [
                'repitem' => $repitem,
                'rank' => $rank,
                'position' => $position,
            ];
        }
    }

    if (empty($chosenBySet)) {
        return $items;
    }

    $allowedPuwerRepitems = [];
    foreach ($chosenBySet as $chosen) {
        $allowedPuwerRepitems[(int)$chosen['repitem']] = true;
    }

    return array_values(array_filter($items, static function ($repitem) use ($puwerRepitems, $allowedPuwerRepitems) {
        return !isset($puwerRepitems[$repitem]) || isset($allowedPuwerRepitems[$repitem]);
    }));
}

$items = deliveryCollapsePuwerReports($items, (int)$clientnumber);

function deliveryParseLinkedChain($linkedRaw)
{
    $linkedRaw = trim((string)$linkedRaw);
    if ($linkedRaw === '' || $linkedRaw === '[]') {
        return null;
    }

    if (!preg_match('/^\s*(\d+)\s*:/', $linkedRaw, $match)) {
        return null;
    }

    $chainNumber = (string)$match[1];
    $chainTitle = 'C' . $chainNumber;
    $posLastColon = strrpos($linkedRaw, ':');
    if ($posLastColon !== false) {
        $tail = trim(substr($linkedRaw, $posLastColon + 1));
        if ($tail !== '' && $tail !== $linkedRaw) {
            $chainTitle = $tail;
        }
    }

    return [
        'number' => $chainNumber,
        'id' => 'C' . $chainNumber,
        'title' => $chainTitle,
    ];
}

function deliveryLinkedReportMap(array $repitems)
{
    $repitems = array_values(array_unique(array_filter(array_map('intval', $repitems))));
    if (empty($repitems)) {
        return [];
    }

    $sqlList = implode(',', $repitems);
    $map = [];
    $res = mysqli_query($GLOBALS['con'], "
        SELECT a.`repitem`, b.`linked`
        FROM `reportitems` a
        INNER JOIN `itemdetails` b ON b.`itemnumber` = a.`itemnumber`
        WHERE a.`repitem` IN ($sqlList)
          AND b.`linked` IS NOT NULL
          AND b.`linked` <> ''
          AND b.`linked` <> '[]'
    ");

    if (!$res) {
        return $map;
    }

    while ($row = mysqli_fetch_assoc($res)) {
        $chain = deliveryParseLinkedChain($row['linked'] ?? '');
        if ($chain) {
            $map[(int)$row['repitem']] = $chain;
        }
    }

    return $map;
}

function deliveryLocationName($locnumber, $clientnumber)
{
    static $cache = array();

    $locnumber = (int)$locnumber;
    $clientnumber = (int)$clientnumber;
    if ($locnumber < 1 || $clientnumber < 1) {
        return '';
    }

    $key = $clientnumber . ':' . $locnumber;
    if (array_key_exists($key, $cache)) {
        return $cache[$key];
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `locname` FROM `locations` WHERE `locnumber`=? AND `clientnumber`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('ii', $locnumber, $clientnumber);
    $stmt->execute();
    $result = $stmt->get_result();
    $stmt->close();
    $row = mysqli_fetch_array($result);

    $cache[$key] = trim((string)($row['locname'] ?? ''));
    return $cache[$key];
}

function deliveryPuwerCoverReportMap(array $candidateItems, array $deliveryItems, int $clientnumber): array
{
    $candidateItems = array_values(array_unique(array_filter(array_map('intval', $candidateItems))));
    $deliveryItems = array_fill_keys(array_values(array_unique(array_filter(array_map('intval', $deliveryItems)))), true);
    $itemSetLookup = deliveryPuwerItemSetLookup($clientnumber);
    if (empty($candidateItems) || empty($deliveryItems) || empty($itemSetLookup)) {
        return [];
    }

    $sqlList = implode(',', $candidateItems);
    $reportsBySet = [];
    $representativeBySet = [];
    $res = mysqli_query($GLOBALS['con'], "
        SELECT a.`repitem`, a.`repnumber`, a.`itemnumber`, a.`reptype`, a.`esname`, a.`result`,
               b.`linked`, b.`locnumber`
        FROM `reportitems` a
        INNER JOIN `itemdetails` b ON b.`itemnumber` = a.`itemnumber`
        WHERE a.`repitem` IN ($sqlList)
          AND a.`reptype` = 5002
    ");

    if (!$res) {
        return [];
    }

    while ($row = mysqli_fetch_assoc($res)) {
        $setId = $itemSetLookup[(int)($row['itemnumber'] ?? 0)] ?? 0;
        if ($setId < 1) {
            continue;
        }

        $chain = deliveryParseLinkedChain($row['linked'] ?? '');
        $report = [
            'repnumber' => (int)($row['repnumber'] ?? 0),
            'itemnumber' => (int)($row['itemnumber'] ?? 0),
            'form' => (int)($row['reptype'] ?? 0),
            'surveyor' => (int)($row['esname'] ?? 0),
            'status' => strtoupper(trim((string)($row['result'] ?? ''))),
            'chainId' => $chain['id'] ?? '',
            'chainTitle' => $chain['title'] ?? '',
            'locationName' => deliveryLocationName((int)($row['locnumber'] ?? 0), $clientnumber),
        ];
        $reportsBySet[$setId][] = $report;

        $repitem = (int)($row['repitem'] ?? 0);
        if (isset($deliveryItems[$repitem])) {
            $representativeBySet[$setId] = implode('-', [
                $report['repnumber'],
                $report['itemnumber'],
                $report['form'],
                $report['surveyor'],
            ]);
        }
    }

    $map = [];
    foreach ($representativeBySet as $setId => $token) {
        if (count($reportsBySet[$setId] ?? []) > 1) {
            $map[$token] = $reportsBySet[$setId];
        }
    }

    return $map;
}

$linkedMap = deliveryLinkedReportMap($items);
$linked = array_keys($linkedMap);
$itemTypeOptions = deliveryItemTypeOptions($items);
$puwerCoverReportMap = deliveryPuwerCoverReportMap($coverCandidateItems, $items, (int)$clientnumber);

if (empty($items)) {

    $siteRows = [];

    if ($clientnumber > 0) {
        $stmt = $GLOBALS['con']->prepare("
            SELECT `locnumber`, `locname`, `postcode`
            FROM `locations`
            WHERE `clientnumber` = ?
              AND `statuslive` = 1
            ORDER BY `locname` ASC
        ") or die(mysqli_error($GLOBALS['con']));

        $stmt->bind_param('i', $clientnumber);
        $stmt->execute();
        $sitesResult = $stmt->get_result();
        $stmt->close();

        while ($site = mysqli_fetch_array($sitesResult)) {
            $siteRows[] = $site;
        }
    }
?>

<style>
.delivery-empty-state .empty-icon {
    width: 110px;
    height: 110px;
    margin: 0 auto;
    border-radius: 50%;
    background: #f5f7fb;
    display: flex;
    align-items: center;
    justify-content: center;
}



.delivery-empty-state .filter-icon {
    width: 54px;
    height: 54px;
    min-width: 54px;
    border-radius: 50%;
    background: #f5f7fb;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.delivery-empty-state .filter-label {
    font-size: 1.1rem;
    font-weight: 600;
    color: #3f3f3f;
}

.delivery-empty-state .filter-hint {
    font-size: .85rem;
    color: #757575;
}

.delivery-empty-state .form-control,
.delivery-empty-state .select-wrapper {
    width: 100%;
}
</style>

<div id="nullScreen" class="container delivery-empty-state my-4">

    <div class="card shadow-4-strong border-0">
        <div class="card-body p-4 p-lg-5">

            <div class="text-center mb-4">
                <div class="empty-icon mb-3">
                    <i class="fad fa-file-slash fa-4x text-muted"></i>
                </div>

                <h3 class="fw-bold mb-2">No reports found</h3>

                <p class="text-muted mb-0">
                    No reports were found for the selected date range:
                    <strong><?= $startValue ?></strong>
                    <span class="mx-1">to</span>
                    <strong><?= $endValue ?></strong>
                </p>
            </div>

            <div class="note note-warning mb-4">
                <strong>Refine the search below.</strong>
                Select a site or adjust the date range, then load the reports again.
            </div>

            <section class="dark-grey-text">
                <div class="row g-4">

                    <div class="col-12 col-md-4">
                        <div class="card filter-card hover-shadow">
                            <div class="card-body">
                                <div class="d-flex align-items-center mb-3">
                                    <span class="filter-icon me-3">
                                        <i class="fad fa-building fa-2x green-text"></i>
                                    </span>
                                    <div>
                                        <div class="filter-label">
                                            Site <span class="filter-hint">(optional)</span>
                                        </div>
                                        <div class="filter-hint">Leave blank to search all sites.</div>
                                    </div>
                                </div>

                                <select class="form-control" id="siteList2" name="siteList">
                                    <option value="">All sites</option>

                                    <?php if (!empty($siteRows)) { ?>
                                    <optgroup label="Active Sites">
                                        <?php foreach ($siteRows as $site) {
                                                    $locnumber = (string)$site['locnumber'];
                                                    $postcode = trim((string)($site['postcode'] ?? ''));
                                                    $locname = trim((string)($site['locname'] ?? ''));

                                                    $labelParts = [];
                                                    if ($postcode !== '') {
                                                        $labelParts[] = $postcode;
                                                    }
                                                    if ($locname !== '') {
                                                        $labelParts[] = $locname;
                                                    }

                                                    $label = htmlspecialchars(implode(' - ', $labelParts), ENT_QUOTES, 'UTF-8');
                                                    $selected = ((string)$selectedSite === $locnumber) ? ' selected' : '';
                                                ?>
                                        <option value="<?= htmlspecialchars($locnumber, ENT_QUOTES, 'UTF-8') ?>"
                                            <?= $selected ?>>
                                            <?= $label ?>
                                        </option>
                                        <?php } ?>
                                    </optgroup>
                                    <?php } ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="col-12 col-md-4">
                        <div class="card filter-card hover-shadow">
                            <div class="card-body date-picker" data-mdb-toggle-button="false" data-format="dd-mm-yyyy">

                                <div class="d-flex align-items-center mb-3">
                                    <span class="filter-icon me-3">
                                        <i class="fad fa-calendar-alt fa-2x text-info"></i>
                                    </span>
                                    <div>
                                        <div class="filter-label">Start Date</div>
                                        <div class="filter-hint">First inspection date to include.</div>
                                    </div>
                                </div>

                                <input data-mdb-toggle="datepicker" data-mdb-confirmDateOnSelect class="form-control"
                                    type="text" name="date_start" id="date_start2" placeholder="Start date"
                                    value="<?= $startValue ?>">
                            </div>
                        </div>
                    </div>

                    <div class="col-12 col-md-4">
                        <div class="card filter-card hover-shadow">
                            <div class="card-body date-picker" data-mdb-toggle-button="false" data-format="dd-mm-yyyy">

                                <div class="d-flex align-items-center mb-3">
                                    <span class="filter-icon me-3">
                                        <i class="fad fa-calendar-alt fa-2x purple-text"></i>
                                    </span>
                                    <div>
                                        <div class="filter-label">End Date</div>
                                        <div class="filter-hint">Last inspection date to include.</div>
                                    </div>
                                </div>

                                <input data-mdb-toggle="datepicker" data-mdb-confirmDateOnSelect class="form-control"
                                    type="text" name="date_end" id="date_end2" placeholder="End date"
                                    value="<?= $endValue ?>">
                            </div>
                        </div>
                    </div>

                </div>

                <div class="text-center mt-4">
                    <button type="button" class="btn btn-info btn-lg" onclick="loadReports2()" data-mdb-tooltip-init
                        data-mdb-placement="top" data-mdb-trigger="hover"
                        title="Search again using the selected filters">
                        <i class="fad fa-search me-2"></i>Load Reports
                    </button>
                </div>
            </section>

        </div>
    </div>
</div>
<script>
(function() {
    var noReportBox = document.getElementById('nullScreen');

    if (!noReportBox || typeof mdb === 'undefined') {
        return;
    }

    var siteSelect = document.getElementById('siteList2');

    if (siteSelect) {
        new mdb.Select(siteSelect, {
            filter: true,
            container: 'body'
        });
    }

    var datepickerElements = noReportBox.querySelectorAll('.date-picker');

    datepickerElements.forEach(function(datepickerEl) {
        new mdb.Datepicker(datepickerEl, {
            confirmDateOnSelect: true,
            format: 'dd-mm-yyyy',
            container: 'body'
        });
    });
})();

window.loadReports2 = function() {
    var xsite = document.getElementById('siteList2') ? document.getElementById('siteList2').value : '';
    var xstart = document.getElementById('date_start2') ? document.getElementById('date_start2').value : '';
    var xend = document.getElementById('date_end2') ? document.getElementById('date_end2').value : '';

    if (xstart === '' || xend === '') {
        showResponse('danger', 'Please set START date and END date before proceeding');
        return;
    }

    var nullScreen = document.getElementById('nullScreen');
    var loadingObject = document.getElementById('loadingObject');

    if (nullScreen) {
        nullScreen.style.display = 'none';
    }

    if (loadingObject) {
        loadingObject.style.display = 'block';
    }

    var params = 'site=' + encodeURIComponent(xsite) +
        '&clientnumber=' + encodeURIComponent('<?= (int)$clientnumber ?>') +
        '&start=' + encodeURIComponent(xstart) +
        '&end=' + encodeURIComponent(xend) +
        '&tenant=' + TENANT_URL;

    loadContentAndExecuteScripts(ROOT_URL + '/functions/generators/genReports.php', 'reports', params, function() {
        if (loadingObject) {
            loadingObject.style.display = 'none';
        }

        var messageHolder = document.getElementById('messageHolder');

        if (messageHolder) {
            messageHolder.textContent =
                'Please find attached your inspection reports for the period ' + xstart + ' - ' + xend +
                '.';
        }
    });
};
</script>

<?php } else { ?>
<style>
.delivery-toolbar {
    background: #f7f9fb;
    border-left: 4px solid #2d4862;
    border-radius: 6px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
    margin: 0 0 1rem 0;
    padding: .75rem;
}

.delivery-toolbar .form-control,
.delivery-toolbar .btn {
    min-height: 38px;
}

.delivery-toolbar .form-label {
    color: #2d4862;
    font-size: .78rem;
    font-weight: 700;
    text-transform: uppercase;
}

.delivery-toolbar-compact-field {
    min-width: 0;
}

.holder {
    position: relative;
    opacity: 0.6;
    filter: grayscale(100%);
    transition: opacity .2s ease, filter .2s ease;
}

.delivery-report-grid {
    --bs-gutter-x: .75rem;
    --bs-gutter-y: .75rem;
}

.delivery-report-card {
    aspect-ratio: 1 / 1;
    border-radius: 8px;
    overflow: visible;
    padding: .65rem .65rem 2.25rem;
}

.delivery-report-card .delivery-icon-link {
    align-items: center;
    color: inherit;
    display: flex;
    flex-direction: column;
    font-size: clamp(1.45rem, 4vw, 2.25rem);
    height: 100%;
    justify-content: center;
    margin: 0;
    padding: .25rem .15rem 1.1rem;
    text-decoration: none;
}

.delivery-report-meta {
    font-size: .74rem;
    line-height: 1.18;
    margin: .35rem 0 0;
    max-width: 100%;
    overflow: hidden;
}

.delivery-report-meta strong,
.delivery-report-meta span {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.delivery-report-date {
    font-size: .72rem;
}

.delivery-report-card .arrow-right {
    font-size: .62rem;
}

.delivery-report-card .badge {
    max-width: calc(100% - 16px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.itemToggle {
    margin-bottom: 0 !important;
    position: absolute;
    bottom: .55rem;
    left: 50%;
    transform: translateX(-50%);
    z-index: 4;
}

.delivery-chain-control {
    position: relative;
}

.delivery-chain-toggle {
    align-items: center;
    display: flex;
    gap: .35rem;
    justify-content: space-between;
}

.delivery-toolbar .delivery-chain-toggle,
.delivery-toolbar .delivery-chain-toggle:hover,
.delivery-toolbar .delivery-chain-toggle:focus,
.delivery-toolbar .delivery-chain-toggle:active {
    background: #fff !important;
    border: 1px solid #ced4da !important;
    box-shadow: none !important;
    color: #4f4f4f !important;
    font-weight: 400;
    height: 38px;
    letter-spacing: 0;
    text-transform: none;
}

.delivery-toolbar .delivery-chain-toggle i {
    color: #6c757d;
    font-size: .9rem;
}

.delivery-chain-toggle span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.delivery-chain-menu {
    background: #fff;
    border: 1px solid #cfd8e3;
    border-radius: 6px;
    box-shadow: 0 8px 22px rgba(0, 0, 0, .18);
    display: none;
    left: 0;
    max-height: 280px;
    overflow-y: auto;
    padding: .5rem;
    position: absolute;
    top: calc(100% + .35rem);
    width: min(360px, 90vw);
    z-index: 1045;
}

.delivery-chain-control.is-open .delivery-chain-menu {
    display: block;
}

.delivery-chain-menu-header {
    align-items: center;
    border-bottom: 1px solid #edf1f5;
    display: flex;
    justify-content: space-between;
    margin-bottom: .35rem;
    padding-bottom: .35rem;
}

.delivery-chain-option {
    align-items: flex-start;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    gap: .45rem;
    margin: 0;
    padding: .38rem .35rem;
}

.delivery-chain-option:hover {
    background: #eef4f8;
}

.delivery-chain-option input {
    margin-top: .2rem;
}

.delivery-chain-option span {
    overflow: hidden;
    text-overflow: ellipsis;
}

.delivery-sublocation-option {
    padding-left: 1.85rem;
}

.delivery-sublocation-option span:before {
    color: #8a97a5;
    content: "- ";
}

.delivery-option-label {
    align-items: center;
    display: inline-flex;
    gap: .35rem;
}

.delivery-content-layout {
    align-items: start;
    display: grid;
    gap: 1rem;
    grid-template-columns: minmax(0, 1fr);
}

.delivery-reports-panel {
    min-width: 0;
}

.delivery-options-button {
    position: fixed;
    right: 16px;
    bottom: 18px;
    z-index: 1040;
}

.delivery-options-backdrop {
    background: rgba(0, 0, 0, .45);
    inset: 0;
    opacity: 0;
    pointer-events: none;
    position: fixed;
    transition: opacity .2s ease;
    z-index: 1055;
}

.delivery-options-canvas {
    background: #fff;
    bottom: 0;
    box-shadow: -8px 0 24px rgba(0, 0, 0, .22);
    max-width: min(420px, 94vw);
    overflow-y: auto;
    position: fixed;
    right: 0;
    top: 0;
    transform: translateX(105%);
    transition: transform .22s ease;
    width: 420px;
    z-index: 1060;
}

.delivery-options-canvas.is-open {
    transform: translateX(0);
}

.delivery-options-backdrop.is-open {
    opacity: 1;
    pointer-events: auto;
}

@media (max-width: 767.98px) {
    .delivery-toolbar {
        border-radius: 0;
        margin-left: -.75rem;
        margin-right: -.75rem;
        margin-bottom: 1.25rem;
        padding: .5rem;
        position: sticky;
        top: 58px;
        z-index: 20;
    }

    .delivery-content-layout {
        padding-top: .75rem;
    }

    .delivery-toolbar .form-label {
        display: none;
    }

    .delivery-toolbar .form-control,
    .delivery-toolbar .btn,
    .delivery-toolbar .input-group-text {
        font-size: .86rem;
        min-height: 34px;
        padding-bottom: .35rem;
        padding-top: .35rem;
    }

    .delivery-chain-control {
        position: static;
    }

    .delivery-chain-menu {
        left: .5rem;
        max-height: 220px;
        right: .5rem;
        top: calc(100% - .25rem);
        width: auto;
    }

    #reportFilterCount {
        font-size: .76rem;
        text-align: center;
    }
}

@media (min-width: 768px) and (max-width: 1199.98px) {
    .delivery-shown-summary {
        align-items: center;
        display: flex;
        gap: .65rem;
        justify-content: flex-start;
        text-align: left !important;
    }

    .delivery-shown-summary .form-label {
        margin: 0 !important;
        white-space: nowrap;
    }

    #reportFilterCount {
        white-space: nowrap;
    }
}

@media (min-width: 1200px) {
    .delivery-toolbar .row {
        flex-wrap: nowrap;
    }

    .delivery-toolbar .form-control,
    .delivery-toolbar .btn,
    .delivery-toolbar .input-group-text {
        font-size: .84rem;
        height: 34px;
        min-height: 34px;
        padding-left: .5rem;
        padding-right: .5rem;
    }

    .delivery-toolbar .form-label {
        font-size: .68rem;
    }

    .delivery-toolbar-search {
        flex: 0 0 21%;
        max-width: 21%;
    }

    .delivery-toolbar-type {
        flex: 0 0 15%;
        max-width: 15%;
    }

    .delivery-toolbar-action {
        flex: 0 0 10.5%;
        max-width: 10.5%;
    }

    .delivery-toolbar-location,
    .delivery-toolbar-chain {
        flex: 0 0 14.5%;
        max-width: 14.5%;
    }

    .delivery-toolbar-count {
        flex: 0 0 8%;
        max-width: 8%;
    }

    .delivery-content-layout {
        grid-template-columns: minmax(0, 1fr) 360px;
    }

    .delivery-options-backdrop {
        display: none;
    }

    .delivery-options-canvas {
        background: transparent;
        bottom: auto;
        box-shadow: none;
        max-width: none;
        overflow: visible;
        position: static;
        right: auto;
        top: auto;
        transform: none;
        transition: none;
        width: auto;
        z-index: auto;
    }

    .delivery-options-canvas .card {
        border-radius: 6px !important;
        max-height: calc(100vh - 80px);
        overflow: auto;
        position: sticky;
        top: 72px;
    }

    .delivery-options-canvas .card-header button {
        display: none;
    }
}
</style>
<div class="delivery-toolbar">
    <div class="row g-2 align-items-end">
        <div class="col-12 col-lg-3 delivery-toolbar-search delivery-toolbar-compact-field">
            <label for="deliveryReportSearch" class="form-label mb-1">Search reports</label>
            <div class="input-group">
                <span class="input-group-text"><i class="fad fa-search"></i></span>
                <input id="deliveryReportSearch" class="form-control" type="search"
                    placeholder="Report, plant, serial, location or type">
                <button id="deliveryReportSearchClear" class="btn btn-secondary" type="button">
                    <i class="fad fa-times"></i>
                </button>
            </div>
        </div>
        <div class="col-6 col-md-3 col-lg-2 delivery-toolbar-type delivery-toolbar-compact-field">
            <label for="deliveryReportTypeFilter" class="form-label mb-1">Item type</label>
            <select id="deliveryReportTypeFilter" class="form-control">
                <option value="">All types</option>
                <?php foreach ($itemTypeOptions as $itemTypeCode => $itemTypeTitle) { ?>
                <option value="<?= htmlspecialchars($itemTypeCode, ENT_QUOTES, 'UTF-8') ?>">
                    <?= htmlspecialchars($itemTypeTitle, ENT_QUOTES, 'UTF-8') ?></option>
                <?php } ?>
            </select>
        </div>
        <div class="col-6 col-md-3 col-lg-2 delivery-toolbar-action delivery-toolbar-compact-field">
            <label for="deliverySelectAction" class="form-label mb-1">Select</label>
            <select id="deliverySelectAction" class="form-control">
                <option value="">Choose</option>
                <option value="ALL">All</option>
                <option value="URGENT">Urgent</option>
                <option value="DEFECT">Defect</option>
                <option value="OBS">Obs</option>
                <option value="PNA">PNA</option>
            </select>
        </div>
        <div class="col-6 col-md-3 col-lg-2 delivery-toolbar-action delivery-toolbar-compact-field">
            <label for="deliveryDeselectAction" class="form-label mb-1">Deselect</label>
            <select id="deliveryDeselectAction" class="form-control">
                <option value="">Choose</option>
                <option value="ALL">All</option>
                <option value="DELIVERED">Delivered</option>
            </select>
        </div>
        <div id="deliveryLocationControl"
            class="col-6 col-md-3 col-lg-2 delivery-chain-control delivery-toolbar-location delivery-toolbar-compact-field">
            <label for="deliveryLocationToggle" class="form-label mb-1">Location</label>
            <button id="deliveryLocationToggle" class="btn btn-secondary w-100 delivery-chain-toggle" type="button"
                aria-expanded="false">
                <span id="deliveryLocationSummary">Locations</span>
                <i class="fad fa-map-marker-alt"></i>
            </button>
            <div id="deliveryLocationMenu" class="delivery-chain-menu">
                <div class="delivery-chain-menu-header">
                    <strong>Locations</strong>
                    <button id="clearLocationFilter" class="btn btn-sm btn-secondary" type="button">Clear</button>
                </div>
                <div id="deliveryLocationList"></div>
            </div>
        </div>
        <?php if (!empty($linked)) { ?>
        <div id="deliveryChainControl"
            class="col-6 col-md-3 col-lg-2 delivery-chain-control delivery-toolbar-chain delivery-toolbar-compact-field">
            <label for="deliveryChainToggle" class="form-label mb-1">Chains</label>
            <button id="deliveryChainToggle" class="btn btn-secondary w-100 delivery-chain-toggle" type="button"
                aria-expanded="false">
                <span id="deliveryChainSummary">Chains</span>
                <i class="fad fa-link"></i>
            </button>
            <div id="deliveryChainMenu" class="delivery-chain-menu">
                <div class="delivery-chain-menu-header">
                    <strong>Chains</strong>
                    <button id="clearChainFilter" class="btn btn-sm btn-secondary" type="button">Clear</button>
                </div>
                <div id="deliveryChainList"></div>
            </div>
        </div>
        <?php } else { ?>
        <div id="deliveryChainList" class="d-none"></div>
        <?php } ?>
        <div class="col-6 col-md-3 col-lg-2 d-xl-none">
            <label class="form-label mb-1">Options</label>
            <button type="button" class="btn btn-secondary w-100" onclick="openDeliveryOptions()">
                <i class="fad fa-sliders-h"></i> Delivery Options
            </button>
        </div>
        <div
            class="col-12 col-md-3 col-lg-1 text-md-end delivery-shown-summary delivery-toolbar-count delivery-toolbar-compact-field">
            <label class="form-label mb-1">Shown</label>
            <div id="reportFilterCount" class="text-muted small"></div>
        </div>
    </div>
</div>

<div class="delivery-content-layout">
    <div class="delivery-reports-panel">
        <div class="row delivery-report-grid">
            <?php
                $repCount = 0;
                foreach ($items as $item) {
                    $stmt = $GLOBALS['con']->prepare("SELECT 
                a.repitem,
                a.repnumber,
                a.reptype,
                a.itemnumber,
                a.insdate,
                a.reportdata,
                a.result,
                a.delivery,
                a.esname,
                a.esname,
                b.itemnumber,
                b.plantnumber,
                b.serialnumber,
                b.locnumber,
                b.subloc,
                b.linked,
                b.code,
                b.desc,
                b.manf,
                b.model
                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);

                    $chainData = $linkedMap[(int)$item] ?? deliveryParseLinkedChain($dta['linked'] ?? '');
                    if ($chainData) {
                        $chainId = $chainData['id'];
                        $chainTitle = $chainData['title'] !== '' ? $chainData['title'] : $chainId;
                        $chainBadgeLabel = htmlspecialchars($chainId, ENT_QUOTES);
                        $link = '<span style="font-size:20px; position:absolute; right:0; top:3px; width:100px"><span class="badge badge-light d-inline-flex align-items-center gap-1" title="' . htmlspecialchars($chainTitle, ENT_QUOTES) . '"><i class="fad fa-link"></i><span class="ms-1">' . $chainBadgeLabel . '</span></span></span>';
                        $dataLink = 'data-link="' . htmlspecialchars($chainId, ENT_QUOTES) . '"';
                        $isLinked = "yes";
                        $dclass = 'isLinkedItem' . $chainData['number'];
                        $li[] = $chainData['number'] . "|" . $chainTitle;
                        $linkedItem = 'isLinkedHolder' . $chainData['number'];
                    } else {
                        $chainId = '';
                        $chainTitle = '';
                        $linkedItem = "";
                        $link = '';
                        $dclass = '';
                        $isLinked = '';
                        $dataLink = '';
                    }
                    $col = '';
                    $tag = '';
                    $date = date('d-m-Y', $dta['insdate']);
                    $itemTypeCode = trim((string)($dta['code'] ?? ''));
                    $itemTypeLabel = (string)($itemTypeOptions[$itemTypeCode] ?? $itemTypeCode);
                    $locNumber = (int)($dta['locnumber'] ?? 0);
                    $locName = trim((string)deliveryLocationName($locNumber, $clientnumber));
                    if ($locName === '') {
                        $locName = $locNumber > 0 ? 'Location #' . $locNumber : 'No location';
                    }
                    $subLocName = trim((string)($dta['subloc'] ?? ''));
                    $locationFilterKey = 'loc:' . $locNumber;
                    $sublocFilterKey = $subLocName !== '' ? 'sub:' . $locNumber . '|' . strtolower($subLocName) : '';
                    $rd = enrepReportDataFromRow($dta);
                    $adefect = explode("|", (string)($rd['adefect'] ?? ''));
                    $ldesc = explode(":", $dta['linked']);

                    if ($dta['result'] == "URGENT") {
                        $col = "#e96152";
                        $tag = "URGENT";
                        $title = "URGENT<br>" . $adefect[0];
                        $file = "file-excel";
                    }
                    if ($dta['result'] == "DEFECT" || $dta['result'] == "DEFECTS") {
                        $col = "#F4AA09";
                        $tag = "DEFECT";
                        $title = "DEFECT<br>" . ($rd['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>" . ($rd['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-6 col-sm-4 col-md-3 col-lg-2 holder <?= $linkedItem ?>"
                data-report-number="<?= htmlspecialchars($dta['repnumber'], ENT_QUOTES) ?>"
                data-plant-number="<?= htmlspecialchars($dta['plantnumber'], ENT_QUOTES) ?>"
                data-serial-number="<?= htmlspecialchars($dta['serialnumber'], ENT_QUOTES) ?>"
                data-location-key="<?= htmlspecialchars($locationFilterKey, ENT_QUOTES) ?>"
                data-sublocation-key="<?= htmlspecialchars($sublocFilterKey, ENT_QUOTES) ?>"
                data-location-name="<?= htmlspecialchars($locName, ENT_QUOTES) ?>"
                data-sublocation-name="<?= htmlspecialchars($subLocName, ENT_QUOTES) ?>"
                data-report-type="<?= htmlspecialchars($itemTypeCode, ENT_QUOTES) ?>"
                data-report-type-label="<?= htmlspecialchars($itemTypeLabel, ENT_QUOTES) ?>"
                data-status="<?= htmlspecialchars($tag, ENT_QUOTES) ?>"
                data-chain-id="<?= htmlspecialchars($chainId, ENT_QUOTES) ?>"
                data-delivered="<?= $dta['delivery'] != 0 ? '1' : '0' ?>" style="<?= $style ?>">
                <div class="card card-body fileIcon text-center shadow-3-strong delivery-report-card">
                    <?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="delivery-icon-link" style="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 ?>
                        <p class="text-dark delivery-report-meta mt-1">
                            <strong><?= $dta['repnumber'] ?></strong>
                            <strong><?= $dta['desc'] ?></strong>
                            <span><?= $dta['plantnumber'] !== '' ? $dta['plantnumber'] : '' ?> <?= $dta['serialnumber'] !== '' ? ' / ' . $dta['serialnumber'] : '' ?></span>
                            <span><?= $dta['manf'] !== '' ? $dta['manf'] : '' ?> <?= $dta['model'] !== '' ? ' / ' . $dta['model'] : '' ?></span>
                            <span><i class="fad fa-map-marker-alt"></i>
                                <?= htmlspecialchars($locName) ?><?= $subLocName !== '' ? ' / ' . htmlspecialchars($subLocName) : '' ?></span>
                            
                            <span class="delivery-report-date"><?= $date ?></span>
                        </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>

    <?php
        $coverTemplates = [];
        $coverTemplatePreviews = [];
        $coverTemplateDir = '../../../' . trim((string)TENANT_URL, "/\\") . '/output/covers';
        if (is_dir($coverTemplateDir)) {
            foreach (glob($coverTemplateDir . '/*.php') ?: [] as $coverTemplatePath) {
                $coverKey = pathinfo($coverTemplatePath, PATHINFO_FILENAME);
                if (preg_match('/\A[A-Za-z0-9_-]{1,80}\z/', $coverKey)) {
                    $coverTemplates[$coverKey] = $coverKey === 'default'
                        ? 'Default'
                        : ucwords(str_replace(['_', '-'], ' ', $coverKey));
                    foreach (['png', 'jpg', 'jpeg', 'webp'] as $coverPreviewExt) {
                        $coverPreviewPath = $coverTemplateDir . '/previews/' . $coverKey . '.' . $coverPreviewExt;
                        if (is_file($coverPreviewPath)) {
                            $coverTemplatePreviews[$coverKey] = TENANT_URL . '/output/covers/previews/' . $coverKey . '.' . $coverPreviewExt;
                            break;
                        }
                    }
                }
            }
        }
        if (!isset($coverTemplates['default'])) {
            $coverTemplates = ['default' => 'Default'] + $coverTemplates;
        } else {
            $defaultLabel = $coverTemplates['default'];
            unset($coverTemplates['default']);
            $coverTemplates = ['default' => $defaultLabel] + $coverTemplates;
        }
        ?>

    <div id="deliveryOptionsBackdrop" class="delivery-options-backdrop" onclick="closeDeliveryOptions()"></div>
    <aside id="deliveryOptionsCanvas" class="delivery-options-canvas" aria-hidden="true">
        <div id="scroller-anchor"></div>
        <div class="card hoverable bg-info text-light h-100 rounded-0">
            <div class="card-header bg-secondary d-flex align-items-center justify-content-between">
                <span>Delivery Options</span>
                <button class="btn btn-sm btn-secondary" type="button" onclick="closeDeliveryOptions()">
                    <i class="fad fa-times"></i>
                </button>
            </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($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($clientnumber) == "pdf") { ?>checked<?php } ?>>
                                <label class="form-check-label" for="pOutput">PDF</label>
                            </div>
                        </div>
                    </div>
                    <hr />
                    <div class="col-12 mt-1">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>

                    </div>
                    <hr />
                    <div class="col-12 mb-2 mt-1">
                        <label class="form-label mb-1 text-light" for="coverTemplate">Cover Layout</label>
                        <div class="input-group input-group-sm">
                            <select class="form-control form-control-sm" id="coverTemplate">
                                <?php foreach ($coverTemplates as $coverKey => $coverLabel) { ?>
                                <option value="<?= htmlspecialchars($coverKey, ENT_QUOTES, 'UTF-8') ?>"
                                    data-preview="<?= htmlspecialchars($coverTemplatePreviews[$coverKey] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                                    <?= $coverKey === 'default' ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($coverLabel, ENT_QUOTES, 'UTF-8') ?>
                                </option>
                                <?php } ?>
                            </select>
                            <button class="btn btn-secondary" type="button" onclick="deliveryPreviewCoverTemplate()"
                                data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                title="Preview selected cover layout">
                                <i class="fad fa-eye"></i>
                            </button>
                        </div>
                    </div>
                    <hr />

                    <div class="col-12 mb-2 mt-1">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="The system will include the schedule for the loaded report range<?= $selectedSiteInt > 0 ? ' and selected site' : '' ?>.">
                            <input type="checkbox" class="form-check-input" id="schAttach">
                            <label class="form-check-label" for="schAttach">Attach Schedule</label>
                        </div>
                    </div>
                    <hr />
                    <?php if (!empty($linked)) { ?>
                    <div id="chainCoversOption" class="col-12 mb-2 d-none">
                        <div class="form-check" data-toggle="tooltip" data-placement="bottom" data-html="true"
                            data-original-title="Create separate cover sheets for selected chains, plus one for selected reports not in a chain.">
                            <input type="checkbox" class="form-check-input" id="splitCoverByChain">
                            <label class="form-check-label delivery-option-label" for="splitCoverByChain"
                                data-help-topic="delivery_chain_covers">Chain Covers</label>
                        </div>
                        <hr />
                    </div>
                    <?php } ?>
                    <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 delivery-option-label" for="forceGen"
                                data-help-topic="delivery_report_regeneration">Report 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 delivery-option-label" for="bypass"
                                data-help-topic="delivery_bypass">Bypass Delivery</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 mb-3" href="javascript:void(0)"
                        onClick="getChecksMulti()">Produce Multiform</a>
                </div>
                <?php } ?>
            </div>
        </div>
    </aside>
</div>

</div>
<?php } ?>

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

<script>
function deliveryListFromAny(value) {
    if (Array.isArray(value)) {
        return value.map(String).map(item => item.trim()).filter(Boolean);
    }

    const raw = String(value ?? '').trim();
    if (!raw || raw === '0' || raw.toLowerCase() === 'delivery') {
        return [];
    }

    try {
        const parsed = JSON.parse(raw);
        return deliveryListFromAny(parsed);
    } catch (error) {
        return raw.split('|').map(item => item.trim()).filter(Boolean);
    }
}

function deliveryListToJson(value) {
    return JSON.stringify(deliveryListFromAny(value));
}

function deliveryListAppend(existing, token) {
    const list = deliveryListFromAny(existing);
    if (token) {
        list.push(String(token));
    }
    return deliveryListToJson(list);
}

function deliveryStoreList(id, value) {
    const element = document.getElementById(id);
    if (element) {
        element.textContent = deliveryListToJson(value);
        if ('value' in element) {
            element.value = deliveryListToJson(value);
        }
    }
}

function deliveryStoreAppend(id, token) {
    const element = document.getElementById(id);
    if (element) {
        deliveryStoreList(id, deliveryListAppend(element.textContent || element.value || '', token));
    }
}

function deliveryTokenParts(token) {
    const parts = String(token ?? '').split('-');
    return {
        repnumber: parts[0] || '',
        itemnumber: parts[1] || '',
        reptype: parts[2] || '',
        esname: parts[3] || ''
    };
}

function deliveryJsArg(value) {
    return JSON.stringify(String(value ?? ''));
}

var deliverySelectedSite = '<?= (int)($selectedSiteInt ?? 0) ?>';
var errordel = '';
var hse = '';
var selected = '';
var chains = [];
var deliveryLocations = [];
var deliverySelectedTokens = new Set();
var deliveryPuwerCoverReportMap = <?= json_encode($puwerCoverReportMap, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;
<?php ////////////////////////////////////////////////////////////////////////////////
    require('../delivery/flow.php');
    ////////////////////////////////////////////////////////////////////////////////
    ?>
<?php
    if ($wsDetected == 1) { ?>
$('#addWS').css('display', 'block')
<?php } ?>

var deliveryReportFilterState = {
    search: '',
    reportType: '',
    status: '',
    chains: [],
    locations: [],
    hideDelivered: false
};

function openDeliveryOptions() {
    document.getElementById('deliveryOptionsCanvas')?.classList.add('is-open');
    document.getElementById('deliveryOptionsBackdrop')?.classList.add('is-open');
    document.getElementById('deliveryOptionsCanvas')?.setAttribute('aria-hidden', 'false');
}

function closeDeliveryOptions() {
    document.getElementById('deliveryOptionsCanvas')?.classList.remove('is-open');
    document.getElementById('deliveryOptionsBackdrop')?.classList.remove('is-open');
    document.getElementById('deliveryOptionsCanvas')?.setAttribute('aria-hidden', 'true');
}

function deliveryEscapeHtml(value) {
    return String(value ?? '').replace(/[&<>"']/g, function(match) {
        return {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        } [match];
    });
}

function deliveryCoverTemplateDescription(key) {
    const descriptions = {
        default: 'Standard report summary cover sheet.',
        priority_counts: 'Shows a priority count summary before the selected report table.',
        action_required: 'Groups selected reports by action level so urgent, defect, observation and PNA items are easy to review.',
        location_summary: 'Summarises selected reports by location before the selected report table.',
        executive_minimal: 'Compact high-level summary for a lighter management view.',
        exceptions_only: 'Highlights urgent, defect and observation items before the full selected report list.'
    };

    return descriptions[key] || 'Custom tenant cover sheet template.';
}

function deliveryReportFromInput(input) {
    if (!input || !input.name) {
        return null;
    }

    const parts = input.name.split('-');
    const holder = input.closest('.holder');
    const chainId = holder?.dataset?.chainId || '';
    const report = {
        repnumber: parseInt(parts[0] || '0', 10),
        itemnumber: parseInt(parts[1] || '0', 10),
        form: parseInt(parts[2] || '0', 10),
        surveyor: parseInt(parts[3] || '0', 10),
        status: input.getAttribute('data-status') || holder?.dataset?.status || '',
        chainId: chainId,
        chainTitle: deliveryManifestChainTitle(chainId)
    };

    return report.repnumber > 0 && report.itemnumber > 0 ? report : null;
}

function deliveryBuildCoverPreviewManifest() {
    const manifest = deliveryBuildManifest('multi');
    if (manifest.reports.length > 0) {
        return manifest;
    }

    manifest.reports = getVisibleReportCards().map(function(holder) {
        return deliveryReportFromInput(holder.querySelector('.repitem'));
    }).filter(Boolean);
    manifest.coverReports = deliveryBuildCoverReports(manifest.reports);

    return manifest;
}

function deliveryFileUrl(file) {
    if (!file || !file.source || !file.file) {
        return '';
    }

    const source = String(file.source).replace(/^\/+|\/+$/g, '');
    return '/' + source + '/' + encodeURIComponent(file.file);
}

function deliveryPreviewCoverTemplate() {
    const select = document.getElementById('coverTemplate');
    const option = select?.selectedOptions?. [0];
    if (!option) {
        return;
    }

    const key = option.value || '';
    const label = option.textContent.trim() || 'Cover Layout';
    const description = deliveryCoverTemplateDescription(key);
    const manifest = deliveryBuildCoverPreviewManifest();

    if (manifest.reports.length < 1) {
        loadModalContent(
            '<div class="p-3"><p class="mb-0">No reports are currently selected or visible to preview.</p></div>',
            'deliveryCoverPreviewBox',
            'modal-sm',
            1080,
            'true',
            'Cover Layout Preview',
            'close'
        );
        return;
    }

    manifest.options.coverTemplate = key;
    manifest.options.chainCovers = false;

    const html = `
        <div class="p-2">
            <h5 class="mb-2">${deliveryEscapeHtml(label)}</h5>
            <p class="text-muted">${deliveryEscapeHtml(description)}</p>
            <div id="deliveryCoverPreviewLoading" class="text-center p-5">
                <i class="fad fa-file-pdf fa-spin fa-3x"></i>
                <div class="mt-3">Generating preview from ${manifest.reports.length} report${manifest.reports.length === 1 ? '' : 's'}...</div>
            </div>
        </div>
    `;

    loadModalContent(html, 'deliveryCoverPreviewBox', 'modal-xl', 1080, 'true', 'Cover Layout Preview', 'close');

    deliveryPostJson('/functions/delivery/preview_cover.php', {
        manifest: manifest
    }).then(function(data) {
        const body = document.querySelector('#deliveryCoverPreviewBox .modal-body');
        const url = deliveryFileUrl(data.file) + '?preview=' + Date.now() +
            '#toolbar=0&navpanes=0&scrollbar=1&view=FitH';
        if (!body || !url) {
            return;
        }

        body.innerHTML = `
            <div class="p-2">
                <h5 class="mb-2">${deliveryEscapeHtml(label)}</h5>
                <p class="text-muted">${deliveryEscapeHtml(description)}</p>
                <iframe src="${deliveryEscapeHtml(url)}" style="width:100%; height:70vh; border:0;" title="${deliveryEscapeHtml(label)} preview"></iframe>
            </div>
        `;
    }).catch(function(error) {
        const body = document.querySelector('#deliveryCoverPreviewBox .modal-body');
        if (body) {
            body.innerHTML = `
                <div class="p-3">
                    <p class="text-danger mb-1"><strong>Unable to generate cover preview.</strong></p>
                    <p class="mb-0">${deliveryEscapeHtml(error.message || 'Please try again.')}</p>
                </div>
            `;
        }
    });
}

function getReportCards() {
    return Array.from(document.querySelectorAll('.holder'));
}

function getVisibleReportCards() {
    return getReportCards().filter(holder => holder.style.display !== 'none');
}

function deliveryReportTokenFromInput(input) {
    return input && input.name ? String(input.name) : '';
}

function deliverySetSelectedToken(input, selected) {
    const token = deliveryReportTokenFromInput(input);
    if (!token) {
        return;
    }

    if (selected) {
        deliverySelectedTokens.add(token);
    } else {
        deliverySelectedTokens.delete(token);
    }
}

function deliverySyncReportSelection(input, selected) {
    if (!input) {
        return;
    }

    input.dataset.selected = selected ? '1' : '0';
    deliverySetSelectedToken(input, selected);

    const holder = input.closest('.holder');
    if (holder) {
        holder.dataset.selected = selected ? '1' : '0';
    }

    updateChainCoversVisibility();
}

function updateChainCoversVisibility() {
    const option = document.getElementById('chainCoversOption');
    if (!option) {
        return;
    }

    const hasSelectedChain = Array.from(document.querySelectorAll('.repitem')).some(function(input) {
        const holder = input.closest('.holder');
        return !!holder?.dataset?.chainId && deliveryInputIsSelected(input);
    });

    option.classList.toggle('d-none', !hasSelectedChain);

    if (!hasSelectedChain) {
        const chainCovers = document.getElementById('splitCoverByChain');
        if (chainCovers) {
            chainCovers.checked = false;
        }
    }
}

function setReportChecked(input, checked) {
    if (!input) {
        return;
    }

    deliverySyncReportSelection(input, checked);

    if (input.checked !== checked) {
        input.checked = checked;
        input.dispatchEvent(new Event('change'));
    }
}

function clearReportSearch() {
    const search = document.getElementById('deliveryReportSearch');
    if (search) {
        search.value = '';
    }
    deliveryReportFilterState.search = '';
}

function clearChainSelection() {
    document.querySelectorAll('.delivery-chain-check').forEach(function(chainCheck) {
        chainCheck.checked = false;
    });
    chains = [];
    deliveryReportFilterState.chains = [];
    document.getElementById('chainedSelects').textContent = '';
    updateChainSummary();
}

function clearLocationSelection() {
    document.querySelectorAll('.delivery-location-check').forEach(function(locationCheck) {
        locationCheck.checked = false;
    });
    deliveryLocations = [];
    deliveryReportFilterState.locations = [];
    updateLocationSummary();
}

function updateChainSummary() {
    const summary = document.getElementById('deliveryChainSummary');
    if (!summary) {
        return;
    }

    if (!chains.length) {
        summary.textContent = 'Chains';
        return;
    }

    if (chains.length === 1) {
        const selected = document.querySelector('.delivery-chain-check:checked');
        summary.textContent = selected?.getAttribute('data-label') || chains[0];
        return;
    }

    summary.textContent = chains.length + ' chains';
}

function updateLocationSummary() {
    const summary = document.getElementById('deliveryLocationSummary');
    if (!summary) {
        return;
    }

    if (!deliveryLocations.length) {
        summary.textContent = 'Locations';
        return;
    }

    if (deliveryLocations.length === 1) {
        const selected = document.querySelector('.delivery-location-check:checked');
        summary.textContent = selected?.getAttribute('data-label') || '1 location';
        return;
    }

    summary.textContent = deliveryLocations.length + ' filters';
}

function closeDeliveryChainMenu() {
    const control = document.getElementById('deliveryChainControl');
    const toggle = document.getElementById('deliveryChainToggle');
    if (control) {
        control.classList.remove('is-open');
    }
    if (toggle) {
        toggle.setAttribute('aria-expanded', 'false');
    }
}

function closeDeliveryLocationMenu() {
    const control = document.getElementById('deliveryLocationControl');
    const toggle = document.getElementById('deliveryLocationToggle');
    if (control) {
        control.classList.remove('is-open');
    }
    if (toggle) {
        toggle.setAttribute('aria-expanded', 'false');
    }
}

function syncChainSelection() {
    chains = Array.from(document.querySelectorAll('.delivery-chain-check:checked')).map(function(chainCheck) {
        return chainCheck.value;
    }).filter(Boolean);

    clearReportSearch();
    deliveryReportFilterState.status = '';
    deliveryReportFilterState.chains = chains;
    document.getElementById('chainedSelects').textContent = chains.join(',');
    updateChainSummary();

    deselectAllReports();
    applyReportFilters();
    if (chains.length > 0) {
        selectVisibleReports();
    }
}

function syncLocationSelection() {
    deliveryLocations = Array.from(document.querySelectorAll('.delivery-location-check:checked')).map(function(
        locationCheck) {
        return locationCheck.value;
    }).filter(Boolean);

    deliveryReportFilterState.locations = deliveryLocations;
    updateLocationSummary();

    deselectAllReports();
    applyReportFilters();
    if (deliveryLocations.length > 0) {
        selectVisibleReports();
    }
}

function syncLocationChildren(parentCheck) {
    document.querySelectorAll('.delivery-location-check').forEach(function(locationCheck) {
        if (locationCheck.dataset.parentLocation === parentCheck.value) {
            locationCheck.checked = parentCheck.checked;
        }
    });
}

function syncLocationParent(childCheck) {
    const parentKey = childCheck.dataset.parentLocation || '';
    if (!parentKey) {
        return;
    }

    let parentCheck = null;
    const childChecks = [];
    document.querySelectorAll('.delivery-location-check').forEach(function(locationCheck) {
        if (locationCheck.value === parentKey && locationCheck.dataset.locationScope === 'location') {
            parentCheck = locationCheck;
        }
        if (locationCheck.dataset.parentLocation === parentKey) {
            childChecks.push(locationCheck);
        }
    });

    if (parentCheck && childChecks.length) {
        parentCheck.checked = childChecks.every(function(locationCheck) {
            return locationCheck.checked;
        });
    }
}

function handleLocationCheckChange(event) {
    const locationCheck = event.currentTarget;
    if (locationCheck.dataset.locationScope === 'location') {
        syncLocationChildren(locationCheck);
    } else {
        syncLocationParent(locationCheck);
    }

    syncLocationSelection();
}

function initDeliveryChainMenu() {
    const control = document.getElementById('deliveryChainControl');
    const toggle = document.getElementById('deliveryChainToggle');
    if (!control || !toggle) {
        return;
    }

    toggle.addEventListener('click', function(event) {
        event.stopPropagation();
        const isOpen = control.classList.toggle('is-open');
        toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    });

    control.addEventListener('click', function(event) {
        event.stopPropagation();
    });

    document.addEventListener('click', function() {
        closeDeliveryChainMenu();
    });

    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeDeliveryChainMenu();
        }
    });
}

function initDeliveryLocationMenu() {
    const control = document.getElementById('deliveryLocationControl');
    const toggle = document.getElementById('deliveryLocationToggle');
    const clear = document.getElementById('clearLocationFilter');
    if (!control || !toggle) {
        return;
    }

    toggle.addEventListener('click', function(event) {
        event.stopPropagation();
        const isOpen = control.classList.toggle('is-open');
        toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    });

    control.addEventListener('click', function(event) {
        event.stopPropagation();
    });

    if (clear) {
        clear.addEventListener('click', function(event) {
            event.preventDefault();
            clearLocationSelection();
            closeDeliveryLocationMenu();
            applyReportFilters();
        });
    }

    document.addEventListener('click', function() {
        closeDeliveryLocationMenu();
    });

    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeDeliveryLocationMenu();
        }
    });
}

function buildLocationSelects() {
    const locationList = document.getElementById('deliveryLocationList');
    if (!locationList) {
        return;
    }

    const locations = new Map();
    getReportCards().forEach(function(holder) {
        const locKey = holder.dataset.locationKey || '';
        if (!locKey) {
            return;
        }

        const locName = holder.dataset.locationName || locKey;
        const subKey = holder.dataset.sublocationKey || '';
        const subName = holder.dataset.sublocationName || '';

        if (!locations.has(locKey)) {
            locations.set(locKey, {
                label: locName,
                sublocations: new Map()
            });
        }

        if (subKey && subName) {
            locations.get(locKey).sublocations.set(subKey, subName);
        }
    });

    locationList.innerHTML = '';
    Array.from(locations.entries())
        .sort((a, b) => a[1].label.localeCompare(b[1].label))
        .forEach(function(entry) {
            const locKey = entry[0];
            const loc = entry[1];

            const locLabel = document.createElement('label');
            locLabel.className = 'delivery-chain-option delivery-location-option';
            locLabel.innerHTML =
                '<input type="checkbox" class="form-check-input delivery-location-check" value="' +
                deliveryEscapeHtml(locKey) + '" data-label="' + deliveryEscapeHtml(loc.label) +
                '" data-location-scope="location">' +
                '<span><strong>' + deliveryEscapeHtml(loc.label) + '</strong></span>';
            locationList.appendChild(locLabel);

            Array.from(loc.sublocations.entries())
                .sort((a, b) => a[1].localeCompare(b[1]))
                .forEach(function(subEntry) {
                    const subLabel = document.createElement('label');
                    subLabel.className =
                        'delivery-chain-option delivery-location-option delivery-sublocation-option';
                    subLabel.innerHTML =
                        '<input type="checkbox" class="form-check-input delivery-location-check" value="' +
                        deliveryEscapeHtml(subEntry[0]) + '" data-label="' + deliveryEscapeHtml(loc.label +
                            ' / ' + subEntry[1]) + '" data-parent-location="' + deliveryEscapeHtml(locKey) +
                        '">' +
                        '<span>' + deliveryEscapeHtml(subEntry[1]) + '</span>';
                    locationList.appendChild(subLabel);
                });
        });

    document.querySelectorAll('.delivery-location-check').forEach(function(locationCheck) {
        locationCheck.addEventListener('change', handleLocationCheckChange);
    });

    initDeliveryLocationMenu();
    updateLocationSummary();
}

function buildSelects() {
    const chainList = document.getElementById('deliveryChainList');

    <?php if (!empty($li)) {
            $items = array_unique($li);
            sort($items, SORT_NUMERIC);
            foreach ($items as $i) {
                $i = explode('|', $i);
                $chainName = trim($i[1] ?? '');
                if ($chainName === '') {
                    $chainName = 'Chain C' . $i[0];
                }
                $chainLabel = 'C' . $i[0] . ' ' . $chainName;
        ?>
    if (chainList) {
        var label = document.createElement('label');
        label.className = 'delivery-chain-option';
        label.innerHTML =
            '<input type="checkbox" class="form-check-input delivery-chain-check" value="C<?= $i[0] ?>" data-label="<?= htmlspecialchars($chainLabel, ENT_QUOTES) ?>">' +
            '<span><?= addslashes(htmlspecialchars($chainLabel, ENT_QUOTES)) ?></span>';
        chainList.appendChild(label);
    }

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

    document.querySelectorAll('.delivery-chain-check').forEach(function(chainCheck) {
        chainCheck.addEventListener('change', syncChainSelection);
    });

    initDeliveryChainMenu();
    updateChainSummary();
    buildLocationSelects();
}

function applyReportFilters() {
    const search = deliveryReportFilterState.search.toLowerCase();
    let visible = 0;
    const total = getReportCards().length;

    getReportCards().forEach(holder => {
        const statusMatch = !deliveryReportFilterState.status || holder.dataset.status ===
            deliveryReportFilterState.status;
        const reportTypeMatch = !deliveryReportFilterState.reportType || holder.dataset.reportType ===
            deliveryReportFilterState.reportType;
        const chainMatch = deliveryReportFilterState.chains.length === 0 || deliveryReportFilterState.chains
            .includes(holder.dataset.chainId);
        const locationMatch = deliveryReportFilterState.locations.length === 0 ||
            deliveryReportFilterState.locations.includes(holder.dataset.locationKey || '') ||
            deliveryReportFilterState.locations.includes(holder.dataset.sublocationKey || '');
        const haystack = [
            holder.dataset.reportNumber || '',
            holder.dataset.plantNumber || '',
            holder.dataset.serialNumber || '',
            holder.dataset.locationName || '',
            holder.dataset.sublocationName || '',
            holder.dataset.reportTypeLabel || ''
        ].join(' ').toLowerCase();
        const searchMatch = !search || haystack.indexOf(search) !== -1;
        const show = statusMatch && reportTypeMatch && chainMatch && locationMatch && searchMatch;

        holder.style.display = show ? '' : 'none';
        if (!show) {
            setReportChecked(holder.querySelector('.repitem'), false);
        }
        if (show) {
            visible += 1;
        }
    });

    const count = document.getElementById('reportFilterCount');
    if (count) {
        count.textContent = visible + ' of ' + total + ' reports shown';
    }
}

function maybeWarnForLargeSelection(count) {
    if (count > 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();
    }
}

function selectVisibleReports() {
    let count = 0;
    getVisibleReportCards().forEach(function(holder) {
        var repitem = holder.querySelector(".repitem");
        if (repitem) {
            count++;
            setReportChecked(repitem, true);
        }
    });
    maybeWarnForLargeSelection(count);
}

function deselectAllReports() {
    document.querySelectorAll(".repitem").forEach(function(repitem) {
        setReportChecked(repitem, false);
    });
}

function deselectDeliveredReports() {
    document.querySelectorAll(".delitem").forEach(function(delitem) {
        setReportChecked(delitem, false);
    });
}

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

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

document.addEventListener('pointerdown', function(event) {
    const toggle = event.target.closest('.itemToggle');
    if (!toggle) {
        return;
    }

    const input = toggle.querySelector('.repitem');
    if (input) {
        input.dataset.previousChecked = input.checked ? '1' : '0';
    }
});

document.addEventListener('click', function(event) {
    const toggle = event.target.closest('.itemToggle');
    if (!toggle) {
        return;
    }

    const input = toggle.querySelector('.repitem');
    if (!input) {
        return;
    }

    setTimeout(function() {
        const previous = input.dataset.previousChecked === '1';
        let selected = input.checked;

        if (input.checked === previous && event.target !== input) {
            selected = !previous;
            input.checked = selected;
        }

        deliverySyncReportSelection(input, selected);
        input.dispatchEvent(new Event('change'));
    }, 0);
}, true);

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

function showItems() {
    applyReportFilters();
}

buildSelects();
updateChainCoversVisibility();

document.getElementById('deliveryReportSearch')?.addEventListener('input', function() {
    deliveryReportFilterState.search = this.value.trim();
    applyReportFilters();
});

document.getElementById('deliveryReportSearchClear')?.addEventListener('click', function() {
    const search = document.getElementById('deliveryReportSearch');
    if (search) {
        search.value = '';
    }
    deliveryReportFilterState.search = '';
    applyReportFilters();
});

document.getElementById('deliveryReportTypeFilter')?.addEventListener('change', function() {
    deliveryReportFilterState.reportType = this.value;
    deselectAllReports();
    applyReportFilters();
    if (this.value) {
        selectVisibleReports();
    }
});

document.getElementById('clearChainFilter')?.addEventListener('click', function() {
    clearChainSelection();
    applyReportFilters();
});

document.getElementById('deliverySelectAction')?.addEventListener('change', function() {
    const action = this.value;
    if (!action) {
        return;
    }

    clearReportSearch();
    clearChainSelection();
    deliveryReportFilterState.status = action === 'ALL' ? '' : action;
    applyReportFilters();
    selectVisibleReports();
    this.value = '';
});

document.getElementById('deliveryDeselectAction')?.addEventListener('change', function() {
    const action = this.value;
    if (action === 'ALL') {
        deselectAllReports();
    }
    if (action === 'DELIVERED') {
        deselectDeliveredReports();
    }
    this.value = '';
});
applyReportFilters();
var fileset = [];

function manualSort(selected, errordel, hse) {
    deliveryOpenSortModal('/functions/sortReports.php', {
        selected: deliveryListFromAny(selected),
        errordel: deliveryListFromAny(errordel),
        hse: hse || '',
        tenant: TENANT_URL
    });
}

function manualSortSingle(selected, errordel, forceGen, hse, chainMode) {
    deliveryOpenSortModal('/functions/sortReportsSingle.php', {
        selected: deliveryListFromAny(selected),
        errordel: deliveryListFromAny(errordel),
        forceGen: forceGen || '',
        chainMode: chainMode || '',
        hse: hse || '',
        tenant: TENANT_URL
    });
}

function deliveryOpenSortModal(endpoint, payload) {
    fetch(ROOT_URL + endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Sort modal failed to load');
            }
            return response.text();
        })
        .then(html => {
            loadModalContent(html, "sortBox", "modal-xl", 1070, "true", "Sort Reports");
        })
        .catch(error => {
            console.error(error);
            showResponse('danger', 'Unable to load the sort modal');
        });
}

function deliveryInjectHtml(containerId, html) {
    const container = document.getElementById(containerId);
    if (!container) {
        return;
    }

    container.innerHTML = html;
    const scripts = Array.from(container.querySelectorAll('script'));
    scripts.forEach(oldScript => {
        const script = document.createElement('script');
        Array.from(oldScript.attributes).forEach(attr => script.setAttribute(attr.name, attr.value));
        script.textContent = oldScript.textContent;
        document.body.appendChild(script);
        document.body.removeChild(script);
    });
}

function deliveryReleaseMailerScroll() {
    document.body.classList.add('delivery-mailer-active');

    [document.documentElement, document.body].forEach(function(element) {
        if (!element) {
            return;
        }

        element.style.overflow = '';
        element.style.overflowY = 'auto';
        element.style.height = 'auto';
    });

    ['delivery', 'mailerContainer', 'deliveryMailerPane'].forEach(function(id) {
        const element = document.getElementById(id);
        if (!element) {
            return;
        }

        element.style.overflow = 'visible';
        element.style.overflowY = 'visible';
        element.style.height = 'auto';
        element.style.maxHeight = 'none';
    });
}

function deliveryScrollMailerIntoView() {
    const mailer = document.getElementById('deliveryMailerPane') || document.getElementById('mailerContainer');
    if (!mailer) {
        return;
    }

    deliveryReleaseMailerScroll();
    window.requestAnimationFrame(function() {
        deliveryReleaseMailerScroll();
        mailer.scrollIntoView({
            block: 'start',
            inline: 'nearest',
            behavior: 'auto'
        });
    });
}

function deliveryLoadMailer(payload) {
    const mailerPayload = Object.assign({
        clientnumber: '<?= (int)$clientnumber ?>',
        site: deliverySelectedSite,
        tenant: TENANT_URL
    }, payload || {});

    fetch(ROOT_URL + '/includes/master/deliveryMailer.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(mailerPayload)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Delivery mailer failed to load');
            }
            return response.text();
        })
        .then(html => {
            deliveryInjectHtml('mailerContainer', html);
            deliveryScrollMailerIntoView();
        })
        .catch(error => {
            console.error(error);
            showResponse('danger', 'Unable to load the delivery mailer');
        });
}

function deliveryJsonValue(value) {
    if (typeof value !== 'string') {
        return value;
    }

    try {
        return JSON.parse(value);
    } catch (error) {
        return value;
    }
}

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

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('<?= (int)$clientnumber ?>') +
        '&ws=' + encodeURIComponent(wshAttach) +
        '&sched=' + encodeURIComponent(schAttach) +
        '&site=' + encodeURIComponent(deliverySelectedSite) +
        '&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('<?= (int)$clientnumber ?>') +
        '&defectList=' + encodeURIComponent(defect));
}

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

function triggerZip() {
    deliveryPromptSort('multi');
}
</script>
