<?php include "../../root.class.php";

$html = new html();
$db = new db_safeguard();
$html->add_styles_page();
$html->prevent_enter_script();
$barcode = new barcodeReader();
$serial_barcode = new serial_scanner();


// $html->check_user_type("ADMIN");

echo $_GET['record_id'];

$items_res = $db->query("order_items", "SELECT * FROM order_items WHERE order_id = '{$_GET['record_id']}'");

$results = $db->query("stock", "SELECT * FROM stock WHERE 1");

$datalist = "";
while ($result = $results->fetch_assoc()) {
    $datalist .= "<option value='" . $result['record_id'] . " | " . $result['description'] . "'></option>";
}

?>

<style>
    .form_down {
        display: flex;
        flex-wrap: wrap;
        align-content: space-around;
        justify-content: space-around;
        align-items: center;
        width: 95%;
        max-width: 1920px;
    }

    .inputs {
        font-size: 3vw;
        margin: 1vw;
        cursor: pointer;
        border: 3px solid grey;
        /* width: 80%; */
        background: white;
        color: grey;
        border-radius: 15px;
        padding: 2vw;
        max-height: 5vw;
    }

    .submit_btn {
        font-size: 3vw;
        /* margin: 1vw auto; */
        cursor: pointer;
        border: 3px solid white;
        background: grey;
        color: white;
        border-radius: 15px;
        padding: 3vw;
        /* width: 100%; */
        /* margin-bottom: 4vw; */
        text-align: center;
    }
</style>
<form action="dispatch.php" method="POST" style="width: 80%;">
    <datalist id="stock">
        <?php echo $datalist; ?>
    </datalist>
    <div class="form_down">
        <div class="search_form">
            <?php echo $html->input_html("JC NUMBER", "", "jc_number", "jc_number", "inputs", '', '', 'text', 'required') ?>
        </div>

        <?php $index = 0;
        $counter = 0;
        ?>

        <table id="order_table" style="font-size:2vw;width: 100%;">
            <tr>
                <td>
                    <div class='row border'>
                        <div class='column'>
                            <input type='text' class='inputs' readonly value='item : <?php echo $index; ?>' />
                            <div class='row'>
                                <input type="text" class="inputs" name='stock_description_<?php echo $counter; ?>'
                                    id="stock_description_<?php echo $index; ?>" list="stock"
                                    placeholder="SELECT STOCK ITEM" onchange="getstockAmount(this.value, 0)" />

                                <input type="text" class="inputs" name='amount_ind_0' id="amount_ind_0"
                                    onchange="check_values(this.value,0)" hidden PLACEHOL DER="AMOUNT" />

                                <input type="text" class="inputs" name='in_stock_0' id="in_stock_0" hidden
                                    PLACEHOLDER="in_stock" />

                            </div>
                        </div>
                    </div>
                </td>
            </tr>
            <tbody id="order_table_body">
            </tbody>
        </table>
        <input type="text" id="order_table_index" value="0" name="counter">
        <button type="button" class="submit_btn" onclick="add_row('order_table')">ADD STOCK ITEM</button>

        <!-- NON STOCK ITEMS -->

        <div class="form_down">
            <?php $index = 0;
            $counter = 0;
            ?>

            <table id="non_stock_table" style="font-size:2vw;width: 100%;">
                <tr>
                    <td>
                        <div class='row border'>
                            <div class='column'>
                                <input type='text' class='inputs' readonly value='item : <?php echo $index; ?>' />
                                <div class='row'>
                                    <input type="text" class="inputs"
                                        name='non_stock_description_<?php echo $counter; ?>'
                                        id="non_stock_description_<?php echo $index; ?>" placeholder="DESCRIPTION"
                                        hidden />

                                    <input type="text" class="inputs"
                                        name='non_stock_serial_number_<?php echo $counter; ?>'
                                        id="non_stock_serial_number_<?php echo $index; ?>"
                                        onchange="check_serial_number(this.value,0)" placeholder="SERIAL NUMBER" />

                                    <input type="text" class="inputs" hidden name='non_stock_id_0'
                                        id="non_stock_id_0" />


                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
                <tbody id="non_stock_table_body">
                </tbody>
            </table>
            <input type="text" id="non_stock_table_index" value="0" name="non_counter">
            <button type="button" class="submit_btn" onclick="add_row_non_stock('non_stock_table')">ADD NON STOCK
                ITEM</button>
            <?php
            echo $html->submit_btn('submit', 'DISPATCH', ''); ?>
</form>
</div>

<script>
    let allowExit = false;

    window.addEventListener('DOMContentLoaded', () => {
        // Allow leaving only if the #complete button is clicked
        const completeBtn = document.getElementById('complete');
        if (completeBtn) {
            completeBtn.addEventListener('click', () => {
                allowExit = true;
            });
        }

        window.addEventListener('beforeunload', function (e) {
            if (!allowExit) {
                e.preventDefault(); // Required for some browsers
                e.returnValue = ''; // Required for Chrome
            }
        });
    });
    function check_values(amount, index) {
        if (amount > document.getElementById("in_stock_" + index).value) {
            alert("Not Enough in stock");
            document.getElementById("amount_ind_" + index).value = 0;
            document.getElementById("amount_ind_" + index).style.backgroundColor = "red";
            document.getElementById("amount_ind_" + index).style.color = "white";
        } else {
            document.getElementById("amount_ind_" + index).style.backgroundColor = "green";
            document.getElementById("amount_ind_" + index).style.color = "white";

        }
    }
    function getstockAmount(stock_id, index) {
        stock_id = stock_id.split("|")[0];

        let xhr = new XMLHttpRequest();
        xhr.open("GET", "get_stock_amount.ajax.php?stock_id=" + stock_id, true);

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) { // Request is complete
                if (xhr.status === 200) { // Success
                    if (xhr.responseText == "0") {

                        alert("Stock selected has no stock on the system eg. Stock amount is 0");
                        document.getElementById("stock_description_" + index).value = "";

                    } else {

                        document.getElementById("in_stock_" + index).hidden = false;
                        document.getElementById("amount_ind_" + index).hidden = false;
                        document.getElementById("in_stock_" + index).value = xhr.responseText;

                    }
                } else { // Error
                    console.error("Error:", xhr.statusText);
                }
            }
        };

        xhr.send();

    }


    function add_row(table_id) {
        event.preventDefault();
        var table = document.getElementById(table_id);
        var counter = document.getElementById(table_id + "_index").value;

        var row = table.insertRow(-1); // Insert a new row at the end of the table
        counter++;

        row.innerHTML = `  
        <td>
        <div class='row border
        '>
        <div class='column'>
        <input type='text' class='inputs' readonly value='item : `+ counter + `' />
            <div class='row'>

            <input type="text" class="inputs" name='stock_description_` + counter + `' id="stock_description_` + counter + `" list="stock" onchange="getstockAmount(this.value, ` + counter + `)" />

            <input type="text" class="inputs" hidden  onchange="check_values(this.value,`+ counter + `)" name='amount_ind_` + counter + `'  id="amount_ind_` + counter + `" PLACEHOLDER="AMOUNT" />
                                    
            <input type="text" class="inputs" hidden name='in_stock_ `+ counter + `'  id="in_stock_` + counter + `" PLACEHOLDER="IN STOCK AMOUNT" />
        
            </div>
        </div>

        </td >
        `;
        document.getElementById(table_id + "_index").value = counter;
        document.getElementById('index').value = counter;
        // document.getElementById('index').value = parseInt(document.getElementById('index').value) + 1;
        document.getElementById('order_table').appendChild(row);

    }

    function add_row_non_stock(table_id) {
        event.preventDefault();
        var table = document.getElementById(table_id);
        var counter = document.getElementById(table_id + "_index").value;

        var row = table.insertRow(-1); // Insert a new row at the end of the table
        counter++;

        row.innerHTML = `  
        <td>
        <div class='row border
        '>
        <div class='column'>
        <input type='text' class='inputs' readonly value='item : `+ counter + `' />
            <div class='row'>

            <input type="text" PLACEHOLDER="DESCRIPTION" hidden class="inputs" name='non_stock_description_` + counter + `' id="non_stock_description_` + counter + `"/>

            <input type="text" class="inputs"
            name='non_stock_serial_number_` + counter + `'
            id="non_stock_serial_number_` + counter + `"
            onchange="check_serial_number(this.value,` + counter + `)" placeholder="SERIAL NUMBER" />

            <input type="text" class="inputs" name='non_stock_id_` + counter + `' id="non_stock_id_` + counter + `" hidden/>

        
            </div>
        </div>

        </td >
        `;
        document.getElementById(table_id + "_index").value = counter;
        // document.getElementById('index').value = parseInt(document.getElementById('index').value) + 1;
        document.getElementById(table_id).appendChild(row);

    }

    function check_serial_number(serial_number_id, index) {
        let url = "check_serial_number_ajax.php?serial_number=" + serial_number_id;

        let xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    console.log(xhr.responseText);
                    if (xhr.responseText != 0) {
                        document.getElementById("non_stock_description_" + index).hidden = false;
                        data = xhr.responseText.split("|");
                        document.getElementById("non_stock_id_" + index).value = data[1];
                        document.getElementById("non_stock_description_" + index).value = data[0];


                    } else {
                        alert("SERIAL NUMBER NOT RECOGNISED");
                    }

                } else {
                    return;
                }
            }
        };
        xhr.send();
    }

    function showPopup(message) {
        // Create popup container
        var popup = document.createElement('div');
        popup.style.position = 'fixed';
        popup.style.left = '50%';
        popup.style.top = '50%';
        popup.style.transform = 'translate(-50%, -50%)';
        popup.style.backgroundColor = 'white';
        popup.style.padding = '20px';
        popup.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.5)';
        popup.style.borderRadius = '2vw';
        popup.style.zIndex = '1000';

        // Create heading
        var heading = document.createElement('h2');
        heading.innerText = message;
        popup.appendChild(heading);

        // Create close button
        var closeButton = document.createElement('button');
        closeButton.innerText = 'Close';
        closeButton.onclick = function () {
            document.body.removeChild(popup);
        };
        popup.appendChild(closeButton);

        // Append popup to body
        document.body.appendChild(popup);
    }


</script>

</form>