<?php

include "../../classes/autoload.php";

$html = new html("");

$app = new inner_app();
$app->quick_bar("/app/invoices/");
$app->app_start();

$order_res = $db->query("orders", "SELECT * FROM orders WHERE record_id = '{$_GET['record_id']}'");
$order = $order_res->fetch_assoc();

$order_items_res = $db->query("order_list", "SELECT * FROM order_list WHERE order_id = '{$order['record_id']}'");


$order_checklist_res = $db->query("order_checklist", "SELECT * FROM order_checklist WHERE order_id = '{$order['record_id']}'");


?>

<script>
    function get_unit_of_measure(input, i) {
        let xhr = new XMLHttpRequest();
        xhr.open("POST", "get_unit_of_measure.ajax.php", true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText);
                document.getElementById("unit_of_measure_" + i).value = xhr.responseText.split(',')[0];
                document.getElementById("retail_price_" + i).value = xhr.responseText.split(',')[1];
                calculateRow(document.getElementById("retail_price_" + i), i);
            }
        };
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send("record_id=" + input.value);
    }

    function calculateRow(input, i) {
        let qty = parseFloat(document.querySelector(`#table #unit_of_measure_${i}`).parentNode.parentNode.querySelector("[name='qty[]']").value) || 0;
        let price = parseFloat(document.getElementById("retail_price_" + i).value) || 0;
        let total = qty * price;
        document.getElementById("total_" + i).value = total.toFixed(2);
        calculateTotals();
    }

    function calculateTotals() {
        let totals = document.querySelectorAll("[id^='total_']");
        let subtotal = 0;
        totals.forEach(t => {
            subtotal += parseFloat(t.value) || 0;
        });
        let vat = subtotal * 0.15;
        let net_total = subtotal + vat;

        document.getElementById("subtotal").value = subtotal.toFixed(2);
        document.getElementById("vat").value = vat.toFixed(2);
        document.getElementById("net_total").value = net_total.toFixed(2);
    }
</script>

<div class="column width_90 background_1 border_radius">

    <h1>SITE WORK SCHEDULE <?php echo $order['record_id']; ?></h1>
    <div class="row column_gap_2 width_80">
        <div class="column  width_100">
            <label>INSTELLATION DATE</label>
            <input type="date" name="order_date" class="width_100" value="<?php echo $order['order_date']; ?>">
            <input type="text" name="record_id" hidden class="width_100" value="<?php echo $order['record_id']; ?>">
        </div>
    </div>
    <br>
    <!-- <button class="width_90" onclick="add_row()">ADD NEW ROW</button> -->
    <br>
    <table class="width_80" id="table">
        <thead>
            <tr>
                <th>Colour & Code</th>
                <th>Description</th>
                <th>Qty</th>
                <th>Size m</th>
            </tr>
        </thead>
        <tbody>
            <?php
            while ($order_items = $order_items_res->fetch_assoc()) {
                $stock_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = '{$order_items['stock_id']}'");
                $stock = $stock_res->fetch_assoc();

                if ($stock['code'] == "DLVR") {
                    continue;
                }
                ?>
                <tr>
                    <td>
                        <input class="background_1  padding_minmal border_1" readonly
                            style="color:white; width: 8vw;font-size: 0.9em;" id="stock_code_1"
                            value="<?php echo $stock['code']; ?>">
                    </td>
                    <td>
                        <input class=" background_1 padding_minmal border_1" readonly
                            style="color:white;font-size: 0.9em;width:20vw;" name="stock_id[]" id="stock_1"
                            value="<?php echo $stock['code']; ?>">
                    </td>
                    <td>
                        <input class="background_1 width_90 padding_minmal border_1" readonly
                            style="color:white; width:5vw;font-size: 0.9em;" type="text" name="qty[]"
                            value="<?php echo $order_items['qty']; ?>">
                    </td>
                    <td>
                        <input class="background_1 width_90 padding_minmal border_1" readonly
                            style="color:white; width:5vw;font-size: 0.9em;" type="text" name="size_m[]"
                            value="<?php echo $order_items['size_m']; ?>">
                    </td>
                </tr>
                <?php

            } ?>
        </tbody>
    </table>
    <div class="row column_gap_2 width_80">
        <div class="column  width_100">
            <label>JOB DESCRIPTION</label>
            <textarea name="description" class="width_100" rows="4"><?php echo $order['description']; ?></textarea>
        </div>
    </div>
    <br>
    <button class="width_90" onclick="add_row()">ADD NEW ROW</button>
    <br>
    <table class="width_80" id="table_list">
        <thead>
            <tr>
                <th>CHECK LIST</th>
                <th></th>
        </thead>
        <tbody>
            <?php
            while ($order_checklist = $order_checklist_res->fetch_assoc()) {
                ?>
                <tr>
                    <td>
                        <textarea class="background_1  padding_minmal border_1"
                            style="color:white; width: 8vw;font-size: 0.9em;"
                            name="list[]"><?php echo $order_checklist['text']; ?></textarea>
                    </td>
                    <td><button class="width_100" onclick="delete_row(this)">DELETE</button></td>
                </tr>

                <?php

            } ?>
        </tbody>
    </table>
    <div class="row column_gap_2 width_80">
        <div class="column  width_100">
            <label>Clause</label>
            <textarea name="clause" class="width_100" rows="12"><?php echo $order['clause']; ?>
            </textarea>
        </div>
    </div>
    <script>
        let index = 1;

        function delete_row(el) {
            var row = el.parentNode.parentNode;
            row.parentNode.removeChild(row);
            calculateTotals();
        }



        function add_row() {
            index++;
            var table = document.getElementById("table_list").getElementsByTagName('tbody')[0];
            var row = table.insertRow(-1);

            row.innerHTML = `
            <tr>
                <td>
                    <textarea class="background_1  padding_minmal border_1" style="color:white; width: 8vw;font-size: 0.9em;width:100%;" name="list[]"></textarea>
                </td>
                  <td><button class="width_100" onclick="delete_row(this)">DELETE</button></td>
            </tr>
            `;
        }

        function delete_row(el) {
            var row = el.parentNode.parentNode;
            row.parentNode.removeChild(row);
            calculateTotals();
        }

        function get_unit_of_measure(input, i) {
            data = input.value.split("~");
            document.getElementById("stock_code_" + i).value = data[0];
            let price = parseFloat(data[3].replace(/ /g, "").replace(/[^\d.]/g, '.')) || 0;
            console.log(data[3]);
            console.log(price);
            document.getElementById("stock_" + i).value = data[1];

        }

    </script>
    <br>
    <button class="width_90" onclick="save('update_orders.php')">SAVE</button>
    <br>
</div>

<script>
    function open_pdf(url) {
        window.open(url);
    }
    function save(url) {
        let payload = {};

        // handle all inputs
        let inputs = document.querySelectorAll("input, select, textarea");
        inputs.forEach(el => {
            let name = el.name;
            if (!name) return;

            if (name.endsWith("[]")) {
                // ensure array
                if (!payload[name]) payload[name] = [];
                payload[name].push(el.value);
            } else {
                payload[name] = el.value;
            }
        });

        // create form
        let form = document.createElement("form");
        form.method = "POST";
        form.action = url;

        // add hidden inputs
        for (let key in payload) {
            if (Array.isArray(payload[key])) {
                payload[key].forEach(v => {
                    let input = document.createElement("input");
                    input.type = "hidden";
                    input.name = key;   // already has [] in name
                    input.value = v;
                    form.appendChild(input);
                });
            } else {
                let input = document.createElement("input");
                input.type = "hidden";
                input.name = key;
                input.value = payload[key];
                form.appendChild(input);
            }
        }

        document.body.appendChild(form);
        form.submit();
    }
</script>