<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$stock_data_res = $db->query("stock", "SELECT * FROM stock");

while ($stock_data = $stock_data_res->fetch_assoc()) {

    $stock_items = $stock_items . "<option value='" . $stock_data["record_id"] . "'>" . $stock_data["item_name"] . "</option>";
}

$date_booked_label = new label();
$date_booked_label->for("date_booked_label");
$date_booked_label->value("BOOKING DATE : ");
$date_booked_label->addAttribute("style", "font-size: 1.5em; width: 30%;");

$date_booked = new input();
$date_booked->class("inputs");
$date_booked->name("date_booked");
$date_booked->id("date_booked");
$date_booked->type("datetime-local");
$date_booked->style("font-size: 1.5em; width: 80%; margin: 0.5vw auto;");

$user_id = new input();
$user_id->type("hidden");
$user_id->id("user_id");
$user_id->name("user_id");
$user_id->value($_SESSION["user_id"]);

$submit_btn = new button();
$submit_btn->value("SUBMIT");
$submit_btn->id("submit_btn");

$jobcard_data_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE status = 0");

$jobcard_datalist = "";
while ($jobcard = $jobcard_data_res->fetch_assoc()) {
    $jobcard_datalist .= "<option value='" . $jobcard["jc_no"] . "'>{$jobcard["jc_no"]} ~ {$jobcard["address"]}</option>";
}

$code_data_res = $db->query("stock", "SELECT * FROM stock WHERE stock_type_id = '3'");

$code_list = "";
while ($code = $code_data_res->fetch_assoc()) {
    $code_list .= "<option value='" . $code["pump_code"] . "'>{$code["item_name"]} ~ {$code["pump_code"]}</option>";
}

?>

<datalist id="jobcard_list">
    <?php echo $jobcard_datalist; ?>
</datalist>

<datalist id="pump_code_list">
    <?php echo $code_list; ?>
</datalist>

<form action="book_stock.ajax.php" method="post" onsubmit="return check_submit()">
    <div class="form_down">
        <h1>ASSIGN STOCK</h1>
        <style>
            table {
                border-collapse: collapse;
                width: 80%;
                background: #ffffff;
                font-size: 1rem;
                border: 2px solid black;
            }

            th,
            td {
                border: 1px solid #e5e7eb;
                padding: 0.1vw;
                text-align: left;

            }

            th {
                background: #1e3a8a;
                color: #ffffff;
                font-weight: 700;
                padding: 0.1vw;

            }

            .inputs {
                border: 1px solid #cbd5e1;
                border-radius: 8px;
                padding: 10px 5px;
                font-size: 0.9rem;
                background: #ffffff;
                color: #0f172a;
                margin: auto;
            }

            .inputs:focus {
                outline: none;
                border-color: #2563eb;
                box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15);
            }

            .delete_btn {
                width: 100%;
                padding: 12px;
                border-radius: 10px;
                border: none;
                background: linear-gradient(135deg, #f97316, #fb923c);
                color: #ffffff;
                font-weight: 700;
                letter-spacing: 0.04em;
                cursor: pointer;
                transition: transform 0.15s ease, box-shadow 0.15s ease;
            }

            .delete_btn:hover {
                background: linear-gradient(135deg, #224396, #153b96);
            }
        </style>

        <?php
        $user_id->add();

        $teams_list_res = $db->query("teams", "SELECT * FROM teams");
        $teams_list = "";

        while ($teams = $teams_list_res->fetch_assoc()) {
            $teams_list .= "<option value='{$teams['record_id']}'>{$teams['name']}</option>";
        }

        $order_no_data = $db->query("book_stock", "SELECT COUNT(*) as total FROM book_stock");
        $row = $order_no_data->fetch_assoc();

        $order_num = $row['total'] + 1;

        $order = "SO_" . $order_num;
        ?>

        <br>
        <div id="defualt_section" style="display: flex; flex-direction: column; width: 100%; align-items: center;">

            <div style="display: flex; flex-direction: row; width: 100%;">
                <label for="order_no_label" class="labels" style="font-size: 1.5em; width: 30%;">ORDER NO : </label>
                <input type="text" id="order_no" name="order_no" class="inputs" value="<?= $order; ?>" readonly
                    style="font-size: 1.5em; width: 80%; margin: 0.5vw auto;">
            </div>

            <div style="display: flex; flex-direction: row; width: 100%;">
                <?php
                $date_booked_label->add();
                $date_booked->add();
                ?>
            </div>

            <div style="display: flex; flex-direction: row; width: 100%;">
                <label for="pump_code" class="labels" style="font-size: 1.5em; width: 30%;">CODE : </label>
                <input type="text" id="pump_code" name="pump_code" class="inputs" list="pump_code_list"
                    style="font-size: 1.5em; width: 80%; margin: 0.5vw auto;">
            </div>

            <div style="display: flex; flex-direction: row; width: 100%;">
                <label for="jobcard_label" class="labels" style="font-size: 1.5em; width: 30%;">TEAM ASSIGNED : </label>
                <select id="team_assigned" name="team_assigned"
                    style="width: 80%; margin: 0.5vw auto; font-size: 1.5em;" class="inputs">
                    <option value=""></option>
                    <?php
                    echo $teams_list;
                    ?>
                </select>
            </div>

            <input type="text" id="no_rows" name="no_rows" value="1" hidden>

            <?php
            $stock_type_list_res = $db->query("stock_types", "SELECT * FROM stock_types");
            $stock_type_list = "";

            while ($stock_type = $stock_type_list_res->fetch_assoc()) {
                $stock_type_list .= "<option value='{$stock_type['record_id']}'>{$stock_type['name']}</option>";
            }

            ?>

            <br>
            <table style="width:95%;" id="table_defualt">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Item Name</th>
                        <th>Amount</th>
                        <th>Registaration No.</th>
                        <th>Open Balance</th>
                        <th>Closing Balance</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            <select id="type_1" name="type_1" style="width: 100%; margin: 0vw;" class="inputs"
                                onchange="getStockTypeDetails(1); clear_item(this, 1);">
                                <option value=""></option>
                                <?php
                                echo $stock_type_list;
                                ?>
                            </select>
                            <input type="text" id="stock_no_1" name="stock_no_1" hidden class="inputs">
                        </td>
                        <td>
                            <input id="item_name_1" name="item_name_1" list="stock_list_1"
                                style="width: 100%; margin: 0vw;" class="inputs" onchange="getQuantity(1)">
                            <datalist id="stock_list_1"></datalist>
                        </td>
                        <td>
                            <input type="number" id="quantity_1" name="quantity_1" style="width: 100%; margin: 0vw;"
                                class="inputs" onchange="maxQuantity(1)">
                        </td>
                        <td>
                            <input id="registration_no_1" name="registration_no_1" style="width: 100%; margin: 0vw;"
                                class="inputs">
                        </td>
                        <td>
                            <input id="open_balance_1" name="open_balance_1" style="width: 100%; margin: 0vw;"
                                class="inputs" onchange="calculateOpenTotals()">
                        </td>
                        <td>
                            <input id="close_balance_1" name="close_balance_1" style="width: 100%; margin: 0vw;"
                                class="inputs" onchange="calculateCloseTotals();">
                        </td>
                        <td>
                            <button type="button" onclick="delete_row(this)" class="delete_btn">DELETE</button>
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" style="text-align: right; font-size: 0.9em; font-weight: bold;">TOTAL : </td>
                        <td>
                            <input id="open_row_balance_total" name="open_row_balance_total"
                                style="width: 100%; margin: 0vw;" class="inputs" readonly>
                        </td>
                        <td>
                            <input id="close_row_balance_total" name="close_row_balance_total"
                                style="width: 100%; margin: 0vw;" class="inputs" readonly>
                        </td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>

            <input type="button" value="ADD ROW" onclick="add_row()" class="submit_btn">
        </div>

        <br>

        <?php
        $submit_btn->add();
        ?>
    </div>
</form>

<script>

    let rowIndex = 1;

    function getStockTypeDetails(i) {

        const stock_type = document.getElementById(`type_${i}`).value;
        const datalist = document.getElementById(`stock_list_${i}`);

        if (!datalist) {
            console.error("Missing datalist: stock_list_" + i);
            return;
        }

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "get_stock_type.ajax.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.onload = function () {

            console.log(xhr.responseText);
            datalist.innerHTML = xhr.responseText;

        };

        xhr.send("stock_type=" + stock_type);
    }

    function getQuantity(i) {

        const item_name = document.getElementById(`item_name_${i}`).value;
        const open_balance = document.getElementById(`open_balance_${i}`);
        const stock_no = document.getElementById(`stock_no_${i}`);

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "get_stock.ajax.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.onload = function () {
            if (xhr.status === 200 && xhr.responseText !== "") {

                console.log(xhr.responseText);
                // Expected format: quantity|cost
                const data = xhr.responseText.split("|");

                open_balance.value = data[0] ?? "";
                stock_no.value = data[2] ?? "";

                calculateOpenTotals();
                calculateCloseTotals();
            }
        };

        xhr.send("item_name=" + encodeURIComponent(item_name));
    }

    function maxQuantity(i) {
        const open_balance = parseFloat(
            document.getElementById(`open_balance_${i}`).value
        ) || 0;

        const quantityInput = document.getElementById(`quantity_${i}`);
        let quantity = parseFloat(quantityInput.value) || 0;

        if (quantity > open_balance) {
            alert("Quantity cannot be greater than Open Balance");
            quantityInput.value = open_balance;
            quantity = open_balance;
        }

        document.getElementById(`close_balance_${i}`).value =
            open_balance - quantity;

        calculateOpenTotals();
        calculateCloseTotals();
    }


    function get_stock_data(i) {
        var type = document.getElementById("type_" + i).value;
        var item_name = document.getElementById("item_name_" + i).value;
        const stock_type = document.getElementById("stock_type").value;

        let xhr = new XMLHttpRequest();
        xhr.open("POST", "get_stock_data.ajax.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // 🔥 Inject options into datalist
                console.log(xhr.responseText);

                document.getElementById("quantity_" + i).innerHTML = xhr.responseText;
            }
        };

        xhr.send("type=" + type + "&item_name=" + item_name + "&stock_type=" + stock_type);

    }

    function add_row() {
        rowIndex++;

        const tableBody = document.querySelector("#table_defualt tbody");
        if (!tableBody) return;

        const row = document.createElement("tr");

        row.innerHTML = `
        <td>
            <select id="type_${rowIndex}" name="type_${rowIndex}"
                class="inputs"
                onchange="getStockTypeDetails(${rowIndex}); clear_item(this, ${rowIndex});">
                <option value=""></option>
                <?php echo $stock_type_list; ?>
            </select>
            <input type="hidden" id="stock_no_${rowIndex}" name="stock_no_${rowIndex}">
        </td>

        <td>
            <input id="item_name_${rowIndex}" name="item_name_${rowIndex}"
                list="stock_list_${rowIndex}"
                class="inputs"
                onchange="getQuantity(${rowIndex})">
            <datalist id="stock_list_${rowIndex}"></datalist>
        </td>

        <td>
            <input type="number" id="quantity_${rowIndex}" name="quantity_${rowIndex}"
                class="inputs"
                onchange="maxQuantity(${rowIndex})">
        </td>

        <td>
            <input id="registration_no_${rowIndex}" name="registration_no_${rowIndex}"
                class="inputs">
        </td>

        <td>
            <input id="open_balance_${rowIndex}" name="open_balance_${rowIndex}"
                class="inputs"
                onchange="calculateOpenTotals()">
        </td>

        <td>
            <input id="close_balance_${rowIndex}" name="close_balance_${rowIndex}"
                class="inputs"
                onchange="calculateCloseTotals()">
        </td>

        <td>
            <button type="button" class="delete_btn" onclick="delete_row(this)">
                DELETE
            </button>
        </td>
    `;

        tableBody.appendChild(row);
        document.getElementById("no_rows").value = rowIndex;
    }

    function delete_row(btn) {
        btn.closest("tr").remove();
        calculateOpenTotals();
        calculateCloseTotals();
    }

    calculateOpenTotals();
    calculateCloseTotals();

    function calculateOpenTotals() {
        var open_balance_total = 0;

        document.getElementById("open_row_balance_total").value = 0;

        // Only row inputs, NOT totals
        const open_balance_inputs = document.querySelectorAll(
            "input[name^='open_balance']"
        );

        open_balance_inputs.forEach(input => {
            open_balance_total += parseFloat(input.value) || 0;
        });

        document.getElementById("open_row_balance_total").value = open_balance_total;
    }

    function calculateCloseTotals() {
        var closing_balance_total = 0;

        document.getElementById("close_row_balance_total").value = 0;

        const closing_balance_inputs = document.querySelectorAll(
            "input[name^='close_balance']"
        );

        closing_balance_inputs.forEach(input => {
            closing_balance_total += parseFloat(input.value) || 0;
        });

        document.getElementById("close_row_balance_total").value = closing_balance_total;
    }

    function check_submit() {
        var team_assigned = document.getElementById("team_assigned").value;
        var date_booked = document.getElementById("date_booked").value;

        if (!team_assigned || !date_booked) {
            alert("TEAM ASSIGNED AND BOOKING DATE ARE REQUIRED");
            return false;
        }

        return true;
    }

    function clear_item(selectElement, i) {
        var itemField = document.getElementById("item_name_" + i);

        // Always clear item when type changes
        itemField.value = "";
    }

</script>