<?php include "../../root.class.php";
$call_functions = new call_functions();
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();
// $html->check_user_type("ADMIN");
$stock_take_res = $db->query("stock_takes", "SELECT * FROM stock_takes WHERE record_id = {$_GET['record_id']}");
$stock_take_data = $stock_take_res->fetch_assoc();

$total_stock_value = 0;
$total_non_stock_value = 0;
$total_unit_value = 0;
$total_value = 0;
?>
<div style="position: sticky;
    display: flex
;
    top: 1px;
    background-color: grey;
    width: 100%;
    padding: 1vw;
    border-radius: 2vw;
    flex-direction: row;
    align-content: center;
    justify-content: center;
    align-items: center;">
    <button onclick="generate_excell()" class="select_button" style="z-index: 0;">Generate Excell</button>

    <input type="text" id="search_input" style="width:100vw;" class="inputs" placeholder="Search...">
    <button onclick="search()" class="select_button">Search</button>
    <script>
        function generate_excell() {
            window.location.href = "stock_take_excell.php?record_id=<?php echo $_GET['record_id']; ?>";
        }
        function search() {
            var search_input = document.getElementById("search_input").value;
            var inputs = document.querySelectorAll(".form_down .inputs");
            index = 0;
            inputs.forEach(input => {
                if (input.value.toUpperCase().includes(search_input.toUpperCase())) {
                    if (index == 0) {
                        input.focus();
                    }
                    input.style.backgroundColor = "white";
                    input.style.backgroundColor = "lightgrey";
                    index++;
                }

            });
        }
    </script>
</div>
<form class="form_down">

    <h1> STOCK TAKE CREATED ON : <?php echo $stock_take_data['date_created']; ?></h1>
    <h1> STOCK TAKE CREATED BY : <?php echo $call_functions->get_username($stock_take_data['user_id_created']); ?></h1>
    <h1> STOCK TAKE DONE ON : <?php echo $stock_take_data['date_done']; ?></h1>
    <h1> STOCK TAKE DONE BY : <?php echo $call_functions->get_username($stock_take_data['user_id_done']); ?></h1>
    <hr>
    <h1> STOCK TAKE RESULTS (STOCK) </h1>

    <?php
    $stock_res = $db->query("stock_take_stock", "SELECT * FROM stock_take_stock WHERE stock_take_id = {$_GET['record_id']}");
    $stock_index = 1;
    echo "<div class='row'>";


    echo $html->input_html("ITEM", "", '', '', 'inputs', 'font-size:1.5vw;');
    echo $html->input_html("PACKAGE SIZE", "", '', '', 'inputs', 'width:17vw;font-size:1.5vw;');
    echo $html->input_html("SYSTEM STOCK", "", '', '', 'inputs', 'width:17vw;font-size:1.5vw;');
    echo $html->input_html("COUNTED STOCK", "", '', '', 'inputs', 'width:17vw;font-size:1.5vw;');
    echo $html->input_html("STOCK VALUE", "", '', '', 'inputs', 'width:17vw;font-size:1.5vw;');

    echo "</div>";
    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'], '', '', 'inputs', 'width:15vw;');

        echo $html->input_html("AMOUNT IN STOCK", $stock['amount_in_stock'], "in_stock_amount_$stock_index", "in_stock_amount_$stock_index", 'inputs', 'width:15vw;', '', 'number', 'readonly');


        echo $html->input_html("AMOUNT COUNTED", $stock['amount_counted'], "stock_amount_$stock_index", "stock_amount_$stock_index", 'inputs', 'width:15vw;', 'onchange="price_adjust(\'' . $stock_index . '\')"', 'number', 'required');

        ?>
        <script>
            document.getElementById("stock_amount_<?php echo $stock_index; ?>").addEventListener("click", function () {
                var value = this.value;
                if (value == "0") {
                    this.value = value.replace("0", "");
                }
            });
        </script>


        <?php

        if ($stock['amount_in_stock'] * 1 != $stock['amount_counted'] * 1) {
            echo "<script>document.getElementById('stock_amount_$stock_index').style.backgroundColor = 'red';
            document.getElementById('stock_amount_$stock_index').style.color = 'white';
            </script>";
        } else {
            echo "<script>document.getElementById('stock_amount_$stock_index').style.backgroundColor = 'green';
            document.getElementById('stock_amount_$stock_index').style.color = 'white';
            </script>";
        }

        // get stock value 
        $stock_value_res = $db->query("stock", "SELECT * FROM `stock` WHERE record_id = $stock_id");
        $stock_value = $stock_value_res->fetch_assoc();
        $stck_value = is_numeric($stock['amount_counted']) && is_numeric($stock_value['cost_price']) ? $stock['amount_counted'] * $stock_value['cost_price'] : 0;

        if ($stock_value['stock_type'] == 0) {
            $total_stock_value += $stck_value;
        }
        if ($stock_value['stock_type'] == 1) {
            $total_non_stock_value += $stck_value;
        }
        if ($stock_value['stock_type'] == 2) {
            $total_unit_value += $stck_value;
        }
        $total_value += $stck_value;

        echo $html->input_html("Cost", $stck_value, "total_value_$stock_index", "total_value_$stock_index", 'inputs', 'width:15vw;', '', 'text', 'required');
        echo $html->input_html("Cost", $stock_value['cost_price'], "cost_price_$stock_index", "cost_price_$stock_index", 'inputs', 'width:15vw;', '', 'text', 'hidden');


        echo "</div>";
        $stock_index++;
    }
    ?>

    <label>TOTAL VALUE</label>
    <input type="number" class="inputs" value="R <?php echo number_format($total_value, 3); ?>" style="width:15vw;"
        id="total_stock_value" readonly>
    <label>TOTAL STOCK VALUE</label>
    <input type="number" class="inputs" value="R <?php echo number_format($total_stock_value, 3); ?>"
        style="width:15vw;" id="total_stock_value" readonly>
    <label>TOTAL NON STOCK VALUE</label>
    <input type="number" class="inputs" value="R <?php echo number_format($total_non_stock_value, 3); ?>"
        style="width:15vw;" id="total_stock_value" readonly>
    <label>TOTAL UNIT VALUE</label>
    <input type="number" class="inputs" value="R <?php echo number_format($total_unit_value, 3); ?>" style="width:15vw;"
        id="total_stock_value" readonly>

    <hr>
    <script>
        function select_non_stock(type, index) {
            if (type == 'no') {
                document.getElementById("non_stock_in_stock_" + index).value = '0';
                document.getElementById("select_button_yes_" + index).style.backgroundColor = 'grey';
                document.getElementById("select_button_no_" + index).style.backgroundColor = 'green';
            }
            if (type == 'yes') {
                document.getElementById("non_stock_in_stock_" + index).value = '1';
                document.getElementById("select_button_yes_" + index).style.backgroundColor = 'green';
                document.getElementById("select_button_no_" + index).style.backgroundColor = 'grey';
            }

        }

        function price_adjust(index) {
            var amount = document.getElementById("stock_amount_" + index).value;
            var cost = document.getElementById("cost_price_" + index).value;
            var total = parseFloat(amount * cost).toFixed(3);
            document.getElementById("total_value_" + index).value = "R " + total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
    </script>


    <?php

    if ($stock_take_data['disision'] == "APPROVED") {
        echo "<div class='search_form' style='font-size:3vw;'>APPROVED & ADJUSTED BY ";
        echo $call_functions->get_username($stock_take_data['user_id_assesed']);
        echo " ON {$stock_take_data['date_assesed']}</div>";
    } else {
        echo $html->submit_btn('save', 'SAVE', '');
        echo $html->submit_btn('add_stock', 'ADD STOCK', '');

        echo $html->submit_btn('submit', 'APPROVE & ADJUST', '');

    }
    ?>
</form>


<script>

    document.addEventListener("keydown", function (event) {
        if (event.keyCode === 13) {
            event.preventDefault();
        }
    });



    document.querySelector("#submit").addEventListener("click", (e) => {
        e.preventDefault();
        const formElement = document.querySelector(".form_down");
        let valid = true;
        const inputs = formElement.querySelectorAll("input");
        inputs.forEach(input => {
            if (input.id.startsWith("stock_amount_")) {
                if (input.value == "" || input.value < 0) {
                    input.style.background = "red";
                    if (!document.querySelector(".form_down input[style*='red']:focus")) {
                        input.focus();
                    }
                    valid = false;
                } else {
                    input.style.background = "green";
                }
            }
        });
        if (valid) {
            const http = new XMLHttpRequest();
            const formData = new FormData(formElement);
            http.addEventListener("load", () => {
                if (http.responseText == 1) {
                    formElement.reset();
                    // alert("STOCK TAKE SUBMITTED");
                    console.log(http.responseText);
                    window.location.href = "";
                } else {
                    console.log(http.responseText);

                }
            });
            http.open("POST", "stock_take_approve_ajax.php?stock_take_id=<?php echo $_GET['record_id']; ?>&save=0");
            http.send(formData);
        }
    });
    document.querySelector("#save").addEventListener("click", (e) => {
        e.preventDefault();
        const formElement = document.querySelector(".form_down");
        let valid = true;
        const inputs = formElement.querySelectorAll("input");
        inputs.forEach(input => {
            if (input.id.startsWith("stock_amount_")) {
                if (input.value == "" || input.value < 0) {
                    input.style.background = "red";
                    if (!document.querySelector(".form_down input[style*='red']:focus")) {
                        input.focus();
                    }
                    valid = false;
                } else {
                    input.style.background = "green";
                }
            }
        });
        if (valid) {
            const http = new XMLHttpRequest();
            const formData = new FormData(formElement);
            http.addEventListener("load", () => {
                if (http.responseText == 1) {
                    formElement.reset();
                    // alert("STOCK TAKE SUBMITTED");
                    console.log(http.responseText);
                    window.location.href = "";
                } else {
                    console.log(http.responseText);

                }
            });
            http.open("POST", "stock_take_approve_ajax.php?stock_take_id=<?php echo $_GET['record_id']; ?>&save=1");
            http.send(formData);
        }
    });
    document.querySelector("#add_stock").addEventListener("click", (e) => {
        e.preventDefault();
        const formElement = document.querySelector(".form_down");
        let valid = true;
        const inputs = formElement.querySelectorAll("input");
        inputs.forEach(input => {
            if (input.id.startsWith("stock_amount_")) {
                if (input.value == "" || input.value < 0) {
                    input.style.background = "red";
                    if (!document.querySelector(".form_down input[style*='red']:focus")) {
                        input.focus();
                    }
                    valid = false;
                } else {
                    input.style.background = "green";
                }
            }
        });
        if (valid) {
            const http = new XMLHttpRequest();
            const formData = new FormData(formElement);
            http.addEventListener("load", () => {
                if (http.responseText == 1) {
                    formElement.reset();
                    // alert("STOCK TAKE SUBMITTED");
                    console.log(http.responseText);
                    window.location.href = "add_manual_stock.php?stock_take_id=<?php echo $_GET['record_id']; ?>";
                } else {
                    console.log(http.responseText);

                }
            });
            http.open("POST", "stock_take_approve_ajax.php?stock_take_id=<?php echo $_GET['record_id']; ?>&save=1");
            http.send(formData);
        }
    });
</script>