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

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


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


?>



<div class="form_down" style='width: 97vw; background-color: white;'>
    <div class="search_form" style="width: 100%;
    border-radius: 1vw;
    padding: 0.5vw;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: center;
    background-color: white;
    align-content: flex-start;
    justify-content: center;
    overflow-x: scroll;">

        <?php echo $html->input_html_from_db("orders", "jc_number", "record_id = {$_GET['record_id']}", "jc_number", "jc_number", "", "inputs", "", "readonly"); ?>

        <?php echo $html->input_html_from_db("orders", "po_number", "record_id = {$_GET['record_id']}", "po_number", "po_number", "", "inputs", "", "readonly"); ?>

        <?php // echo $html->select_html_from_db("users", "record_id", "username", "", "user_id", "user_id", "inputs", "", "", "disabled"); ?>

        <?php // echo $html->select_from_db_add_current_selected_column("orders", 'user_id', "record_id = {$_GET['record_id']}", 'user_id'); ?>

        <?php echo $html->select_html_from_db("suppliers", "record_id", "name", "", "supplier_id", "supplier_id", "inputs", "width:50%;", "", "disabled"); ?>

        <?php echo $html->select_from_db_add_current_selected_column("orders", 'supplier_id', "record_id = {$_GET['record_id']}", 'supplier_id'); ?>
        <form action="stock_receive.php" method="post">
            <?php echo $html->input_html("", date("Y-m-d H:i", strtotime("+2 hours")), "date_ordered", "date_ordered", "hidden", "", "", "text", "readonly") ?>
    </div>


    <?php

    $index = 0;
    $items_res = $db->query("order_items", "SELECT * FROM order_items WHERE order_id = '{$_GET['record_id']}' AND stock_id != 0 AND stock_type = 0 ORDER BY record_id ASC");
    if ($items_res->num_rows > 0) {
        ?>

        <div class="search_form">

            <h1>Stock Items</h1>
        </div>
        <?php
        echo "<div class='row'>";
        echo $html->input_html("", "ITEM", "", "", 'inputs', "width: 30vw;");
        echo $html->input_html("", "ORDERED", "", "", 'inputs', "width: 20vw;");
        echo $html->input_html("", "RECEIVED", "", "", 'inputs', "width: 20vw;");

        echo "</div>";
        while ($items = $items_res->fetch_assoc()) {
            $amount_res = $db->query("order_trans", "SELECT * FROM order_trans WHERE order_id = {$_GET['record_id']} AND stock_id = {$items['stock_id']}");
            if ($amount_res->num_rows > 0) {
                $total = 0;
                while ($amount = $amount_res->fetch_assoc()) {
                    $total = $total + $amount['amount'];
                }
            } else {
                $total = 0;
            }
            if ($total != $items['quantity']) {
                echo "<div class='row'>";
                echo $html->input_html("", $items['stock_id'], "stock_id_$index", "stock_id_$index", "hidden");
                echo "<textarea id='name_$index' name='name_$index' class='inputs' style='width: 30vw;height: auto; overflow-y: hidden;' oninput='this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';' onfocus='this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';'>{$items['name']}</textarea>";
                // echo $html->input_html("", $items['name'], "name_$index", "name_$index", "inputs", "", "", "text", "readonly");
                echo $html->input_html("", $items['quantity'] - $total, "quantity_$index", "quantity_$index", "inputs", "width:20vw;", "", "text", "readonly");
                echo $html->input_html("", "", "actual_amount_$index", "actual_amount_$index", "inputs", "width:20vw;", "onchange = check($index)");
                echo $html->input_html("", $items['purchase_price_ex'], "price_$index", "price_$index", "hidden", "", "");
                echo "</div>";
            }
            $index++;
        }
    }
    ?>

    <?php

    $items_res = $db->query("order_items", "SELECT * FROM order_items WHERE order_id = '{$_GET['record_id']}' AND stock_id != 0 AND stock_type = 1 ORDER BY record_id ASC");
    if ($items_res->num_rows > 0) {

        ?>
        <div class="search_form">
            <h1>Non-Stock Items</h1>
        </div>

        <?php
        echo "<div class='row'>";
        echo $html->input_html("", "ITEM", "", "", 'inputs', "width: 30vw;");
        echo $html->input_html("", "ORDERED", "", "", 'inputs', "width: 20vw;");
        echo $html->input_html("", "RECEIVED", "", "", 'inputs', "width: 20vw;");
        echo $html->input_html("", "BARCODE", "", "", 'inputs', "width: 20vw;");

        echo "</div>";
        while ($items = $items_res->fetch_assoc()) {
            $amount_res = $db->query("order_trans", "SELECT * FROM order_trans WHERE order_id = {$_GET['record_id']} AND stock_id = {$items['stock_id']}");
            if ($amount_res->num_rows > 0) {
                $total = 0;
                while ($amount = $amount_res->fetch_assoc()) {
                    $total = $total + $amount['amount'];
                }
            } else {
                $total = 0;
            }
            if ($total != $items['quantity']) {
                echo "<div class='row'>";
                echo $html->input_html("", $items['stock_id'], "stock_id_$index", "stock_id_$index", "hidden");
                echo "<textarea id='name_$index' name='name_$index' class='inputs' style='width: 30vw;height: auto; overflow-y: hidden;' oninput='this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';' onfocus='this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';'>{$items['name']}</textarea>";
                // echo $html->input_html("", $items['name'], "name_$index", "name_$index", "inputs", "", "", "text", "readonly");
                echo $html->input_html("", $items['quantity'] - $total, "quantity_$index", "quantity_$index", "inputs", "width:20vw;", "", "text", "readonly");
                echo $html->input_html("", "", "actual_amount_$index", "actual_amount_$index", "inputs", "width:20vw;", "onchange = check($index)");
                echo $html->input_html("", "", "barcode_non_$index", "barcode_non_$index", "inputs", "width:20vw;", "onkeyup = check_blanks(this)");

                echo $html->input_html("", $items['purchase_price_ex'], "price_$index", "price_$index", "hidden", "", "");
                echo "</div>";
            }
            $index++;
        }
    }
    ?>
    <script>
        function check_blanks(input) {
            let value = input.value.replace(/\s/g, '');
            input.value = value;
        }
    </script>



    <?php

    $items_res = $db->query("order_items", "SELECT * FROM order_items WHERE order_id = '{$_GET['record_id']}' AND stock_id != 0 AND stock_type = 2 ORDER BY record_id ASC");
    if ($items_res->num_rows > 0) {
        ?>
        <div class="search_form">
            <h1>UNITS</h1>
        </div>
        <?php
        echo "<div class='row'>";
        echo $html->input_html("", "ITEM", "", "", 'inputs', "width: 15vw;");
        echo $html->input_html("", "ORDERED", "", "", 'inputs', "width: 15vw;");
        echo $html->input_html("", "RECEIVED", "", "", 'inputs', "width: 15vw;");
        echo $html->input_html("", "S/N", "", "", 'hidden', "width: 15vw;");

        echo "</div>";
        while ($items = $items_res->fetch_assoc()) {
            $amount_res = $db->query("order_trans", "SELECT * FROM order_trans WHERE order_id = {$_GET['record_id']} AND stock_id = {$items['stock_id']}");
            if ($amount_res->num_rows > 0) {
                $total = 0;
                while ($amount = $amount_res->fetch_assoc()) {
                    $total = $total + $amount['amount'];
                }
            } else {
                $total = 0;
            }
            if ($total != $items['quantity']) {

                echo "<div class='row'>";

                echo $html->input_html("", $items['stock_id'], "stock_id_$index", "stock_id_$index", "hidden");

                echo $html->input_html("", $items['record_id'], "order_item_id_$index", "order_item_id_$index", "hidden");

                echo "<textarea id='name_$index' name='name_$index' class='inputs' style='width: 30vw;height: auto; overflow-y: hidden;' oninput='this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';' onfocus='this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';'>{$items['name']}</textarea>";

                // echo $html->input_html("", $items['name'], "name_$index", "name_$index", "inputs", "", "", "text", "readonly");
    
                echo $html->input_html("", $items['quantity'] - $total, "quantity_$index", "quantity_$index", "inputs", "width: 15vw;", "", "text", "readonly");

                echo $html->input_html("", "", "actual_amount_$index", "actual_amount_$index", "inputs", "width: 15vw;", "onchange = 'check($index);create_popup_for_serial_numbers(this,\"serial_numbers_$index\",$index);'");

                echo $html->input_html("", $items['purchase_price_ex'], "price_$index", "price_$index", "hidden", "", "");

                echo $html->input_html("", "", "serial_numbers_$index", "serial_numbers_$index", 'hidden', "width: 15vw;", '', 'text', 'readonly');

                echo "</div>";
            }
            $index++;
        }
    }
    ?>




    <input type="text" name="order_id" id="order_id" hidden value="<?php echo $_GET['record_id']; ?>">
    <input type="text" name="counter" id="counter" hidden value="<?php echo $index; ?>">


    <?php

    echo $html->submit_btn('submit', 'RECEIVE', 'security_check(this)', 'select_button'); ?>
    </form>


    <div style="width: 100%;height: 100%;position: fixed;inset: 0px;background-color: rgba(0, 0, 0, 0.87);z-index: 44;display: none;justify-content: center;align-items: center;align-content: center;flex-direction: column;"
        id="popup_background">
        <div id="popups"
            style="z-index: 45; width: 85%;max-height: 80vh;height: auto;top: 2vh;overflow: auto;display: none;border-radius: 4vw;position: absolute;background-color: grey;padding: 2vw;text-align: center;flex-flow: column;align-content: center;align-items: center;">
            <h1>INPUT SERIAL NUMBERS</h1>
            <div id="popup_data">
            </div>
            <div>
                <input type="text" hidden id="index_to_clear_on_cancel">
                <button onclick="close_popup_with_data()" class="select_button"
                    style="width:50vw;margin-bottom: 2vh;">SAVE</button>
                <button onclick="close_popup()" class="submit_btn" style="width:50vw;">CLOSE</button>

            </div>
        </div>
    </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 security_check(submit_btn) {
            quantity = document.getElementById('quantity').value;
            actual_amount = document.getElementById('actual_amount').value;

            if (actual_amount > quantity) {
                console.log("actual_amount may not be bigger than the quantity");
            }
        }

        function check(ind) {
            event.preventDefault();
            actual_amount = document.getElementById('actual_amount_' + ind);
            quantity = document.getElementById('quantity_' + ind);

            if (actual_amount.value * 1 > quantity.value * 1) {
                alert("Receiving more than ordered");
                actual_amount.value = "";
                actual_amount.style.backgroundColor = "red";
                setTimeout(close_popup, 500);
            } else {
                actual_amount.style.backgroundColor = "green";
            }
            if (actual_amount.value * 1 == 0) {
                close_popup();
                setTimeout(close_popup, 500);
                actual_amount.style.backgroundColor = "white";
            }
            if (actual_amount.value * 1 < 0) {
                alert("Cant Be Negative Number, leave blank if no stock received");
                actual_amount.value = "";
                actual_amount.style.backgroundColor = "red";
                setTimeout(close_popup, 500);
            }
            if (isNaN(actual_amount.value)) {
                alert("Must input a number, leave blank if no stock received");
                actual_amount.value = "";
                actual_amount.style.backgroundColor = "red";
                setTimeout(close_popup, 500);
            }
        }

        function create_popup_for_serial_numbers(amount, input, index) {
            document.getElementById("index_to_clear_on_cancel").value = amount.id;
            document.getElementById("popups").style.display = "flex";
            document.getElementById("popup_background").style.display = "flex";

            console.log("selected");
            const page = `barcode_ajax.php?serial_number_id=styles=width: 20vw;&amount=${amount.value}`;
            const xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState === 4 && this.status === 200) {
                    document.getElementById("popup_data").innerHTML += this.responseText;
                    document.getElementById("popup_data").innerHTML += `<input type='text' class='inputs' hidden id='return_id' value='${input}'><br>`;
                    // console.log(index);
                    console.log(`barcode_ajax.php?&styles=width: 40vw;&amount=${amount.value}`);
                }
            };
            xhttp.open("GET", page, true);
            xhttp.send();
        }

        function close_popup() {
            document.getElementById(document.getElementById("index_to_clear_on_cancel").value).value = 0;
            document.getElementById(document.getElementById("index_to_clear_on_cancel").value).style.backgroundColor = "white";
            document.getElementById(document.getElementById("index_to_clear_on_cancel").value).style.color = "black";
            document.getElementById("popups").style.display = "none";
            document.getElementById("popup_background").style.display = "none";
            document.getElementById("popup_data").innerHTML = ""

        }

        function serial_barcode_check(input, inputs_index_1) {
            console.log(input.value);
            const popupDataDiv = document.getElementById("popup_data");
            const no_inputs = document.getElementById("no_inputs").value;
            var data = "";
            for (let i = 1; i < no_inputs; i++) {
                if (i != inputs_index_1) {
                    s_n = document.getElementById('s_n_' + i);
                    barcode = document.getElementById('barcode_' + i);
                    if (input.value == s_n.value) {
                        console.log(s_n.value);
                        s_n.style.backgroundColor = "green";
                        s_n.style.color = "white";
                        input.style.backgroundColor = "red";
                        input.style.color = "white";
                        input.value = "";
                        s_n.focus();
                        alert("Serial Number already exists");
                        return;
                    } else if (input.value == barcode.value) {
                        console.log(barcode.value);
                        barcode.style.backgroundColor = "green";
                        barcode.style.color = "white";
                        input.style.backgroundColor = "red";
                        input.style.color = "white";
                        input.value = "";
                        barcode.focus();
                        alert("Barcode already exists");
                        return;

                    } else {
                        s_n.style.backgroundColor = "white";
                        s_n.style.color = "black";
                        input.style.backgroundColor = "white";
                        input.style.color = "black";
                        barcode.style.backgroundColor = "white";
                        barcode.style.color = "black";
                    }
                }
            }
            if (input.id.includes('s_n')) {
                if (input.value == document.getElementById('barcode_' + inputs_index_1).value) {
                    input.style.backgroundColor = "green";
                    input.style.color = "white";
                    document.getElementById('barcode_' + inputs_index_1).style.backgroundColor = "red";
                    document.getElementById('barcode_' + inputs_index_1).style.color = "white";
                    input.value = "";
                    document.getElementById('barcode_' + inputs_index_1).focus();
                    alert("Serial Number already exists");
                    return;
                }
            }
            if (input.id.includes('barcode')) {
                if (input.value == document.getElementById('s_n_' + inputs_index_1).value) {
                    input.style.backgroundColor = "green";
                    input.style.color = "white";
                    document.getElementById('s_n_' + inputs_index_1).style.backgroundColor = "red";
                    document.getElementById('s_n_' + inputs_index_1).style.color = "white";
                    input.value = "";
                    document.getElementById('s_n_' + inputs_index_1).focus();
                    alert("Barcode already exists");
                    return;
                }
            }

        }

        function close_popup_with_data() {
            event.preventDefault();
            const popupDataDiv = document.getElementById("popup_data");
            const no_inputs = document.getElementById("no_inputs").value;
            var data = "";
            $amount_of_inputs_received = 0;
            for (let i = 1; i < no_inputs; i++) {
                const s_n = document.getElementById('s_n_' + i);
                const barcode = document.getElementById('barcode_' + i);
                // if (s_n.value != "" && barcode.value != "") {
                //     data += s_n.value + "~" + barcode.value + ",";
                // } else {
                //     alert("Please fill both values for each line");
                //     return;
                // }
                if (s_n.value == '' || barcode.value == '') {
                    if (barcode.value != '' && s_n.value == '') {
                        s_n.style.backgroundColor = "red";
                        alert("Please fill both values for each line");
                        s_n.focus();
                        return;
                    } else if (s_n.value != '' && barcode.value == '') {
                        barcode.style.backgroundColor = "red";
                        alert("Please fill both values for each line");
                        barcode.focus();
                        return;
                    } else {
                        s_n.remove();
                        barcode.remove();
                    }
                } else {
                    s_n.style.backgroundColor = "green";
                    barcode.style.backgroundColor = "green";
                    $amount_of_inputs_received++;
                    data += s_n.value + "~" + barcode.value + ",";
                }
            }
            document.getElementById(document.getElementById('return_id').value).value = data;
            document.getElementById(document.getElementById("index_to_clear_on_cancel").value).value = $amount_of_inputs_received;
            document.getElementById(document.getElementById("index_to_clear_on_cancel").value).style.color = "white";
            document.getElementById("popup_data").innerHTML = "";
            document.getElementById("popups").style.display = "none";
            document.getElementById("popup_background").style.display = "none";

        }
    </script>