<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$date_returned_label = new label();
$date_returned_label->for("date_returned_label");
$date_returned_label->value("DATE RETURNED : ");
$date_returned_label->addAttribute("style", "font-size: 1.5em; width: 30%;");

$date_returned = new input();
$date_returned->class("inputs");
$date_returned->name("date_returned");
$date_returned->id("date_returned");
$date_returned->type("datetime-local");
$date_returned->style("font-size: 1.5em; width: 80%; margin: 0.5vw auto;");

$date_booked_label = new label();
$date_booked_label->for("date_booked_label");
$date_booked_label->value("DATE BOOKED : ");
$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->style("font-size: 1.5em; width: 80%; margin: 0.5vw auto;");
$date_booked->value_from_db("book_stock", "booking_date", "record_id = {$_GET['record_id']}");
$date_booked->addAttribute("readonly", "readonly");
$date_booked->addAttribute("disabled", "disabled");

$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");

$booked_stock_res = $db->query("book_stock", "SELECT * FROM book_stock WHERE record_id = '{$_GET['record_id']}'");

$booked_stock = $booked_stock_res->fetch_assoc();

$booked_data_res = $db->query("book_stock_list", "SELECT * FROM book_stock_list WHERE order_no = '{$booked_stock['order_no']}'");
// echo "SELECT * FROM book_stock_list WHERE order_no = '{$booked_stock['order_no']}'";

?>

<form action="return_stock.ajax.php" method="post">
    <div class="form_down">
        <h1>STOCK ASSIGNED</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;
            }

            .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>

        <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="<?php echo $booked_stock['order_no']; ?>" 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%;">
            <?php
            $date_returned_label->add();
            $date_returned->add();
            ?>
        </div>

        <br>
        <?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>";
        }

        ?>

        <input type="text" id="team_assigned_id" name="team_assigned_id"
            value="<?php echo $booked_stock['team_assigned_id']; ?>" hidden>

        <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>
                </tr>
            </thead>

            <?php
            $rows = $booked_data_res->num_rows;

            if ($rows > 0) {

                $i = 1;
                while ($booked_data = $booked_data_res->fetch_assoc()) {

                    $stock_type_data = $db->query("stock_types", "SELECT * FROM stock_types WHERE record_id = '{$booked_data['stock_type_id']}'");
                    $stock_type = $stock_type_data->fetch_assoc();
                    ?>
                    <tbody>
                        <tr>
                            <td>
                                <select id="type_defualt_<?= $i ?>" name="type_defualt_<?= $i ?>"
                                    style="width: 100%; margin: 0vw;" class="inputs" onchange="getStockTypeDetails(1,'defualt')"
                                    disabled>
                                    <option value=""></option>
                                    <option value="OILS" <?= ($stock_type['name'] == 'OILS') ? 'selected' : '' ?>>OILS</option>
                                    <option value="HYDRAULICS" <?= ($stock_type['name'] == 'HYDRAULICS') ? 'selected' : '' ?>>
                                        HYDRAULICS
                                    </option>
                                    <option value="PUMPS" <?= ($stock_type['name'] == 'PUMPS') ? 'selected' : '' ?>>PUMPS</option>
                                    <option value="HAMMER, BYTEL OR RIEMER" <?= ($stock_type['name'] == 'HAMMER, BYTEL OR RIEMER') ? 'selected' : '' ?>>HAMMER, BYTEL OR RIEMER
                                    </option>
                                    <option value="BOLTS & NUTS" <?= ($stock_type['name'] == 'BOLTS & NUTS') ? 'selected' : '' ?>>
                                        BOLTS & NUTS
                                    </option>
                                    <option value="CONSUMABLES" <?= ($stock_type['name'] == 'CONSUMABLES') ? 'selected' : '' ?>>
                                        CONSUMABLES
                                    </option>
                                </select>
                                <input type="text" id="stock_no_defualt_<?= $i ?>" name="stock_no_defualt_<?= $i ?>" hidden
                                    class="inputs">
                            </td>
                            <td>
                                <input id="item_defualt_<?= $i ?>" name="item_defualt_<?= $i ?>" list="stock_list_<?= $i ?>"
                                    style="width: 100%; margin: 0vw;" class="inputs" onchange="getQuantity(1, 'defualt')"
                                    value="<?php echo $booked_data['item_name']; ?>" disabled>
                                <datalist id="stock_list_1"></datalist>
                            </td>
                            <td>
                                <input type="number" id="quantity_defualt_<?= $i ?>" name="quantity_defualt_<?= $i ?>"
                                    style="width: 100%; margin: 0vw;" class="inputs"
                                    value="<?php echo $booked_data['amount'] ?>" readonly>
                                <input type="number" id="max_q_defualt_1" name="max_q_defualt_1"
                                    style="width: 100%; margin: 0vw;" class="inputs" hidden>
                            </td>
                            <td>
                                <input id="registration_no_defualt_<?= $i ?>" name="registration_no_defualt_<?= $i ?>"
                                    style="width: 100%; margin: 0vw;" class="inputs"
                                    value="<?php echo $booked_data['registration_no'] ?>" readonly>
                            </td>
                            <td>
                                <input id="open_defualt_<?= $i ?>" name="open_defualt_<?= $i ?>"
                                    style="width: 100%; margin: 0vw;" class="inputs" onchange="calculateOpenTotals()"
                                    value="<?php echo $booked_data['open_balance'] ?>" readonly>
                            </td>
                            <td>
                                <input id="close_defualt_<?= $i ?>" name="close_defualt_<?= $i ?>"
                                    style="width: 100%; margin: 0vw;" class="inputs" onchange="calculateCloseTotals();"
                                    value="<?php echo $booked_data['close_balance'] ?>" readonly>
                            </td>
                        </tr>
                    </tbody>

                    <?php
                    $i++;
                }

                ?>
                <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="text" name="index" id="index" value="<?php echo $rows ?>" hidden>

            <h1>RETURN STOCK</h1>

            <table style="width:95%;" id="table_pump">
                <thead>
                    <tr>
                        <th>Type</th>
                        <th>Item Name</th>
                        <th>Amount</th>
                        <th>Registaration No.</th>
                        <th>Open Balance</th>
                        <th>Closing Balance</th>
                    </tr>
                </thead>

                <tbody>
                    <?php
                    $return_data_res = $db->query("book_stock_list", "SELECT * FROM book_stock_list WHERE order_no = '{$booked_stock['order_no']}'");

                    $index = $return_data_res->num_rows;
                    // echo $index;
                
                    if ($index > 0) {
                        $index = 1;
                        while ($return_data = $return_data_res->fetch_assoc()) {

                            $stock_type_res = $db->query("stock_types", "SELECT * FROM stock_types WHERE record_id = '{$return_data['stock_type_id']}'");
                            $stock_type_data = $stock_type_res->fetch_assoc();
                            ?>
                            <tr>
                                <td>
                                    <select id='type_return_defualt_<?= $index ?>' name='type_return_defualt_<?= $index ?>'
                                        style='width: 100%; margin: 0vw;' class='inputs' onchange="getStockTypeDetails(1,'defualt')"
                                        disabled>
                                        <option value=''></option>
                                        <option value='OILS' <?= ($stock_type_data['name'] == 'OILS') ? 'selected' : '' ?>>OILS
                                        </option>
                                        <option value='HYDRAULICS' <?= ($stock_type_data['name'] == 'HYDRAULICS') ? 'selected' : '' ?>>
                                            HYDRAULICS</option>
                                        <option value='PUMPS' <?= ($stock_type_data['name'] == 'PUMPS') ? 'selected' : '' ?>>PUMPS
                                        </option>
                                        <option value='HAMMER, BYTEL OR RIEMER' <?= ($stock_type_data['name'] == 'HAMMER, BYTEL OR RIEMER') ? 'selected' : '' ?>>HAMMER, BYTEL OR RIEMER
                                        </option>
                                        <option value='BOLTS & NUTS' <?= ($stock_type_data['name'] == 'BOLTS & NUTS') ? 'selected' : '' ?>>BOLTS & NUTS</option>
                                        <option value='CONSUMABLES' <?= ($stock_type_data['name'] == 'CONSUMABLES') ? 'selected' : '' ?>>CONSUMABLES</option>
                                    </select>
                                    <input type='text' id='stock_no_pump_<?= $index ?>' name='stock_no_pump_<?= $index ?>' hidden
                                        class='inputs'>
                                </td>
                                <td>
                                    <input id='return_item_name_<?= $index ?>' name='return_item_name_<?= $index ?>'
                                        list='stock_list_<?= $index ?>' style='width: 100%; margin: 0vw;' class='inputs'
                                        onchange="getQuantity(<?= $index ?>, 'pump')"
                                        value="<?php echo $return_data['item_name'] ?>" disabled>
                                    <datalist id='stock_list_<?= $index ?>'></datalist>
                                </td>
                                <td>
                                    <input type='number' id='return_quantity_pump_<?= $index ?>'
                                        name='return_quantity_pump_<?= $index ?>' style='width: 100%; margin: 0vw;' class='inputs'
                                        onchange="maxQuantity(<?= $index ?>)">
                                    <input type='number' id='return_return_max_q_pump_<?= $index ?>'
                                        name='return_return_max_q_pump_<?= $index ?>' style='width: 100%; margin: 0vw;'
                                        class='inputs' hidden>
                                </td>
                                <td>
                                    <input id='return_registration_no_pump_<?= $index ?>'
                                        name='return_registration_no_pump_<?= $index ?>' style='width: 100%; margin: 0vw;'
                                        class='inputs' value="<?php echo $return_data['registration_no'] ?>" readonly>
                                </td>
                                <td>
                                    <input id='or_<?= $index ?>' name='or_<?= $index ?>' style='width: 100%; margin: 0vw;'
                                        class='inputs' onchange='calculateOBTotals()'
                                        value="<?php echo $return_data['close_balance'] ?>">
                                </td>
                                <td>
                                    <input id='cr_<?= $index ?>' name='cr_<?= $index ?>' style='width: 100%; margin: 0vw;'
                                        class='inputs' onchange='calculateCBTotals()'>
                                </td>
                            </tr>
                            <?php
                            $index++;
                        }
                    }

                    ?>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="4" style="text-align: right; font-size: 0.9em; font-weight: bold;">TOTAL : </td>
                        <td>
                            <input id="or_balance_total" name="or_balance_total" style="width: 100%; margin: 0vw;"
                                class="inputs" readonly>
                        </td>
                        <td>
                            <input id="cr_balance_total_pump" name="cr_balance_total_pump" style="width: 100%; margin: 0vw;"
                                class="inputs" readonly>
                        </td>
                        <td></td>
                    </tr>
            </table>

            <input type="text" name="index" id="index" value="<?php echo $index - 1 ?>" hidden>

            <?php
            }

            $submit_btn->add();
            ?>

    </div>
</form>

<script>

    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_']"
        );

        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_']"
        );

        closing_balance_inputs.forEach(input => {
            closing_balance_total += parseFloat(input.value) || 0;
        });

        document.getElementById("close_row_balance_total").value = closing_balance_total;
    }

    calculateOBTotals();
    calculateCBTotals();

    function calculateOBTotals() {
        var open_balance_total = 0;

        document.getElementById("or_balance_total").value = 0;

        // Only row inputs, NOT totals
        const open_balance_inputs = document.querySelectorAll(
            "input[name^='or_']"
        );

        open_balance_inputs.forEach(input => {
            open_balance_total += parseFloat(input.value) || 0;
        });

        document.getElementById("or_balance_total").value = open_balance_total;
    }

    function calculateCBTotals() {
        var closing_balance_total = 0;

        document.getElementById("cr_balance_total_pump").value = 0;

        const closing_balance_inputs = document.querySelectorAll(
            "input[name^='cr_']"
        );

        closing_balance_inputs.forEach(input => {
            closing_balance_total += parseFloat(input.value) || 0;
        });

        document.getElementById("cr_balance_total_pump").value = closing_balance_total;
    }

    function maxQuantity(i) {

        let quantityField = document.getElementById(`return_quantity_pump_${i}`);
        let defualtQuantity = document.getElementById(`quantity_defualt_${i}`);
        let openField = document.getElementById(`or_${i}`);   // ✅ FIXED
        let closeField = document.getElementById(`cr_${i}`);

        if (!quantityField || !openField || !closeField) return;

        let quantity = Number(quantityField.value);
        let open_balance = Number(defualtQuantity.value);
        let close_balance = Number(openField.value);

        if (isNaN(quantity) || quantity < 0) {
            quantity = 0;
        }

        if (quantity > open_balance) {
            quantity = open_balance;
            alert(`Maximum allowed is ${open_balance}`);
        }

        quantityField.value = quantity;
        closeField.value = close_balance + quantity;

        calculateOBTotals();   // ✅ use correct totals
        calculateCBTotals();
    }

</script>