<?php

require_once(ROOT_URL . '/includes/master/form_functions.php');

$spellcheckEnabled = true;
$spellcheckStmt = $GLOBALS['con']->prepare("SELECT * FROM `system` WHERE `id`='1'") or die(mysqli_error($GLOBALS['con']));
if ($spellcheckStmt->execute()) {
    $spellcheckResult = $spellcheckStmt->get_result();
    if ($spellcheckRow = $spellcheckResult->fetch_assoc()) {
        $spellcheckEnabled = !array_key_exists('spellcheck_enabled', $spellcheckRow) || (int)$spellcheckRow['spellcheck_enabled'] === 1;
    }
}
$spellcheckStmt->close();

$rc = mysqli_query($GLOBALS['con'], "SELECT * FROM `reportitems` WHERE `repnumber`='" . $_REQUEST['repnumber'] . "' AND `itemnumber`='" . $d[2] . "' ");
$num = mysqli_num_rows($rc);

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $d[2]);
$stmt->execute();
$rc = $stmt->get_result();
$stmt->close();
$cd = mysqli_fetch_array($rc);


$stmt = $GLOBALS['con']->prepare("SELECT * FROM `reportitems` WHERE `repnumber`=?  ") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $_REQUEST['repnumber']);
$stmt->execute();
$rc = $stmt->get_result();
$stmt->close();
$cx = mysqli_fetch_array($rc);
$rd = enrepReportDataFromRow($cx ?? []);
$rd = formApplyDefaultText($_REQUEST['formnumber'] ?? '', $rd);
$cd = enrepApplyReportDataToItemDetails($cd, $rd);
$reportPdfOptions = enrepReportPdfOptionsFromRow($cx ?? []) ?? [];
$storedPageMode = $reportPdfOptions['orientation'] ?? '1';
$storedImageMode = $reportPdfOptions['imageMode'] ?? null;
$storedTagMode = $reportPdfOptions['tagMode'] ?? '';
$reportReviewAction = null;
$reviewRepnumber = trim((string)($_REQUEST['repnumber'] ?? ''));
$reviewClientnumber = (int)($d[0] ?? 0);
$reviewItemnumber = (int)($d[2] ?? 0);
if ($reviewRepnumber !== '' && $reviewClientnumber > 0 && $reviewItemnumber > 0) {
    $reviewStmt = $GLOBALS['con']->prepare("
        SELECT `status`, `admin_note`, `surveyor_response`, `updated_at`
        FROM `report_review_actions`
        WHERE `repnumber` = ? AND `clientnumber` = ? AND `itemnumber` = ?
        LIMIT 1
    ");
    if ($reviewStmt) {
        $reviewStmt->bind_param('sii', $reviewRepnumber, $reviewClientnumber, $reviewItemnumber);
        if ($reviewStmt->execute()) {
            $reviewResult = $reviewStmt->get_result();
            $reportReviewAction = $reviewResult ? $reviewResult->fetch_assoc() : null;
        }
        $reviewStmt->close();
    }
}

if (file_exists('images/tags/' .  $d[2] . '.jpg')) {
    $tagFound = 1;
} else {
    $tagFound = 0;
}
?>

<style>
    .lead,
    .control-label {
        font-size: 18px
    }

    .lead {
        font-weight: 400;
        text-transform: uppercase
    }

    #savingContainer {
        display: none;
        position: fixed;
        width: 100%;
        height: 1vh;
        top: 200px
    }

    #InfoBox {
        margin-bottom: 0 !important;
    }

    .form-details-trigger-row {
        margin: 0 0 1.35rem;
        position: relative;
        text-align: center;
        z-index: 2;
    }

    .form-details-toggle {
        background: #fff;
        border: 1px solid #7f8790;
        border-radius: 0 0 18px 18px;
        box-shadow: none;
        color: #747b83;
        font-size: .72rem;
        font-weight: 500;
        letter-spacing: .14em;
        line-height: 1;
        min-width: 176px;
        padding: .45rem 1rem .5rem;
        text-transform: uppercase;
    }

    .form-details-toggle:hover,
    .form-details-toggle:focus {
        background: #f8fafc;
        border-color: #536272;
        color: #1f3448;
        box-shadow: none;
    }

    .form-review-toggle {
        background: #f0ad4e;
        border: 1px solid #d99021;
        border-radius: 0 0 18px 18px;
        color: #fff;
        font-size: .72rem;
        font-weight: 700;
        letter-spacing: .1em;
        line-height: 1;
        min-width: 176px;
        padding: .45rem 1rem .5rem;
        position: absolute;
        right: 0;
        text-transform: uppercase;
        top: 0;
    }

    .form-review-toggle:hover,
    .form-review-toggle:focus {
        background: #d99021;
        border-color: #bf7b16;
        color: #fff;
        box-shadow: none;
    }

    .form-review-modal-grid {
        display: grid;
        gap: .35rem .75rem;
        grid-template-columns: 120px minmax(0, 1fr);
    }

    .form-review-modal-grid dt {
        color: #66717d;
        font-weight: 700;
        margin: 0;
    }

    .form-review-modal-grid dd {
        margin: 0;
        overflow-wrap: anywhere;
    }

    @media (max-width: 767px) {
        .form-review-toggle {
            display: inline-block;
            margin-top: .35rem;
            position: static;
        }
    }
</style>

<link rel="stylesheet" href="<?= ROOT_URL ?>/src/css/report-image-handler.css?v=20260724a">
<h2 id="InfoBox" class="alert alert-info text-center">REPORTING ON:
    <?= getReportDesc($_REQUEST['formnumber'], 'formtype') ?> | <?= $cd['desc'] ?></h2>

<div id="formContainer">
    <div class="form-details-trigger-row"><a href="javascript:void(0)" id="B<?= $d[2] ?>" class="form-details-toggle"
            onClick="showDetails('<?= $d[2] ?>')">View plant details</a>
        <?php if ($reportReviewAction) { ?>
            <a href="javascript:void(0)" class="form-review-toggle" onclick="showReportReviewNote()">Review note</a>
        <?php } ?>
    </div>
    <form id="F<?= $d[2] ?>" class="form-horizontal">
        <fieldset>

            <fieldset>
                <?php require_once('forms/items/' . $_REQUEST['formnumber'] . '.php'); ?>

                <div class="mt-3" style="<?= $displayMode ?>">
                    <div class="card border border-info">
                        <div class="card-body">
                            <?php require_once('forms/items/base_data_reload.php'); ?>
                        </div>
                    </div>
                </div>


                <input type="hidden" name="clientnumber" id="clientnumber" value="<?= $d[0] ?>" />
                <input type="hidden" name="itemnumber" id="itemnumber" value="<?= $d[2] ?>" />
                <input type="hidden" name="locnumber" id="locnumber" value="<?= $d[1] ?>" />
                <input type="hidden" name="reptype" id="reptype" value="<?= $_REQUEST['formnumber'] ?>" />
                <input type="hidden" name="pageMode" id="pageSet"
                    value="<?= htmlspecialchars($storedPageMode, ENT_QUOTES) ?>" />
                <?php if ($_REQUEST['formnumber'] == '101' || $_REQUEST['formnumber'] == '700' || $_REQUEST['formnumber'] == '701') {
                    $iMode = 1;
                    $iCheck = "checked";
                } else {
                    $iMode = 0;
                    $iCheck = "";
                } ?>
                <input type="hidden" name="imageMode" id="imageSet"
                    value="<?= htmlspecialchars($storedImageMode ?? (string)$iMode, ENT_QUOTES) ?>" />
                <input type="hidden" name="tagMode" id="tagSet"
                    value="<?= htmlspecialchars($storedTagMode, ENT_QUOTES) ?>" />
                <input type="hidden" name="FUNCTION" id="FUNCTION" value="update" />
                <input type="hidden" name="repnumber" id="repnumber" value="<?= $_REQUEST['repnumber'] ?>" />
                <input id="btn_save" value="save" style="display:none" />
                <input id="btn_later" value="save" style="display:none" />
                <input type="hidden" name="tenant" id="tenant" value="<?= TENANT_URL ?>" />
            </fieldset>
    </form>
    <div class="spacer"></div>


    <div class="row mt-4">

        <div class="col-12 col-md-12 text-center">
            <div class="card" id="card-<?= $d[2] ?>">
                <div class="card-header" id="notesCardHead-<?= $d[2] ?> pointer" onclick="toggleNotes('<?= $d[2] ?>')">
                    Item Notes
                    <a href="javascript:void(0)" class="float-end me-2 text-light">
                        <i class="fad fa-chevrons-down" id="toggleIcon-<?= $d[2] ?>"></i>
                    </a>
                </div>
                <div class="card-body" id="cardBody-<?= $d[2] ?>" style="display: none;">
                    <?php
                    $notecall = mysqli_query($GLOBALS['con'], "SELECT `itemnotes` FROM `itemdetails` WHERE `itemnumber`='" . $d[2] . "'") or die(mysqli_error($GLOBALS['con']));
                    $notedata = mysqli_fetch_array($notecall);
                    ?>
                    <textarea id="item_notes" class="form-control" rows="10"><?= $notedata['itemnotes'] ?></textarea>
                    <div class="col-12 col-md-12 text-center">
                        <a href="javascript:void(0)" onclick="saveNotes()" class="btn btn-white">Update Notes</a>
                    </div>
                </div>
            </div>
        </div>

    </div>
    <div class="spacer"></div>
    <?php
    $directory = 'images/report_images/';
    $pattern = $d[2] . '_*.jpg';
    $images = glob($directory . $pattern);
    $filteredImages = array_filter($images, function ($image) {
        return strpos($image, 'thumb') === false; // Exclude images with "thumb" in their name
    });
    $imageCount = count($filteredImages);
    $imageMessage = "(" . $imageCount . " images found)";
    if ($imageCount > 0) {
        $imageDisplay = "display: block;";
    } else {
        $imageDisplay = "display: none;";
    }
    ?>
<!-- Images -->
    <div class="col-12 col-md-12 text-center">
        <div class="card" id="imageCard-<?= $d[2] ?>">
            <div class="card-header" id="imageCardHead-<?= $d[2] ?>" onclick="toggleImages('<?= $d[2] ?>')">
                Item Images <?= $imageMessage ?>
                <a href="javascript:void(0)" class="float-end me-2 text-light">
                    <i class="fad fa-chevrons-down" id="imageToggleIcon-<?= $d[2] ?>"></i>
                </a>
            </div>

            <div class="card-body" id="imageCardBody-<?= $d[2] ?>" style="<?= $imageDisplay ?>">
                <div class="row">
                    <?php
                    function findReportImage(string $baseNoExt): ?string
                    {
                        // Legacy
                        if (file_exists($baseNoExt . '.jpg')) {
                            return $baseNoExt . '.jpg';
                        }

                        // New format with description
                        $matches = glob($baseNoExt . '__*.jpg');
                        if (!empty($matches)) {
                            return $matches[0];
                        }

                        return null;
                    }

                    function extractDescriptionFromFilename(string $path, string $baseNoExt): string
                    {
                        // baseNoExt example: images/report_images/1_1
                        // filename example: 1_1__some-desc.jpg
                        $filename = basename($path, '.jpg');
                        $base = basename($baseNoExt);

                        $prefix = $base . '__';
                        if (strpos($filename, $prefix) === 0) {
                            return substr($filename, strlen($prefix));
                        }

                        return '';
                    }

                    function reportImageThumbPath(string $path): string
                    {
                        $thumb = preg_replace('/\.jpg$/i', '_thumb.jpg', $path);
                        return $thumb && file_exists($thumb) ? $thumb : $path;
                    }
                    ?>

                    <?php foreach (range(1, 6) as $file) { ?>
                        <?php
                        $baseRel = 'images/report_images/' . $d[2] . '_' . $file; // no ext
                        $imgPath = findReportImage($baseRel);
                        $previewPath = $imgPath ? reportImageThumbPath($imgPath) : '';
                        $descValue = $imgPath ? extractDescriptionFromFilename($imgPath, $baseRel) : '';
                        ?>
                        <div class="col-12 col-sm-6 col-lg-2 mb-4 report-image-slot-col" style="position:relative">
                            <div class="col-12 col-md-12 text-center">
                                <div class="card report-image-card" data-report-image-slot="<?= $d[2] ?>_<?= $file ?>">
                                    <div class="card-header">Report Image #<?= $file ?></div>

                                    <div id="crop<?= $file ?>" class="card-body report-image-slot-body">

                                        <!-- Description (optional) -->
                                        <div class="input-group input-group-sm mb-2">
                                            <?php $hasImage = $imgPath ? '1' : '0'; ?>
                                            <input type="text" class="form-control form-control-sm report-image-desc"
                                                id="imgDesc_<?= $d[2] ?>_<?= $file ?>" placeholder="Description (optional)"
                                                maxlength="60" autocomplete="off"
                                                value="<?= htmlspecialchars($descValue) ?>"
                                                data-imagebase="<?= $d[2] ?>_<?= $file ?>"
                                                data-imageid="<?= $d[2] ?>_<?= $file ?>"
                                                data-current-desc="<?= htmlspecialchars($descValue) ?>"
                                                data-has-image="<?= $hasImage ?>" <?= $imgPath ? '' : 'readonly' ?> />
                                            <button type="button" class="btn btn-info report-image-title-save"
                                                data-imagebase="<?= $d[2] ?>_<?= $file ?>"
                                                data-imageid="<?= $d[2] ?>_<?= $file ?>" data-mdb-tooltip-init
                                                data-mdb-placement="top" data-mdb-trigger="hover" title="Save image title"
                                                <?= $imgPath ? '' : 'disabled' ?>>
                                                <i class="fad fa-save"></i>
                                            </button>

                                        </div>

                                        <div class="report-image-handler-slot report-image-dropzone"
                                            data-meta-desc="<?= htmlspecialchars($descValue) ?>"
                                            data-meta-userid="<?= $d[2] ?>" data-meta-imageid="<?= $d[2] ?>_<?= $file ?>"
                                            data-meta-tenant="<?= TENANT_URL ?>">
                                            <?php if ($imgPath) { ?>
                                                <img src="<?= $previewPath ?>?<?= rand() ?>"
                                                    data-full-src="<?= $imgPath ?>?<?= rand() ?>"
                                                    alt="Report Image #<?= $file ?>">
                                            <?php } else { ?>
                                                <div class="report-image-empty">Drop image here or use the buttons below</div>
                                            <?php } ?>
                                            <input type="file" name="file" accept="image/*"
                                                class="report-image-file d-none" />
                                        </div>

                                        <div class="report-image-actions" data-imageid="<?= $d[2] ?>_<?= $file ?>">
                                            <button type="button" class="btn btn-outline-primary btn-sm report-image-camera"
                                                data-action="camera" title="Take photo">
                                                <i class="fad fa-camera"></i>
                                            </button>
                                            <button type="button" class="btn btn-outline-primary btn-sm report-image-browse"
                                                data-action="browse" title="Browse images">
                                                <i class="fad fa-folder-open"></i>
                                            </button>
                                            <button type="button" class="btn btn-outline-secondary btn-sm report-image-edit"
                                                data-action="edit" title="Edit image">
                                                <i class="fad fa-crop-alt"></i>
                                            </button>
                                            <button type="button" class="btn btn-danger btn-sm report-image-remove"
                                                data-action="remove" title="Remove image">
                                                <i class="fad fa-trash"></i>
                                            </button>
                                        </div>

                                    </div>

                                </div>
                            </div>
                        </div>
                    <?php } ?>

                </div>
            </div>
        </div>
    </div>
</div>

<div id="loadingObject" style="display: none">
    <div class="col-12 text-center">
        <h1>
            <i class="fad fa-spinner fa-pulse fa-3x fa-fw"
                style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Saving Inspection
            Data<br><small>Please wait</small>
        </h1>
    </div>
</div>
<script>
    const FORM_REVIEW_NOTE = <?= json_encode($reportReviewAction ?: null, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>;

    function showReportReviewNote() {
        if (!FORM_REVIEW_NOTE) {
            showResponse('warning', 'No review note is recorded for this report.');
            return;
        }

        const statusLabels = {
            pending: 'Correction pending',
            responded: 'Surveyor responded',
            ready: 'Ready to send',
            complete: 'Action complete'
        };
        const status = String(FORM_REVIEW_NOTE.status || '');
        const adminNote = String(FORM_REVIEW_NOTE.admin_note || '').trim();
        const surveyorResponse = String(FORM_REVIEW_NOTE.surveyor_response || '').trim();
        const updated = Number(FORM_REVIEW_NOTE.updated_at || 0);
        const updatedText = updated > 0 ? new Date(updated * 1000).toLocaleString('en-GB') : '';
        const html = `
            <dl class="form-review-modal-grid mb-3">
                <dt>Status</dt><dd><span class="badge bg-warning text-white">${formReviewEscapeHtml(statusLabels[status] || status || 'Review')}</span></dd>
                ${updatedText ? `<dt>Updated</dt><dd>${formReviewEscapeHtml(updatedText)}</dd>` : ''}
            </dl>
            ${adminNote ? `<div class="alert alert-light border"><strong>Admin note</strong><br>${formReviewEscapeHtml(adminNote).replace(/\n/g, '<br>')}</div>` : ''}
            ${surveyorResponse ? `<div class="alert alert-info border"><strong>Surveyor response</strong><br>${formReviewEscapeHtml(surveyorResponse).replace(/\n/g, '<br>')}</div>` : ''}
        `;
        loadModalContent(html, 'reportReviewNoteBox', 'modal-lg', 1060, 'true', 'Report Review Note', 'close');
    }

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

    <?php if ($spellcheckEnabled) { ?>
    (function() {
        function runReportSpellcheck() {
            if (window.EnrepReportSpellcheck) {
                window.EnrepReportSpellcheck.init(document.getElementById('formContainer'), {
                    canAddWords: <?= ($_SESSION['usertype'] ?? '') === 'admins' ? 'true' : 'false' ?>,
                    tenant: '<?= TENANT_URL ?>'
                });
            }
        }

        if (window.EnrepReportSpellcheck) {
            runReportSpellcheck();
            return;
        }

        if (!window.enrepReportSpellcheckLoading) {
            window.enrepReportSpellcheckLoading = true;
            const script = document.createElement('script');
            script.src = '<?= ROOT_URL ?>/src/js/report-spellcheck.js?v=20260724f';
            script.onload = runReportSpellcheck;
            document.head.appendChild(script);
            return;
        }

        const wait = setInterval(function() {
            if (window.EnrepReportSpellcheck) {
                clearInterval(wait);
                runReportSpellcheck();
            }
        }, 50);
    })();
    <?php } ?>

    (function() {
        function runReportImageHandler() {
            if (window.EnrepReportImageHandler) {
                window.EnrepReportImageHandler.init(document);
            }
        }

        if (window.EnrepReportImageHandler) {
            runReportImageHandler();
            return;
        }

        if (!window.enrepReportImageHandlerLoading) {
            window.enrepReportImageHandlerLoading = true;
            const script = document.createElement('script');
            script.src = '<?= ROOT_URL ?>/src/js/report-image-handler.js?v=20260725a';
            script.onload = runReportImageHandler;
            document.head.appendChild(script);
            return;
        }

        const wait = setInterval(function() {
            if (window.EnrepReportImageHandler) {
                clearInterval(wait);
                runReportImageHandler();
            }
        }, 50);
    })();

    //Toggle notes visibility
    function toggleNotes(cardId) {
        const cardBody = document.getElementById(`cardBody-${cardId}`);
        const toggleIcon = document.getElementById(`toggleIcon-${cardId}`);
        const notesHead = document.getElementById(`notesCardHead-${cardId}`);

        if (cardBody.style.display === "none") {
            cardBody.style.display = "block";
            toggleIcon.classList.remove('fa-chevrons-down');
            toggleIcon.classList.add('fa-chevrons-up');
            notesHead.classList.add('bg-success');
            toggleIcon.parentElement.setAttribute('onclick', `toggleNotes('${cardId}')`);
        } else {
            cardBody.style.display = "none";
            toggleIcon.classList.remove('fa-chevrons-up');
            toggleIcon.classList.add('fa-chevrons-down');
            notesHead.classList.remove('bg-success');
            toggleIcon.parentElement.setAttribute('onclick', `toggleNotes('${cardId}')`);
        }
    }

    //Toggle images visibility
    function toggleImages(cardId) {
        const cardBody = document.getElementById(`imageCardBody-${cardId}`);
        const toggleIcon = document.getElementById(`imageToggleIcon-${cardId}`);
        const imageHead = document.getElementById(`imageCardHead-${cardId}`);

        if (cardBody.style.display === "none") {
            cardBody.style.display = "block";
            toggleIcon.classList.remove('fa-chevrons-down');
            toggleIcon.classList.add('fa-chevrons-up');
            imageHead.classList.add('bg-success');
            toggleIcon.parentElement.setAttribute('onclick', `toggleImages('${cardId}')`);
        } else {
            cardBody.style.display = "none";
            toggleIcon.classList.remove('fa-chevrons-up');
            toggleIcon.classList.add('fa-chevrons-down');
            imageHead.classList.remove('bg-success');
            toggleIcon.parentElement.setAttribute('onclick', `toggleImages('${cardId}')`);
        }
    }

    // Save the shared notes for the item
    function saveNotes() {
        // Get the value of the textarea with the ID 'item_notes'
        var notes = document.getElementById('item_notes').value;

        // Use fetch API for the POST request
        fetch(ROOT_URL + '/functions/notesSave.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded' // Send data as form-urlencoded
                },
                body: new URLSearchParams({
                    item: '<?= $d[2] ?>',
                    notes: notes,
                    tenant: TENANT_URL
                })
            })
            .then(response => response.text()) // Convert response to text
            .then(ret => {
                // Check if the returned text is "success"
                if (ret.trim() === "success") {
                    showResponse('success', 'Notes updated successfully');
                } else {
                    //debug(ret)
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    // Get save Parameters
    function pm() {
        // Get the checkbox and input elements
        const pageModeCheckbox = document.getElementById('pageMode');
        const pageSetInput = document.getElementById('pageSet');

        // Check if the checkbox is checked and set the input value accordingly
        if (pageModeCheckbox.checked) {
            pageSetInput.value = '0';
        } else {
            pageSetInput.value = '1';
        }
    }

    function ia() {
        // Get the checkbox and input elements
        const imageAddCheckbox = document.getElementById('ImageAdd');
        const imageSetInput = document.getElementById('imageSet');

        // Check if the checkbox is checked and set the input value accordingly
        if (imageAddCheckbox.checked) {
            imageSetInput.value = '1';
        } else {
            imageSetInput.value = '0';
        }
    }


    function ta() {
        // Get the checkbox and input elements
        const tagAddCheckbox = document.getElementById('TagAdd');
        const tagSetInput = document.getElementById('tagSet');

        // Check if the checkbox is checked and set the input value accordingly
        if (tagAddCheckbox.checked) {
            tagSetInput.value = '1';
        } else {
            tagSetInput.value = '0';
        }
    }


    // Save process preflight.
    document.addEventListener('DOMContentLoaded', function() {
        // Get the button with ID "btn_save"
        const btnSave = document.getElementById("btn_save");
        const reportForm = document.getElementById('F<?= $d[2] ?>');
        const getInspectionResult = function() {
            const resultField = reportForm ? reportForm.querySelector('[name="result"]') : document
                .getElementById('result');
            return resultField ? resultField.value : '';
        };

        // Add a click event listener to the button
        btnSave.addEventListener("click", function(event) {
            event.preventDefault();
            const pageSet = document.getElementById('pageSet').value;
            const imageSet = document.getElementById('imageSet').value;
            const tagSet = document.getElementById('tagSet').value;
            const bodyEl = document.getElementById('imageCardBody-<?= $d[2] ?>');
            let hasImages = false;

            if (bodyEl) {
                const slots = bodyEl.querySelectorAll('.report-image-handler-slot');
                for (const slot of slots) {
                    // saved image present?
                    const existing = slot.querySelector('img');
                    const saved = existing && /images\/report_images\//.test(existing.src);

                    // pending upload selected?
                    const inp = slot.querySelector('input[type="file"]');
                    const pending = inp && inp.files && inp.files.length > 0;

                    if (saved || pending) {
                        hasImages = true;
                        break;
                    }
                }
            }
            const attachImagesBlock = hasImages ?
                `
            <div class="col-12 col-md-4 mb-3">
            <h6><i class="fad fa-solid fa-images"></i> Attach Images:</h6>
            <div class="d-flex justify-content-center align-items-center">
                <span class="me-2">No</span>
                <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="ImageAdd" onchange="ia()" ${imageSet === '1' ? 'checked' : ''}>
                <label class="form-check-label" for="ImageAdd">Yes</label>
                </div>
            </div>
            </div>` :
                `
            <div class="col-12 col-md-4 mb-3">
            <h6><i class="fad fa-solid fa-images"></i> Attach Images:</h6>
            <div class="d-flex justify-content-center align-items-center">
                <span class="text-warning">No images found</span>
            </div>
            </div>`;

            // Construct the HTML content for the modal
            const dest = `
           <div class="container border mt-3">
                <div class="row">
                    <div class="col-12 col-md-6 bg-info text-light py-5 text-center">
                    <h5>The status of this Inspection is <strong>${getInspectionResult()}</strong></h5>
                    </div>
                    <div class="col-12 col-md-6 py-5 border-info text-center">
                    <h5>The frequency of this Inspection is <strong>${document.getElementById('frequency').value} Months</strong></h5>
                    </div>
                </div>
                <div class="row text-center mt-4">
                    <div class="col-12 col-md-4 mb-3">
                    <h6><i class="fad fa-solid fa-mobile-rotate"></i> Page Orientation:</h6>
                    <div class="d-flex justify-content-center align-items-center">
                        <span class="me-2">Portrait</span>
                        <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="pageMode" onchange="pm()" ${pageSet === '0' ? 'checked' : ''}>
                        <label class="form-check-label" for="pageMode">Landscape</label>
                        </div>
                    </div>
                    </div>
                    ${attachImagesBlock}
                     <?php if ($tagFound == 1) { ?>
                        <div class="col-12 col-md-4 mb-3">
                    <h6><i class="fad fa-solid fa-tags"></i> Insert Asset Tag Image:</h6>
                    <div class="d-flex justify-content-center align-items-center">
                        <span class="me-2">No</span>
                        <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="TagAdd" onchange="ta()" ${tagSet === '1' ? 'checked' : ''}>
                        <label class="form-check-label" for="TagAdd">Yes</label>
                        </div>
                    </div>
                    </div>
                    <?php } else { ?>
                        <div class="col-12 col-md-4 mb-3">
                    <h6><i class="fad fa-solid fa-tags"></i> Insert Asset Tag Image:</h6>
                    <div class="d-flex justify-content-center align-items-center">
                       <span class="text-warning">Tag not found</span>
                        </div>
                    </div>
                    </div>
                        <?php } ?>
             </div>

        `;

            // Call the loadModalContent function with the constructed HTML content
            loadModalContent(dest, "confirmBox", "modal-xl", 1099, "true", "Report Confirmation",
                "cancelConfirm", saveData);
        });





        let isFetching = false; // Flag to prevent duplicate fetch calls

        // Save Report
        function saveData() {
            // Prevent multiple fetch calls
            if (isFetching) {
                return;
            }

            killModal('confirmBox');
            let suv = document.getElementById('surveyor').value;

            // Disable all elements with the class 'actionButton'
            document.querySelectorAll('.actionButton').forEach(button => {
                button.disabled = true;
            });

            const pageSet = document.getElementById('pageSet').value;
            const imageSet = document.getElementById('imageSet').value;
            const tagSet = document.getElementById('tagSet').value;
            const confirmBox = document.getElementById('confirmBox');
            const modalInstance = new mdb.Modal(confirmBox);
            modalInstance.hide(); // Hide the modal

            if (document.getElementById('surveyor').value === "NULL") {
                showResponse('danger', 'Please select surveyor before proceeding');
                document.querySelectorAll('.actionButton').forEach(button => {
                    button.disabled = false;
                });
            } else {
                const formContainer = document.getElementById('formContainer');
                const loadingObject = document.getElementById('loadingObject');

                if (formContainer) {
                    formContainer.style.opacity = '0.33';
                    formContainer.style.transition = 'opacity 0.5s ease'; // Smooth transition
                }
                if (loadingObject) {
                    loadingObject.style.display = 'block';
                }

                const formData = new FormData(document.getElementById('F<?= $d[2] ?>'));
                formData.append('surveyor', suv);
                formData.set('pageMode', pageSet);
                formData.set('imageMode', imageSet);
                formData.set('tagMode', tagSet);
                isFetching = true; // Set flag to indicate fetch is in progress

                fetch(`${ROOT_URL}/includes/master/form_functions.php`, {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.text())
                    .then(result => {
                        const sec = result.trim().split('|');
                        if (sec[0] === "update_success") {
                            let reportsToGenerate = [];
                            try {
                                reportsToGenerate = JSON.parse(sec.slice(1).join('|') || '[]');
                            } catch (e) {
                                reportsToGenerate = [];
                            }

                            if (!Array.isArray(reportsToGenerate) || reportsToGenerate.length === 0) {
                                reportsToGenerate = [{
                                    repnumber: '<?= $_REQUEST['repnumber'] ?>',
                                    itemnumber: '<?= $d[2] ?>'
                                }];
                            }

                            const generationRequests = reportsToGenerate.map((report) => {
                                const formParams = new URLSearchParams({
                                    orientation: pageSet,
                                    imageMode: imageSet,
                                    tagMode: tagSet,
                                    clientnumber: '<?= $d[0] ?>',
                                    repnumber: report.repnumber,
                                    items: report.itemnumber,
                                    form: '<?= $_REQUEST['formnumber'] ?>',
                                    tenant: TENANT_URL
                                });

                                return fetch(`${ROOT_URL}/functions/generators/genPDF2.php`, {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/x-www-form-urlencoded'
                                        },
                                        body: formParams.toString()
                                    })
                                    .then(response => {
                                        if (!response.ok) {
                                            throw new Error(
                                                `HTTP error! Status: ${response.status}`);
                                        }
                                        return response.text();
                                    });
                            });

                            Promise.all(generationRequests)
                                .then(() => {
                                    showResponse('success',
                                        'Your data has been updated successfully<br>PLEASE REISSUE DOCUMENTATION IF REQUIRED'
                                    );
                                    window.location.href = '<?= $_SESSION['returnLanding'] ?>';
                                })
                                .catch(error => {
                                    console.error('Error:', error);
                                });
                        }

                        if (sec[0] === "success") {
                            const postData = {
                                orientation: pageSet,
                                imageMode: imageSet,
                                tagMode: tagSet,
                                clientnumber: '<?= $d[0] ?>',
                                repnumber: sec[1],
                                items: '<?= $d[2] ?>',
                                form: '<?= $_REQUEST['formnumber'] ?>',
                                tenant: TENANT_URL
                            };
                            const genParams = new URLSearchParams(postData);
                            fetch(`${ROOT_URL}/functions/generators/genPDF2.php`, {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded'
                                    },
                                    body: genParams.toString()
                                })
                                .then(response => response.text())
                                .then(data => {
                                    showResponse('success', 'Your data has been saved successfully');
                                    window.location.href = '<?= $_SESSION['returnLanding'] ?>';
                                });
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        document.querySelectorAll('.actionButton').forEach(button => {
                            button.disabled = false;
                        });
                    })
                    .finally(() => {
                        isFetching = false; // Reset flag when fetch is complete
                    });
            }
        }




        // Footer controls

        const footerControls = document.getElementById('footerControls');


        footerControls.innerHTML =
            '<button class="btn btn-secondary" onclick="triggerAction(\'btn_save\')">UPDATE</button>';

    });
</script>
