<?php
include "../../classes/autoload.php";

$html = new html("");
$app = new inner_app();
$app->quick_bar("/app/delivery_note/");
$app->app_start();

$delivery_note_id = (int) ($_GET['record_id'] ?? 0);
if ($delivery_note_id <= 0) {
    die("Invalid delivery note");
}

$dn_res = $db->query("delivery_note", "SELECT * FROM delivery_note WHERE record_id = {$delivery_note_id} LIMIT 1");
if ($dn_res->num_rows == 0) {
    die("Delivery note not found");
}
$delivery_note = $dn_res->fetch_assoc();

$list_res = $db->query("delivery_note_list", "SELECT * FROM delivery_note_list WHERE delivery_note_id = {$delivery_note_id}");

$function->get_stock_datalist("stock_list");
?>

<datalist id="stock_desc_list"></datalist>

<div class="column width_90 background_1 border_radius">
    <h1>DELIVERY NOTE NO. <?php echo $delivery_note['record_id']; ?></h1>
    <div class="row column_gap_2 width_80">
        <div class="column  width_50">
            <?php $function->get_invoices_list_as_record_id('invoice_list'); ?>
            <label>INVOICE</label>
            <input class="width_80" id="invoice_name"
                value="<?php echo $function->get_invoice_no($delivery_note['quote_id']); ?>" autocomplete="off"
                list="invoice_list" required>
            <input type="hidden" name="invoice_id" id="invoice_id" value="<?php echo $delivery_note['quote_id']; ?>">
        </div>
    </div>

    <input type="hidden" name="record_id" value="<?php echo $delivery_note_id; ?>">

    <br>
    <button class="width_90" onclick="add_row()">ADD NEW ROW</button>
    <br>
    <table class="width_80" id="table">
        <thead>
            <tr>
                <th>Code</th>
                <th>Description</th>
                <th>Size m</th>
                <th>Panels</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php
            $index = 0;
            while ($row = $list_res->fetch_assoc()) {
                $index++;
                ?>
                <tr>
                    <td>
                        <input class="background_1 padding_minmal border_1" style="color:white; width:8vw;font-size:0.9em;"
                            id="stock_code_<?php echo $index; ?>" list="stock_list" name="stock_code[]"
                            value="<?php echo htmlspecialchars($row['stock_code']); ?>"
                            onchange="fill_description(this, <?php echo $index; ?>)">
                    </td>
                    <td>
                        <input class="background_1 padding_minmal border_1" style="color:white;font-size:0.9em;width:25vw;"
                            id="stock_<?php echo $index; ?>" list="stock_desc_list" name="description[]"
                            value="<?php echo htmlspecialchars($row['description']); ?>"
                            onchange="fill_from_desc(this, <?php echo $index; ?>)">
                    </td>
                    <td>
                        <input class="background_1 padding_minmal border_1" style="color:white;width:5vw;font-size:0.9em;"
                            type="number" min="0" value="<?php echo htmlspecialchars($row['size_m']); ?>" name="size_m[]">
                    </td>
                    <td>
                        <input class="background_1 padding_minmal border_1" style="color:white;width:5vw;font-size:0.9em;"
                            type="number" min="0" value="<?php echo htmlspecialchars($row['pannels']); ?>" name="pannels[]">
                    </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>NOTE</label>
            <textarea name="note" id="note" class="width_100"
                rows="4"><?php echo htmlspecialchars($delivery_note['note']); ?></textarea>
        </div>
    </div>

    <br>
    <button class="width_90" onclick="open_pdf('delivery_note.pdf.php?record_id=<?php echo $delivery_note_id; ?>')">VIEW
        PDF</button>
    <br><br>
    <button class="width_90" onclick="save('update_delivery_note.php')">SAVE</button>
    <br>
</div>

<script>
    let index = <?php echo $index; ?>;

    function loadInvoiceStock(invoice_id) {
        if (!invoice_id) return;
        let xhr = new XMLHttpRequest();
        xhr.open("POST", "get_invoice_stock.ajax.php", true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let lines = xhr.responseText.trim().split("\n");
                let codeHtml = "";
                let descHtml = "";
                lines.forEach(line => {
                    let parts = line.split("~");
                    if (parts.length >= 4) {
                        codeHtml += '<option value="' + parts[0] + '~' + parts[1] + '~' + parts[2] + '~' + parts[3] + '">';
                        descHtml += '<option value="' + parts[1] + '~' + parts[0] + '~' + parts[2] + '~' + parts[3] + '">';
                    }
                });
                document.getElementById("stock_list").innerHTML = codeHtml;
                document.getElementById("stock_desc_list").innerHTML = descHtml;
            }
        };
        xhr.send("invoice_id=" + invoice_id);
    }

    // Load datalists immediately for the already-selected invoice
    window.addEventListener("load", function () {
        loadInvoiceStock(document.getElementById("invoice_id").value);
    });

    document.getElementById("invoice_name").addEventListener("change", function () {
        const input = this.value;
        const options = document.querySelectorAll("#invoice_list option");
        const hidden = document.getElementById("invoice_id");
        let found = false;
        options.forEach(opt => {
            if (opt.value === input) {
                hidden.value = opt.dataset.id;
                found = true;
            }
        });
        if (!found) {
            hidden.value = "";
            return;
        }
        loadInvoiceStock(hidden.value);
    });

    function fill_description(input, i) {
        let data = input.value.split("~");
        if (data.length >= 2) {
            document.getElementById("stock_code_" + i).value = data[0];
            document.getElementById("stock_" + i).value = data[1];
        }
    }

    function fill_from_desc(input, i) {
        let data = input.value.split("~");
        if (data.length >= 2) {
            document.getElementById("stock_" + i).value = data[0];
            document.getElementById("stock_code_" + i).value = data[1];
        }
    }

    function add_row() {
        index++;
        var table = document.getElementById("table").getElementsByTagName('tbody')[0];
        var row = table.insertRow(-1);
        row.innerHTML = `
        <tr>
            <td>
                <input class="background_1 padding_minmal border_1"
                    style="color:white; width:8vw;font-size:0.9em;" id="stock_code_${index}"
                    list="stock_list" name="stock_code[]"
                    onchange="fill_description(this, ${index})">
            </td>
            <td>
                <input class="background_1 padding_minmal border_1"
                    style="color:white;font-size:0.9em;width:25vw;" id="stock_${index}"
                    list="stock_desc_list" name="description[]"
                    onchange="fill_from_desc(this, ${index})">
            </td>
            <td>
                <input class="background_1 padding_minmal border_1"
                    style="color:white;width:5vw;font-size:0.9em;" type="number"
                    min="0" value="0" name="size_m[]">
            </td>
            <td>
                <input class="background_1 padding_minmal border_1"
                    style="color:white;width:5vw;font-size:0.9em;" type="number"
                    min="0" value="0" name="pannels[]">
            </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);
    }

    function open_pdf(url) {
        window.open(url);
    }

    function save(url) {
        let invoice_id = document.getElementById('invoice_id').value;
        if (invoice_id == '') {
            alert('Please select an invoice');
            return;
        }
        let payload = {};
        let inputs = document.querySelectorAll("input, select, textarea");
        inputs.forEach(el => {
            let name = el.name;
            if (!name) return;
            if (name.endsWith("[]")) {
                if (!payload[name]) payload[name] = [];
                payload[name].push(el.value);
            } else {
                payload[name] = el.value;
            }
        });
        let form = document.createElement("form");
        form.method = "POST";
        form.action = url;
        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;
                    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>