<?php $data = urldecode($_REQUEST['data']);
$d = explode("|", $data);

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

        require_once('form_functions.php');
        $stmt = $GLOBALS['con']->prepare("SELECT `repnumber`,`reptype`,`insdate`,`result` FROM `reportitems` WHERE `itemnumber`=? ORDER BY ABS(repnumber) ASC LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $d[2]);
        $stmt->execute();
        $get = $stmt->get_result();
        $stmt->close();
        $rcount = mysqli_num_rows($get);
        if ($rcount < 1) {
?>
<div class="col-md-12 text-center">
    <a href="index.php?t=includes/master&p=formgen.php&mode=new&formnumber=<?= $rdata['reptype'] ?>&data=<?= $_REQUEST['data'] ?>"
        class="btn btn-info"> LOAD PREVIOUS </a>
</div>
<?php
        } else {
            $rget = mysqli_fetch_array($get);

            if ($_REQUEST['formnumber'] == "701") {
                $pstmt = $GLOBALS['con']->prepare("SELECT `id` FROM `lev_results_initial` WHERE `itemnumber`=? ") or die(mysqli_error($GLOBALS['con']));
                $pstmt->bind_param('i', $d[2]);
                $pstmt->execute();
                $getdata = $pstmt->get_result();
                $pstmt->close();
                $rcount = mysqli_num_rows($getdata);

                if ($rcount > 0) {
                    echo '
<div class="alert alert-warning"><h2 class="text-center">You have previously created an <b>initial report</b> for this item. Do you wish to reload and edit?</h2></div>
<div class="container text-center"><a href="index.php?t=includes/master&p=formgen.php&mode=reload&formnumber=' . $_REQUEST['formnumber'] . '&repnumber=' . $td['repnumber'] . '&data=' . $_REQUEST['data'] . '" class="btn btn-secondary"> RELOAD </a></div>
';
                    exit();
                }
            }
        ?>
<div class="col-12">
    <h2 class="text-center lead">Most recent report generated <strong><?= date('d-m-Y', $rget['insdate']) ?></strong>
    </h2>
    <div class="container text-center"><a
            href="index.php?t=includes/master&p=formgen.php&mode=new&formnumber=<?= $_REQUEST['formnumber'] ?>&repnumber=<?= $td['repnumber'] ?>&data=<?= $_REQUEST['data'] ?>"
            class="btn btn-info"> LOAD NEW
            REPORT</a></div>
</div>

<div class="row mt-5">
    <div class="col-12">
        <h3 class="text-center">Do you wish to load a previous report?</h3>
        <div class="row mt-3">
            <?php
                        $stmt = $GLOBALS['con']->prepare("SELECT `repitem`,`reptype`,`insdate`,`result` FROM `reportitems` WHERE `itemnumber`=? ORDER BY ABS(insdate) DESC LIMIT 6") or die(mysqli_error($GLOBALS['con']));
                        $stmt->bind_param('i', $d[2]);
                        $stmt->execute();
                        $tcr = $stmt->get_result();
                        $stmt->close();
                        while ($tdr = mysqli_fetch_array($tcr)) {

                            $stmt2 = $GLOBALS['con']->prepare("SELECT `repnumber`,`reptype`,`insdate`,`result` FROM `reportitems` WHERE `repitem`='" . $tdr['repitem'] . "' ") or die(mysqli_error($GLOBALS['con']));
                            $stmt2->execute();
                            $tc = $stmt2->get_result();
                            $stmt2->close();
                            $td = mysqli_fetch_array($tc);

                            if ($td['result'] == "DEFECTS") {
                                $col = "#F4AA09";
                                $title = "DEFECTS<br>" . $td['bdefect'];
                                $file = "file-exclamation";
                            }
                            if ($td['result'] == "URGENT") {
                                $col = "#e96152";
                                $title = "URGENT<br>" . $adefect[0];
                                $file = "file-excel";
                            }
                            if ($td['result'] == "PASS") {
                                $col = "#007E33";
                                $tag = "Pass";
                                $title = "Pass";
                                $file = "file-powerpoint";
                            }
                            if ($td['result'] == "OBS") {
                                $col = "#333333";
                                $tag = "Obs";
                                $title = "OBS<br>" . $td['obs'];
                                $file = "file-alt";
                            }
                            if ($td['result'] == "PNA") {
                                $col = "#cccccc";
                                $tag = "PNA";
                                $title = "PNA";
                                $file = "file";
                            }
                            if ($td['result'] == "") {
                                $col = "#9211E8";
                                $tag = "P2UD";
                                $title = "P2UD";
                                $file = "file";
                            }
                        ?>

            <div class="col-6 col-md-3 d-flex">
                <div class="card">
                    <div class="card-body text-center">
                        <i style="color:<?= $col ?>" class="fad fa-<?= $file ?> fa-2x"
                            aria-hidden="true"></i><br><?= $title ?>
                        <p class="text-center mb-n3">
                            <strong><?= getReportDesc($td['reptype'], 'desc') ?></strong><br><?= date('d-m-Y', $td['insdate']) ?>
                        </p>
                    </div>
                    <div class="card-footer">
                        <a href="index.php?t=includes/master&p=formgen.php&mode=reuse&formnumber=<?= $_REQUEST['formnumber'] ?>&repnumber=<?= $td['repnumber'] ?>&data=<?= $_REQUEST['data'] ?>"
                            class="btn btn-info btn-block">Load</a>
                    </div>
                </div>
            </div>
            <?php } ?>
        </div>
    </div>
</div>
<script>
$('#popupBox .modal-header').html('<a href="javascript:void(0)" class="sa">Report Selection</a>');
</script>
<?php
        }
        exit();
        break;

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

    case "continue":
        require(ROOT_URL . '/includes/formgen/form_continue.php');
        break;

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

    case "reload":
        require(ROOT_URL . '/includes/formgen/form_reload.php');
        break;

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

    case "reuse":
        require(ROOT_URL . '/includes/formgen/form_reuse.php');
        break;

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

    case "new":


        require(ROOT_URL . '/includes/formgen/form_new.php');

        break;
} ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const nextDate = document.getElementById('nextDate');
    const insdate = document.getElementById('insdate');

});

document.querySelectorAll('.btnRemove').forEach(button => {
    button.addEventListener('click', function() {
        var image = this.getAttribute("data-target");
        var src = this.getAttribute("data-src");
        fetch(`${ROOT_URL}/functions/image_remove.php`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    'afl': image
                })
            })
            .then(response => response.text())
            .then(data => {
                if (data.trim() == "done") {
                    document.querySelector('#' + src + '-view img').src =
                        'images/company/noimage.png';
                    this.style.display = 'none';
                    showResponse('success', 'Image removed Successfully');
                } else {
                    showResponse('danger', 'There was a problem, please try again');
                }
            });
    });
});

function setBox() {
    document.getElementById('overlay').style.display = 'block';
}

function getItemDetailsShell() {
    return document.querySelector('#popupBox.modal.show .form-details-shell') ||
        document.querySelector('.modal .form-details-shell') ||
        document.querySelector('.form-details-shell');
}

function removeClosedItemDetailsModal() {
    const modal = document.getElementById('popupBox');
    if (modal && !modal.classList.contains('show') && modal.querySelector('.form-details-shell')) {
        modal.remove();
        document.querySelectorAll('.modal-backdrop').forEach(backdrop => {
            if (!document.querySelector('.modal.show')) {
                backdrop.remove();
            }
        });
        if (!document.querySelector('.modal.show')) {
            document.body.classList.remove('modal-open');
            document.body.style.removeProperty('overflow');
            document.body.style.removeProperty('padding-right');
        }
    }
}

function loadItemDetailsContent(itemNumber, targetElement) {
    if (!targetElement) {
        removeClosedItemDetailsModal();
    }

    const target = targetElement || document.querySelector('#popupBox.modal.show .form-details-shell');
    const url = ROOT_URL + '/forms/elements/form_details.php?dataLoad=' + encodeURIComponent(itemNumber) + '&tenant=' + TENANT_URL;

    return fetch(url)
        .then(r => r.text())
        .then(html => {
            if (target) {
                target.outerHTML = html;
                return;
            }

            loadModalContent(
                html,
                "popupBox",
                "modal-xl",
                1060,
                "true",
                "Item Details"
            );
            setTimeout(addItemDetailsModalClose, 150);
        });
}

function addItemDetailsModalClose() {
    const modal = document.getElementById('popupBox');
    if (!modal) return;

    const headerActions = modal.querySelector('.modal-header .text-end');
    if (!headerActions || document.getElementById('popupBox-closeBtn')) return;

    const closeButton = document.createElement('button');
    closeButton.type = 'button';
    closeButton.id = 'popupBox-closeBtn';
    closeButton.className = 'btn btn-link p-0 ms-3 item-details-modal-close';
    closeButton.setAttribute('aria-label', 'Close item details');
    closeButton.setAttribute('title', 'Close');
    closeButton.innerHTML = '<i class="fad fa-times fa-2x"></i>';
    closeButton.addEventListener('click', function() {
        killModal('popupBox');
    });

    headerActions.appendChild(closeButton);
}

function showDetails(i) {
    loadItemDetailsContent(i);
}

function hideDetails(i) {
    killModal('popupBox');
}

function loadItemDetailsEdit(itemNumber) {
    const targetElement = getItemDetailsShell();
    const url = ROOT_URL + '/forms/elements/form_details_edit.php?itemnumber=' + encodeURIComponent(itemNumber) + '&tenant=' + TENANT_URL;

    fetch(url)
        .then(r => r.text())
        .then(html => {
            if (targetElement) {
                targetElement.innerHTML = html;
            }
        });
}

function cancelEdit(itemNumber) {
    const targetElement = getItemDetailsShell();
    if (targetElement) {
        loadItemDetailsContent(itemNumber, targetElement);
    }
}

function viewPlantResource(file) {
    if (!file) return;

    const ext = file.split('.').pop().toLowerCase();
    const fileUrl = `/${TENANT_URL}/resources/plantFiles/${encodeURIComponent(file)}`;

    let html = '';

    if (ext === 'pdf') {
        html = `<iframe src="${fileUrl}#toolbar=0&navpanes=0&scrollbar=0"
        style="width:100%;height:75vh;border:0"></iframe>`;
    } else {
        html = `
            <div class="text-center p-4">
                <p class="mb-3"><strong>Attached document:</strong><br>${file}</p>
                <a class="btn btn-outline-secondary"
                   href="${fileUrl}"
                   download>
                    <i class="fad fa-download"></i> Download document
                </a>
            </div>
        `;
    }

    loadModalContent(
        html,
        "popupBox",
        "modal-lg",
        1060,
        "true",
        "Plant Resource"
    );
}

document.addEventListener('submit', function(event) {
    const form = event.target;
    if (!form || form.id !== 'itemEditForm') {
        return;
    }

    event.preventDefault();
    const formData = new FormData(form);
    const itemNumber = formData.get('itemnumber');

    fetch(`${ROOT_URL}/includes/master/form_functions.php`, {
            method: 'POST',
            body: formData
        })
        .then(r => r.text())
        .then(result => {
            if (result.trim() === "success") {
                showResponse('success', 'Your changes have been saved successfully');
                cancelEdit(itemNumber);
            } else {
                showResponse('danger', 'Your changes have not been saved successfully ' + result);
            }
        });
});

const formnumber = "<?= $_REQUEST['formnumber'] ?>";



function trafficLight600() {
document.querySelectorAll('.iLight.dot.amber').forEach(el => {
    el.style.display = 'none';
});

// Trim whitespace, lower-case, and strip any trailing full stop
var a = document.getElementById('repair_details').value.toLowerCase().trim().replace(/\.$/, '');

 document.querySelectorAll('.iLight').forEach(el => {
            el.classList.remove('lit');
        });
        document.querySelectorAll('#mainNav, #footerBox, #InfoBox').forEach(el => {
            el.classList.remove('litRed', 'litAmber', 'litGreen', 'litBlack', 'libRed', 'libAmber',
                'libGreen', 'libBlack');
        });

if (a !== "none") {
     document.getElementById('mainNav').classList.add('litRed');
            document.getElementById('footerBox').classList.add('libRed');
            document.querySelector('.dot.red').classList.add('lit');
            document.getElementById('result').value = 'URGENT';
            document.getElementById('result').dispatchEvent(new Event('change'));
} else {
    document.getElementById('mainNav').classList.add('litGreen');
    document.getElementById('footerBox').classList.add('libGreen');
    document.querySelector('.dot.green').classList.add('lit');
    document.getElementById('result').value = 'PASS';
    document.getElementById('result').dispatchEvent(new Event('change'));
}
}

function trafficLight800() {
    var a = document.getElementById('adefect_1').value.toLowerCase().trim();
    var b = document.getElementById('bdefect').value.toLowerCase().trim();
    var c = document.getElementById('obs').value.toLowerCase().trim();
    document.querySelectorAll('.iLight').forEach(el => {
        el.classList.remove('lit');
    });
    document.querySelectorAll('#mainNav, #footerBox, #InfoBox').forEach(el => {
        el.classList.remove('litRed', 'litAmber', 'litGreen', 'litBlack');
    });
    if (a !== "none") {
        document.getElementById('mainNav').classList.add('litRed');
        document.getElementById('footerBox').classList.add('libRed');
        document.querySelector('.dot.red').classList.add('lit');
        document.getElementById('result').value = 'URGENT';
        document.getElementById('result').dispatchEvent(new Event('change'));
    }
    if (b !== "none" && a === "none") {
        document.getElementById('mainNav').classList.add('litAmber');
        document.getElementById('footerBox').classList.add('libAmber');
        document.querySelector('.dot.amber').classList.add('lit');
        document.getElementById('result').value = 'DEFECTS';
        document.getElementById('result').dispatchEvent(new Event('change'));
    }
    if (c !== "none" && a === "none" && b === "none") {
        document.getElementById('mainNav').classList.add('litBlack');
        document.getElementById('footerBox').classList.add('libBlack');
        document.querySelector('.dot.green').classList.add('lit');
        document.getElementById('result').value = 'OBS';
        document.getElementById('result').dispatchEvent(new Event('change'));
    }
    if (c === "none" && a === "none" && b === "none") {
        document.getElementById('mainNav').classList.add('litGreen');
        document.getElementById('footerBox').classList.add('libGreen');
        document.querySelector('.dot.green').classList.add('lit');
        document.getElementById('result').value = 'PASS';
        document.getElementById('result').dispatchEvent(new Event('change'));
    }
}

function trafficLight802() {
    document.querySelectorAll('.iLight.dot.amber').forEach(el => {
        el.style.display = 'none';
    });
    var a = document.getElementById('repair_1').value.toLowerCase().trim();
    var b = document.getElementById('repair_2').value.toLowerCase().trim();
    document.querySelectorAll('.iLight').forEach(el => {
        el.classList.remove('lit');
    });
    document.querySelectorAll('#mainNav, #footerBox, #InfoBox').forEach(el => {
        el.classList.remove('litRed', 'litAmber', 'litGreen', 'litBlack');
    });
    if (a !== "none" || b !== "none") {
        document.getElementById('mainNav').classList.add('litRed');
        document.getElementById('footerBox').classList.add('libRed');
        document.querySelector('.dot.red').classList.add('lit');
        document.getElementById('result').value = 'URGENT';
        document.getElementById('result').dispatchEvent(new Event('change'));
    }
    if (a === "none" && b === "none") {
        document.getElementById('mainNav').classList.add('litGreen');
        document.getElementById('footerBox').classList.add('libGreen');
        document.querySelector('.dot.green').classList.add('lit');
        document.getElementById('result').value = 'PASS';
        document.getElementById('result').dispatchEvent(new Event('change'));
    }
}

document.addEventListener('DOMContentLoaded', (event) => {
    if (['500', '502', '504', '506', '507', '508', '507', '5001', '5002', '5003'].includes(formnumber)) {
        document.getElementById('adefect').addEventListener('keyup', trafficLight);
        document.getElementById('bdefect').addEventListener('keyup', trafficLight);
        document.getElementById('obs').addEventListener('keyup', trafficLight);
        trafficLight();
    }

    if (['601', '602'].includes(formnumber)) {
        document.getElementById('repair_details').addEventListener('keyup', trafficLight600);
        trafficLight600();
    }

    if (['101', '503', '701', '700'].includes(formnumber)) {
        document.querySelectorAll('.iLight.dot.red, .iLight.dot.amber, .iLight.dot.green').forEach(el => {
            el.style.display = 'none';
        });
    }

    if (['800', '801'].includes(formnumber)) {
        document.getElementById('adefect_1').addEventListener('keyup', trafficLight800);
        document.getElementById('bdefect').addEventListener('keyup', trafficLight800);
        document.getElementById('obs').addEventListener('keyup', trafficLight800);
        trafficLight800();
    }

    if (formnumber == '802') {
        document.getElementById('repair_1').addEventListener('keyup', trafficLight802);
        document.getElementById('repair_2').addEventListener('keyup', trafficLight802);
        trafficLight802();
    }

    function trafficLight() {

        var a = document.getElementById('adefect').value.toLowerCase().trim();
        var b = document.getElementById('bdefect').value.toLowerCase().trim();
        var c = document.getElementById('obs').value.toLowerCase().trim();
        document.querySelectorAll('.iLight').forEach(el => {
            el.classList.remove('lit');
        });
        document.querySelectorAll('#mainNav, #footerBox, #InfoBox').forEach(el => {
            el.classList.remove('litRed', 'litAmber', 'litGreen', 'litBlack', 'libRed', 'libAmber',
                'libGreen', 'libBlack');
        });
        const isNone = (val) => /^none\.?$/i.test(val);

        if (!isNone(a)) {
            document.getElementById('mainNav').classList.add('litRed');
            document.getElementById('footerBox').classList.add('libRed');
            document.querySelector('.dot.red').classList.add('lit');
            document.getElementById('result').value = 'URGENT';
            document.getElementById('result').dispatchEvent(new Event('change'));
        } else if (!isNone(b)) {
            document.getElementById('mainNav').classList.add('litAmber');
            document.getElementById('footerBox').classList.add('libAmber');
            document.querySelector('.dot.amber').classList.add('lit');
            document.getElementById('result').value = 'DEFECTS';
            document.getElementById('result').dispatchEvent(new Event('change'));
        } else if (!isNone(c)) {
            document.getElementById('mainNav').classList.add('litBlack');
            document.getElementById('footerBox').classList.add('libBlack');
            document.querySelector('.dot.green').classList.add('lit');
            document.getElementById('result').value = 'OBS';
            document.getElementById('result').dispatchEvent(new Event('change'));
        } else {
            document.getElementById('mainNav').classList.add('litGreen');
            document.getElementById('footerBox').classList.add('libGreen');
            document.querySelector('.dot.green').classList.add('lit');
            document.getElementById('result').value = 'PASS';
            document.getElementById('result').dispatchEvent(new Event('change'));
        }
    }

    document.getElementById('result').addEventListener('change', function() {
        document.querySelectorAll('.iLight').forEach(el => {
            el.classList.remove('lit');
        });
        document.querySelectorAll('#mainNav, #footerBox, #InfoBox').forEach(el => {
            el.classList.remove('litRed', 'litAmber', 'litGreen', 'litBlack');
        });
        var selected = this.value;
        if (selected == "URGENT") {
            document.getElementById('mainNav').classList.add('litRed');
            document.getElementById('footerBox').classList.add('libRed');
            document.querySelector('.dot.red').classList.add('lit');
        }
        if (selected == "DEFECTS") {
            document.getElementById('mainNav').classList.add('litAmber');
            document.getElementById('footerBox').classList.add('libAmber');
            document.querySelector('.dot.amber').classList.add('lit');
        }
        if (selected == "PASS") {
            document.getElementById('mainNav').classList.add('litGreen');
            document.getElementById('footerBox').classList.add('libGreen');
            document.querySelector('.dot.green').classList.add('lit');
        }
        if (selected == "PNA" || selected == "OBS") {
            document.getElementById('mainNav').classList.add('litBlack');
            document.getElementById('footerBox').classList.add('libBlack');
        }
    });
});
</script>
