<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$stock_data_res = $db->query("stock_control", "SELECT * FROM stock_control");

while ($stock_data = $stock_data_res->fetch_assoc()) {

    $stock_items = $stock_items . "<option value='" . $stock_data["record_id"] . "'>" . $stock_data["item_name"] . "</option>";
}

$stock_no_label = new label();
$stock_no_label->for("stock_no");
$stock_no_label->value("Stock No:");

$stock_no = new select();
$stock_no->class("inputs");
$stock_no->name("stock_no");
$stock_no->id("stock_no");
$stock_no->fill_from_db("stock_control", "stock_no", "stock_no");

$jobcard_no_label = new label();
$jobcard_no_label->for("jobcard_no_label");
$jobcard_no_label->value("Jobcard No:");

$jobcard_no = new select();
$jobcard_no->class("inputs");
$jobcard_no->name("jobcard_no");
$jobcard_no->id("jobcard_no");
$jobcard_no->fill_from_db("jobcards", "jc_no", "jc_no", "status = 0");

$stock_type_label = new label();
$stock_type_label->for("stock_type_label");
$stock_type_label->value("STOCK TYPE : ");

$stock_type = new select();
$stock_type->class("inputs");
$stock_type->name("stock_type");
$stock_type->id("stock_type");
$stock_type->fill_from_db("stock_type", "record_id", "name");
$stock_type->onchange("getStockTypeDetails()");

$stock_label = new label();
$stock_label->for("stock_label");
$stock_label->value("STOCK : ");

$date_booked_label = new label();
$date_booked_label->for("date_booked_label");
$date_booked_label->value("BOOKING DATE : ");

$date_booked = new input();
$date_booked->class("inputs");
$date_booked->name("date_booked");
$date_booked->id("date_booked");
$date_booked->type("datetime-local");

$user_id = new input();
$user_id->type("hidden");
$user_id->id("user_id");
$user_id->name("user_id");
$user_id->value($_SESSION["user_id"]);

$no_rows = new input();
$no_rows->type("hidden");
$no_rows->id("no_rows");
$no_rows->name("no_rows");
$no_rows->value(0);

$add_row_btn = new input();
$add_row_btn->value("ADD ROW");
$add_row_btn->id("add_row_btn");
$add_row_btn->onclick("add_row()");
$add_row_btn->type("button");
$add_row_btn->class("submit_btn");

$submit_btn = new button();
$submit_btn->value("SUBMIT");
$submit_btn->id("submit_btn");

?>

<form action="book_stock.ajax.php" method="post">
    <div class="form_down">
        <h1>ASSIGN STOCK</h1>
        <style>
            table {
                border-collapse: collapse;
                width: 90%;
                background-color: whitesmoke;
            }

            table,
            th,
            td {
                border: 2px solid black;
            }

            th {
                padding: 1vw;
            }
        </style>

        <?php
        $user_id->add();
        $stock_type_label->add();
        $stock_type->add();
        ?>

        <div id="normal_section" style="display: none; flex-direction: column; width: 100%; align-items: center;">
            <label for="pump_code" class="labels">PUMP CODE : </label>
            <input type="text" id="pump_code" name="pump_code" class="inputs">

            <?php
            $stock_label->add();
            ?>

            <script>
                function getStockTypeDetails() {
                    var stock_type = document.getElementById("stock_type").value;

                    if (stock_type === "Pump") {
                        document.getElementById("pump_section").style.display = "flex";
                        document.getElementById("normal_section").style.display = "flex";
                        document.getElementById("defualt_section").style.display = "none";
                    } else {
                        document.getElementById("pump_section").style.display = "none";
                        document.getElementById("normal_section").style.display = "flex";
                        document.getElementById("defualt_section").style.display = "flex";
                    }

                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "get_stock_type.ajax.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            // document.getElementById('supplier_order_no').value = xhr.responseText;
                            document.getElementById('table').querySelectorAll("tbody tr").forEach(tr => tr.remove());
                            //reset the index to 1
                            index = 0;
                            add_row();
                            console.log(xhr.responseText);
                        }
                    };

                    xhr.send("stock_type=" + stock_type);
                }

                function get_supplier_datalist() {
                    var stock_type = document.getElementById("stock_type").value;

                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "/app/supplier_orders/get_stock_type.ajax.php", true);

                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            document.getElementById("suppliers_datalist").innerHTML = xhr.responseText;
                        }
                    };

                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr.send("supplier_id=" + encodeURIComponent(supplier_id));
                }

            </script>

            <datalist id="stock_list"></datalist>

            <input type="text" name="stock" id="stock" list="stock_list" class="inputs">

            <?php
            $date_booked_label->add();
            $date_booked->add();
            $no_rows->add();
            $add_row_btn->add();

            ?>
        </div>


        <div id="pump_section" style="display: none; width: 100%;">
            <table style="width:80%" id="table">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Item Name</th>
                        <th>Quantity</th>
                        <th>User Assigned</th>
                        <th>Open Balance</th>
                        <th>Closing Balance</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td> <input id="type_1" name="type_1" style=""></td>
                        <td> <input id="item_name_1" name="item_name_1" style=""></td>
                        <td> <input id="quantity_1" name="quantity_1" style=""></td>
                        <td> <input id="user_assigned_1" name="user_assigned_1" style=""></td>
                        <td> <input id="open_balance_1" name="open_balance_1" style=""></td>
                        <td> <input id="closing_balance_1" name="closing_balance_1" style=""></td>
                        <td><button class="width_100" onclick="delete_row(this)">DELETE</button></td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" style="text-align: right; font-size: 0.9em;">TOTAL : </td>
                        <td><input id="total" name="total" readonly style="100%"></td>
                        <td><input id="total" name="total" readonly style="100%"></td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>

            <div id="pump_table" style="width:90%;"></div>
        </div>
        <div id="defualt_section" style="display: none; width: 100%;">
            <table style="width:80%" id="table">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Item Name</th>
                        <th>Quantity</th>
                        <th>User Assigned</th>
                        <th>Open Balance</th>
                        <th>Closing Balance</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td> <input id="type_1" name="type_1" style=""></td>
                        <td> <input id="item_name_1" name="item_name_1" style=""></td>
                        <td> <input id="quantity_1" name="quantity_1" style=""></td>
                        <td> <input id="user_assigned_1" name="user_assigned_1" style=""></td>
                        <td> <input id="open_balance_1" name="open_balance_1" style=""></td>
                        <td> <input id="closing_balance_1" name="closing_balance_1" style=""></td>
                        <td><button class="width_100" onclick="delete_row(this)">DELETE</button></td>
                    </tr>
                    <tr>
                        <td colspan="4" style="text-align: right; font-size: 0.9em;">TOTAL : </td>
                        <td><input id="total" name="total" readonly style="100%"></td>
                        <td><input id="total" name="total" readonly style="100%"></td>
                        <td></td>
                    </tr>
                </tbody>
            </table>

            <div id="stock_table" style="width:90%;"></div>
        </div>

        <br>
        <?php
        $submit_btn->add();
        ?>
    </div>
</form>

<script>

    var i = 1;

    function getItemData(input, index) {
        var i = index - 1;
        // console.log(input + i);

        var item_name = document.getElementById(input + i).value;
        if (!item_name) {
            // console.log("Element not found: " + input + "_" + i);
            return;
        }

        // Create an XMLHttpRequest object
        const xhttp = new XMLHttpRequest();
        // Define a callback function
        xhttp.onload = function () {
            // Here you can use the Data
            if (this.responseText != 1) {

                // console.log("Response received:", this.responseText);

                var data = this.responseText.split("~");
                // console.log("Split data:", data);
                if (data.length >= 3) {

                    stock_no = document.getElementById("stock_no_" + i)
                    description = document.getElementById("description_" + i)
                    current_quantity = document.getElementById("current_quantity_" + i)

                    stock_no.value = data[0];
                    description.value = data[1];
                    current_quantity.value = data[2];

                    // console.log("stock_no : ", stock_no);
                    // console.log("description : ", description);
                    // console.log("current_quantity : ", current_quantity);
                } else {
                    // console.log("Insufficient data parts. Expected 3, got:", data.length);

                    stock_no.value = "";
                    description.value = "";
                    current_quantity.value = "";
                }
            }
        }

        xhttp.open("GET", "get_stock.ajax.php?item_name=" + item_name);
        xhttp.send();
    }

    function add_row() {
        var table = document.createElement("table");
        table.innerHTML = `
        <tr>
            <td> <input id="type_${i}" name="type_${i}" style=""></td>
            <td> <input id="item_name_${i}" name="item_name_${i}" style="" onchange="getItemData('item_name_', ${i})"></td>
            <td> <input id="quantity_${i}" name="quantity_${i}" style="" onblur="maxQuantity(this, ${i})"></td>
            <td> <input id="user_assigned_${i}" name="user_assigned_${i}" style=""></td>
            <td> <input id="open_balance_${i}" name="open_balance_${i}" style=""></td>
            <td> <input id="closing_balance_${i}" name="closing_balance_${i}" style=""></td>
            <td><button class="width_100" onclick="delete_row(this)">DELETE</button></td>
        </tr>
        `;

        document.getElementById("no_rows").value = parseInt(document.getElementById("no_rows").value) + 1;

        i++;
    }

    function maxQuantity(input, index) {
        var j = index - 1;
        var max_quantity = document.getElementById("current_quantity_" + j).value;

        var quantity = document.getElementById("quantity_" + j).value;

        if (max_quantity < quantity) {
            alert("Quantity cannot be greater than current quantity");
        } else {
            return quantity;
        }
    }

    function delete_row(el) {
        var row = el.parentNode.parentNode;
        row.parentNode.removeChild(row);
        calculateTotals();
    }

    function calculateTotals() {

    }

</script>