<?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` 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` 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 showDetails(i) {
    document.getElementById('D' + i).style.display = 'block';
    var button = document.getElementById('B' + i);
    button.setAttribute('onclick', 'hideDetails(\'' + i + '\')');
    button.textContent = 'Hide item details';
}

function hideDetails(i) {
    document.getElementById('D' + i).style.display = 'none';
    var button = document.getElementById('B' + i);
    button.setAttribute('onclick', 'showDetails(\'' + i + '\')');
    button.textContent = 'Show item details';
}

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



function trafficLight600() {
    document.querySelectorAll('.iLight.dot.amber').forEach(el => {
        el.style.display = 'none';
    });
    var a = document.getElementById('repair_details').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 (a === "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 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');
        });
        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'));
        }
    }

    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>