<?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`=? AND `itemnumber`='" . $d[2] . "' ") 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'] ?? '';

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
    }

    .pointer {
        cursor: pointer
    }

    #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;
    }
</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') ?> | <?= htmlspecialchars($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] ?>')" data-mdb-tooltip-init data-mdb-placement="top"
            data-mdb-trigger="hover" title="Show item details">View plant details</a>
    </div>

    <form id="F<?= $d[2] ?>" class="form-horizontal">
        <fieldset>
            <fieldset>
                <?php require_once('forms/items/' . $_REQUEST['formnumber'] . '.php'); ?>

                <div style="<?= $displayMode ?>">
                    <?php require_once('forms/items/base_data.php'); ?>
                </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="create" />
                <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" data-mdb-tooltip-init
                            data-mdb-placement="top" data-mdb-trigger="hover" title="Save notes">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;
    });
    $imageCount = count($filteredImages);
    $imageMessage = "(" . $imageCount . " images found)";
    $imageDisplay = $imageCount > 0 ? "display: block;" : "display: none;";
    ?>
    <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
                    if (!function_exists('findReportImage')) {
                        function findReportImage(string $baseRelNoExt): ?string
                        {
                            if (file_exists($baseRelNoExt . '.jpg')) return $baseRelNoExt . '.jpg';
                            $matches = glob($baseRelNoExt . '__*.jpg');
                            if (!empty($matches)) return $matches[0];
                            return null;
                        }
                    }

                    if (!function_exists('extractDescFromPath')) {
                        function extractDescFromPath(string $path, string $baseNameNoExt): string
                        {
                            $fn = basename($path, '.jpg');
                            $base = basename($baseNameNoExt);
                            $prefix = $base . '__';
                            if (strpos($fn, $prefix) === 0) {
                                return substr($fn, strlen($prefix));
                            }
                            return '';
                        }
                    }

                    if (!function_exists('reportImageThumbPath')) {
                        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;
                        $imgPath = findReportImage($baseRel);
                        $previewPath = $imgPath ? reportImageThumbPath($imgPath) : '';
                        $prefill = $imgPath ? extractDescFromPath($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">
                                        <div class="input-group input-group-sm mb-2" role="group"
                                            aria-label="Report image title">
                                            <input type="text" class="form-control form-control-sm report-image-desc"
                                                id="imgDesc_<?= $d[2] ?>_<?= $file ?>"
                                                data-imagebase="<?= $d[2] ?>_<?= $file ?>"
                                                data-imageid="<?= $d[2] ?>_<?= $file ?>"
                                                data-current-desc="<?= htmlspecialchars($prefill) ?>"
                                                data-has-image="<?= $imgPath ? '1' : '0' ?>" placeholder="Image title"
                                                maxlength="60" autocomplete="off" value="<?= htmlspecialchars($prefill) ?>"
                                                <?= $imgPath ? '' : 'readonly' ?> />
                                            <button type="button" class="btn btn-info report-image-title-save"
                                                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-userid="<?= $d[2] ?>" data-meta-imageid="<?= $d[2] ?>_<?= $file ?>"
                                            data-meta-desc="<?= htmlspecialchars($prefill) ?>" data-size="1024,1024"
                                            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>
    <?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);
    })();

    // notes toggle
    function toggleNotes(cardId) {
        const body = document.getElementById(`cardBody-${cardId}`);
        const icon = document.getElementById(`toggleIcon-${cardId}`);
        const head = document.getElementById(`notesCardHead-${cardId}`);
        const open = body.style.display === "none";
        body.style.display = open ? "block" : "none";
        icon.classList.toggle('fa-chevrons-down', !open);
        icon.classList.toggle('fa-chevrons-up', open);
        head.classList.toggle('bg-success', open);
    }
    // images toggle
    function toggleImages(cardId) {
        const body = document.getElementById(`imageCardBody-${cardId}`);
        const icon = document.getElementById(`imageToggleIcon-${cardId}`);
        const head = document.getElementById(`imageCardHead-${cardId}`);
        const open = body.style.display === "none";
        body.style.display = open ? "block" : "none";
        icon.classList.toggle('fa-chevrons-down', !open);
        icon.classList.toggle('fa-chevrons-up', open);
        head.classList.toggle('bg-success', open);
    }
    // notes save
    function saveNotes() {
        const notes = document.getElementById('item_notes').value;
        fetch(ROOT_URL + '/functions/notesSave.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                item: '<?= $d[2] ?>',
                notes: notes,
                tenant: TENANT_URL
            })
        }).then(r => r.text()).then(t => {
            if (t.trim() === "success") {
                showResponse('success', 'Notes updated successfully');
            }
        }).catch(console.error);
    }

    // switches -> hidden fields
    function pm() {
        document.getElementById('pageSet').value =
            document.getElementById('pageMode').checked ? '0' : '1';
    }

    function ia() {
        document.getElementById('imageSet').value =
            document.getElementById('ImageAdd').checked ? '1' : '0';
    }

    function ta() {
        document.getElementById('tagSet').value =
            document.getElementById('TagAdd').checked ? '1' : '0';
    }

    // preflight
    document.addEventListener('DOMContentLoaded', function() {
        const btnSave = document.getElementById('btn_save');

        btnSave.addEventListener('click', function(event) {
            event.preventDefault();
            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>`;
            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>${document.getElementById('result').value}</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>

        `;
            loadModalContent(dest, "confirmBox", "modal-xl", 1099, "true", "Report Confirmation",
                "cancelConfirm", saveData);
        });

        // save
        function saveData() {
            killModal('confirmBox');

            document.querySelectorAll('.actionButton').forEach(b => b.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();

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

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

            const formData = new FormData(document.getElementById('F<?= $d[2] ?>'));
            formData.set('pageMode', pageSet);
            formData.set('imageMode', imageSet);
            formData.set('tagMode', tagSet);

            fetch(`${ROOT_URL}/includes/master/form_functions.php`, {
                    method: 'POST',
                    body: formData
                })
                .then(r => r.text())
                .then(result => {
                    const sec = result.trim().split('|');

                    if (sec[0] === "update_success") {
                        const postData = {
                            orientation: pageSet,
                            imageMode: imageSet,
                            tagMode: tagSet,
                            clientnumber: '<?= $d[0] ?>',
                            repnumber: '<?= $_REQUEST['repnumber'] ?>',
                            items: '<?= $d[2] ?>',
                            form: '<?= $_REQUEST['formnumber'] ?>',
                            tenant: TENANT_URL
                        };
                        const formParams = new URLSearchParams(postData);
                        fetch(`${ROOT_URL}/functions/generators/genPDF2.php`, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                },
                                body: formParams.toString()
                            })
                            .then(r => r.text())
                            .then(() => {
                                showResponse('success',
                                    'Your data has been updated successfully<br>PLEASE REISSUE DOCUMENTATION IF REQUIRED'
                                );
                                window.location.href = '<?= $_SESSION['returnLanding'] ?>';
                            });
                    }

                    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(r => r.text())
                            .then(() => {
                                showResponse('success', 'Your data has been saved successfully');
                                window.location.href = '<?= $_SESSION['returnLanding'] ?>';
                            });
                    }
                })
                .catch(err => {
                    console.error('Error:', err);
                    document.querySelectorAll('.actionButton').forEach(b => b.disabled = false);
                });
        }

        // save for later (unchanged)
        $("#btn_later").click(function(event) {
            event.preventDefault();
            $('#FUNCTION').val('save_for_later')
            if ($('#surveyor').val() === "NULL") {
                showResponse('danger', 'Please select surveyor before proceeding')
            } else {
                $('#formContainer').fadeTo("slow", 0.33);
                $('#loadingObject').css('display', 'block')
                $.ajax({
                    url: ROOT_URL + '/includes/master/form_functions.php',
                    type: 'POST',
                    data: $('#F<?= $d[2] ?>').serialize(),
                    success: function(result) {
                        if ($.trim(result) == "success") {
                            showResponse('success',
                                'Your data has been updated successfully<br>PLEASE REISSUE DOCUMENTATION IF REQUIRED'
                            )
                            document.location.href = '<?= $_SESSION['returnLanding'] ?>'
                        }
                        if ($.trim(result) == "success") {
                            showResponse('success', 'Your data has been saved successfully')
                            document.location.href = '<?= $_SESSION['returnLanding'] ?>'
                        }
                    }
                });
            }
        });

        // footer
        const footerControls = document.getElementById('footerControls');
        footerControls.innerHTML =
            '<button class="actionButton btn btn-secondary" onclick="triggerAction(\'btn_save\')" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Create report">CREATE</button> ' +
            '<button class="btn btn-warning" onclick="triggerAction(\'btn_later\')" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Save draft">SAVE FOR LATER</button>';
    });
</script>
