<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();

$html->prevent_enter_script();
$db = new db_safeguard();
// $html->check_user_type("ADMIN");
?>
<div style="position: sticky;
    display: flex;
    top: 0px;
    font-size: 1.5em;
    background-color: grey;
    width: 100%;
    padding: 3vw;
    border-radius: 2vw;
    flex-direction: row;
    align-content: center;
    justify-content: center;
    align-items: center;">
    <input type="text" id="search_input" style="width:100vw; font-size: 1em;" class="inputs" placeholder="Search...">
    <button onclick="search()" class="select_button">Search</button>
    <script>
        function search() {
            var search_input = document.getElementById("search_input").value;
            var inputs = document.querySelectorAll(".form_down .inputs");
            index = 0;
            inputs.forEach(input => {
                input.style.backgroundColor = "white";
                if (input.value.toUpperCase().includes(search_input.toUpperCase())) {
                    if (index == 0) {
                        input.focus();
                    }
                    input.style.backgroundColor = "lightgrey";
                    index++;
                }

            });
        }
    </script>
</div>

<div class="form_down" style="font-size:0.8em;">
    <h1> STOCK TAKE </h1>
    <?php
    $stock_res = $db->query("stock_take_stock", "SELECT * FROM stock_take_stock WHERE stock_take_id = {$_GET['record_id']} ORDER BY record_id ASC");
    $stock_index = 1;
    while ($stock = $stock_res->fetch_assoc()) {
        $stock_id = $stock['item_id'];
        echo "<div class='row'>";
        echo $html->input_html("STOCK ID", $stock_id, "stock_id_$stock_index", "stock_id_$stock_index", "hidden");
        $stock_details_res = $db->query("stock", "SELECT * FROM `stock` WHERE record_id = $stock_id");
        $stock_details = $stock_details_res->fetch_assoc();

        echo "<textarea class='inputs' style='height:auto;' oninput='this.style.height = \"auto\"; this.style.height = (this.scrollHeight) + \"px\";'>{$stock_details['description']}</textarea>";

        // echo $html->input_html("PACKAGE SIZE", $stock_details['packaging_size']);
        if ($stock['amount_counted'] == Null) {
            $amount = '';
        } else {
            $amount = $stock['amount_counted'];
        }
        echo $html->input_html("AMOUNT", $amount, "stock_amount_$stock_index", "stock_amount_$stock_index", 'inputs', '', "onchange='save_input($stock_index)'", 'number', 'required');
        echo "</div>";

        $stock_index++;
    }
    ?>
    <hr>

    <?php echo $html->submit_btn('add_stock', 'ADD STOCK', ''); ?>
    <hr>
    <?php echo $html->submit_btn('submit', 'COMPLETE', '', 'submit_device'); ?>
</div>




<script>

    document.querySelector("#submit").addEventListener("click", (e) => {
        e.preventDefault();
        const containerElement = document.querySelector(".form_down");
        let valid = true;
        const inputs = containerElement.querySelectorAll("input");
        inputs.forEach(input => {
            if (input.id.startsWith("stock_amount_")) {
                if (input.value == "" || input.value < 0) {
                    input.style.background = "red";
                    input.style.color = "white";
                    if (!document.querySelector(".form_down input[style*='red']:focus")) {
                        input.focus();
                    }
                    valid = false;
                } else {
                    input.style.background = "green";
                    input.style.color = "white";
                }
            }
        });
        if (valid) {
            const http = new XMLHttpRequest();
            const formData = new FormData();
            inputs.forEach(input => formData.append(input.name, input.value));
            http.addEventListener("load", () => {
                if (http.responseText == 1) {
                    inputs.forEach(input => {
                        input.value = '';
                        input.style.background = '';
                        input.style.color = '';
                    });
                    alert("STOCK TAKE SUBMITTED");
                    window.location.href = "home.php";
                } else {
                    alert(http.responseText);
                }
            });
            http.open("POST", "stock_take_submit.php?stock_take_id=<?php echo $_GET['record_id']; ?>&save=0");
            http.send(formData);
        }
    });

    function save_input(index) {
        const http = new XMLHttpRequest();
        const formData = new FormData();
        amount = document.getElementById("stock_amount_" + index).value;
        if (amount <= -1) {
            amount = document.getElementById("stock_amount_" + index).style.backgroundColor = "red";
            amount = document.getElementById("stock_amount_" + index).style.color = "white";
            alert("CANT BE LESS THAN 0");
            return;
        }
        item_id = document.getElementById("stock_id_" + index).value;
        formData.append("item_id", item_id);
        formData.append("amount", amount);
        http.addEventListener("load", () => {
            if (http.responseText == 1) {
                // alert(http.responseText);
                amount = document.getElementById("stock_amount_" + index).style.backgroundColor = "green";
                amount = document.getElementById("stock_amount_" + index).style.color = "white";

                // formElement.reset();
                // alert("STOCK TAKE SUBMITTED");
                // window.location.href = "home.php";
            } else {
                alert(http.responseText);
                amount = document.getElementById("stock_amount_" + index).style.backgroundColor = "red";
                amount = document.getElementById("stock_amount_" + index).style.color = "white";
            }
        });
        http.open("POST", "stock_take_item_adjust_live.php?stock_take_id=<?php echo $_GET['record_id']; ?>&save=0");
        http.send(formData);
    }

    document.querySelector("#add_stock").addEventListener("click", (e) => {

        window.location.href = "add_manual_stock.php?stock_take_id=<?php echo $_GET['record_id']; ?>";

    });
</script>