<?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_temp` 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_temp` 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);
$iMode = in_array((string)($_REQUEST['formnumber'] ?? ''), ['101', '700', '701'], true) ? 1 : 0;
$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;
}
?>
<script src="<?= ROOT_URL ?>/src/main.min.js"></script>
<link rel="stylesheet" href="<?= ROOT_URL ?>/src/style.css?v=5.0.3">
<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;
}
</style>
<h2 id="InfoBox" class="alert alert-info text-center m-0">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></div>

    <form id="F<?= $d[2] ?>" class="form-horizontal">


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

            <div style="<?= $displayMode ?>">
                <?php //echo "savemode=".$_REQUEST['savemode'];
                ?>
                <?php require_once('forms/items/base_data_reload.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="imageMode" id="imageSet" value="<?= htmlspecialchars($storedImageMode ?? (string)$iMode, ENT_QUOTES) ?>" />
            <input type="hidden" name="pageMode" id="pageSet" value="<?= htmlspecialchars($storedPageMode, ENT_QUOTES) ?>" />
            <input type="hidden" name="tagMode" id="tagSet" value="<?= htmlspecialchars($storedTagMode, ENT_QUOTES) ?>" />
            <input type="hidden" name="reptype" id="reptype" value="<?= $_REQUEST['formnumber'] ?>" />
            <input type="hidden" name="FUNCTION" id="FUNCTION" value="createfromsaved" />
            <input type="hidden" name="repnumber" id="repnumber" value="<?= $_REQUEST['repnumber'] ?>" />
            <input id="btn_save" type="submit" value="save" style="display:none" />
            <input type="hidden" id="btn_later" value="save" />
            <input type="hidden" name="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>

    <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 foreach (range(1, 6) as $file) { ?>
                    <div class="col-md-2 mb-4" style="position:relative">
                        <div class="col-12 col-md-12 text-center">
                            <div class="card">
                                <div class="card-header">Report Image #<?= $file ?></div>
                                <div id="crop<?= $file ?>" class="card-body">

                                    <div class="slim" data-ratio="free" data-did-remove="reportImageRemoved"
                                        data-force-type="jpg" data-label="Select Image"
                                        data-service="images/repimage_save.php" data-filter-sharpen="20"
                                        data-push="true" data-meta-userid="<?= $d[2] ?>"
                                        data-meta-imageid="<?= $d[2] ?>_<?= $file ?>" data-size="1024,1024"
                                        data-meta-tenant="<?= TENANT_URL ?>">
                                        <?php if (file_exists('images/report_images/' . $d[2] . '_' . $file . '.jpg')) { ?>
                                        <img src="images/report_images/<?= $d[2] ?>_<?= $file ?>.jpg?<?= rand() ?>"
                                            alt="Report Image #<?= $file ?>">
                                        <?php } ?>

                                        <input type="file" name="file" />
                                    </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 } ?>

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

function killcrop() {
    // Implementation for the killcrop function if needed
}

function reportImageRemoved(data) {
    console.log(data);
    var name = data.input.name;

    // Use fetch API for the POST request
    fetch('images/repimage_remove.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded' // Send data as form-urlencoded
            },
            body: new URLSearchParams({
                image: name
            })
        })
        .then(response => response.text()) // Handle the response if needed
        .then(data2 => {
            console.log('Image removal response:', data2);
            showResponse('success', 'Image removed successfully');
        })
        .catch(error => {
            console.error('Error:', error);
        });
}
// Get save Parameters
// 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");

    // Add a click event listener to the button
    btnSave.addEventListener("click", function(event) {
        event.preventDefault(); // Prevent the default form submission or button action
        const bodyEl = document.getElementById('imageCardBody-<?= $d[2] ?>');
        let hasImages = false;

        if (bodyEl) {
            const slots = bodyEl.querySelectorAll('.slim');
            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>

        `;

        // 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

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

        killModal('confirmBox');

        // 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.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] === "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
                });
        }
    }



    // Save data to the database and create the form
    $("#btn_later").click(function(event) {

        event.preventDefault();
        $('#FUNCTION').val('update_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) { //debug(result)
                    if ($.trim(result) == "update_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'] ?>'
                    }
                }
            });
        }
    });

    document.getElementById('navBox').innerHTML =
        '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=incomplete.php">Incomplete Reports</a> <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li> <li class="breadcrumb-item active">Continue: <?= $_REQUEST['repnumber'] ?></li>';
    // Footer controls
    const footerControls = document.getElementById('footerControls');
    footerControls.innerHTML =
        '<button class="actionButton btn btn-secondary me-4" onclick="triggerAction(\'btn_save\')">COMMIT REPORT</button> <button class="actionButton btn btn-warning" onclick="triggerAction(\'btn_later\')">Save</button>';
});
</script>
