<?php
require("../../classes/autoload.php");

// ── AJAX: return invoice line items as JSON ───────────────────────────────────
if (isset($_GET['get_items']) && isset($_GET['invoice_id'])) {
    $invoice_id = (int) $_GET['invoice_id'];
    $res = $db->query("invoice_list", "
        SELECT il.size_m, il.pannels, s.code, s.name AS stock_name
        FROM invoice_list il
        JOIN stock s ON s.record_id = il.stock_id
        WHERE il.invoice_id = '$invoice_id'
    ");
    $rows = [];
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
    header('Content-Type: application/json');
    echo json_encode($rows);
    exit;
}

$html = new html("ADD DELIVERY NOTE");
$app  = new inner_app();
$app->quick_bar("/app/delivery_note/");
$app->app_start();

$function->get_invoices_list_as_record_id('invoice_list');
?>

<script>
    // When an invoice is selected from the datalist, look up its record_id
    // then fire AJAX to fetch line items and populate the table
    document.addEventListener('DOMContentLoaded', function () {

        document.getElementById('invoice_name').addEventListener('change', function () {
            var input   = this.value;
            var options = document.querySelectorAll('#invoice_list option');
            var hidden  = document.getElementById('invoice_id');

            var found = false;
            options.forEach(function (opt) {
                if (opt.value === input) {
                    hidden.value = opt.dataset.id;
                    found = true;
                }
            });

            if (!found) {
                hidden.value = '';
                return;
            }

            // Fetch line items for this invoice
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'add_delivery_note.php?get_items=1&invoice_id=' + hidden.value, true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var items = JSON.parse(xhr.responseText);
                    var tbody = document.querySelector('#items_table tbody');
                    tbody.innerHTML = '';

                    if (items.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;color:#888;">No items found for this invoice.</td></tr>';
                        return;
                    }

                    items.forEach(function (item) {
                        var tr = document.createElement('tr');
                        tr.innerHTML =
                            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:8vw;font-size:0.9em;" name="stock_code[]" value="' + escHtml(item.code) + '"></td>' +
                            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:20vw;font-size:0.9em;" name="description[]" value="' + escHtml(item.stock_name) + '"></td>' +
                            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:6vw;font-size:0.9em;" type="number" min="0" step="0.001" name="size_m[]" value="' + escHtml(item.size_m) + '"></td>' +
                            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:6vw;font-size:0.9em;" type="number" min="0" name="pannels[]" value="' + escHtml(item.pannels) + '"></td>' +
                            '<td><button type="button" onclick="delete_row(this)">DELETE</button></td>';
                        tbody.appendChild(tr);
                    });
                }
            };
            xhr.send();
        });
    });

    function escHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    function add_row() {
        var tbody = document.querySelector('#items_table tbody');
        var tr = document.createElement('tr');
        tr.innerHTML =
            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:8vw;font-size:0.9em;" name="stock_code[]" value=""></td>' +
            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:20vw;font-size:0.9em;" name="description[]" value=""></td>' +
            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:6vw;font-size:0.9em;" type="number" min="0" step="0.001" name="size_m[]" value="0"></td>' +
            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:6vw;font-size:0.9em;" type="number" min="0" name="pannels[]" value="0"></td>' +
            '<td><button type="button" onclick="delete_row(this)">DELETE</button></td>';
        tbody.appendChild(tr);
    }

    function delete_row(el) {
        el.closest('tr').remove();
    }

    function save() {
        var payload = {};
        var inputs  = document.querySelectorAll('input, select, textarea');
        inputs.forEach(function (el) {
            if (!el.name) return;
            if (el.name.endsWith('[]')) {
                if (!payload[el.name]) payload[el.name] = [];
                payload[el.name].push(el.value);
            } else {
                payload[el.name] = el.value;
            }
        });

        var form = document.createElement('form');
        form.method = 'POST';
        form.action = 'save_delivery_note.php';

        for (var key in payload) {
            if (Array.isArray(payload[key])) {
                payload[key].forEach(function (v) {
                    var input = document.createElement('input');
                    input.type  = 'hidden';
                    input.name  = key;
                    input.value = v;
                    form.appendChild(input);
                });
            } else {
                var input = document.createElement('input');
                input.type  = 'hidden';
                input.name  = key;
                input.value = payload[key];
                form.appendChild(input);
            }
        }

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

<div class="column width_90 background_1 border_radius">

    <h1>ADD DELIVERY NOTE</h1>

    <div class="row column_gap_2 width_80">
        <div class="column width_50">
            <label>INVOICE</label>
            <input class="width_80" id="invoice_name" name="invoice_name" autocomplete="off"
                   list="invoice_list" placeholder="Select invoice..." required>
            <input type="hidden" name="invoice_id" id="invoice_id">
        </div>
        <div class="column width_50">
            <label>NOTE</label>
            <input class="width_80" name="note" id="note" placeholder="Optional note...">
        </div>
    </div>

    <br>
    <button class="width_90" type="button" onclick="add_row()">ADD NEW ROW</button>
    <br>

    <table class="width_80" id="items_table">
        <thead>
            <tr>
                <th>Code</th>
                <th>Description</th>
                <th>Size (m)</th>
                <th>Panels</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td colspan="5" style="text-align:center;color:#888;">Select an invoice above to load items.</td>
            </tr>
        </tbody>
    </table>

    <br>
    <button class="width_90" type="button" onclick="save()">SAVE</button>
    <br>

</div>