<?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("EDIT DELIVERY NOTE");
$app  = new inner_app();
$app->quick_bar("/app/delivery_note/");
$app->app_start();

// ── Fetch existing delivery note ──────────────────────────────────────────────
$record_id = (int) ($_GET['record_id'] ?? 0);
$dn = $db->query("delivery_note", "SELECT * FROM delivery_note WHERE record_id = '$record_id'")->fetch_assoc();

// ── Fetch existing line items ─────────────────────────────────────────────────
$existing_items = [];
if ($dn) {
    $list_res = $db->query("delivery_note_list", "SELECT * FROM delivery_note_list WHERE delivery_note_id = '$record_id'");
    while ($row = $list_res->fetch_assoc()) {
        $existing_items[] = $row;
    }
}

// ── Fetch invoice number for display ─────────────────────────────────────────
$invoice_number = '';
if ($dn) {
    $inv = $db->query("invoices", "SELECT invoice_number FROM invoices WHERE record_id = '{$dn['quote_id']}'")->fetch_assoc();
    $invoice_number = $inv['invoice_number'] ?? '';
}

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

<script>
    function get_items_for_invoice(invoice_id) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'edit_delivery_note.php?get_items=1&invoice_id=' + invoice_id, 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="5" style="text-align:center;color:#888;">No items found for this invoice.</td></tr>';
                    return;
                }

                items.forEach(function (item) {
                    append_row(item.code, item.stock_name, item.size_m, item.pannels);
                });
            }
        };
        xhr.send();
    }

    function append_row(code, description, size_m, pannels) {
        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="' + escHtml(code) + '"></td>' +
            '<td><input class="background_1 padding_minmal border_1" style="color:white;width:20vw;font-size:0.9em;" name="description[]" value="' + escHtml(description) + '"></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(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(pannels) + '"></td>' +
            '<td><button type="button" onclick="delete_row(this)">DELETE</button></td>';
        tbody.appendChild(tr);
    }

    document.addEventListener('DOMContentLoaded', function () {

        // Pre-populate existing rows
        var existingItems = <?= json_encode($existing_items) ?>;
        if (existingItems.length > 0) {
            document.querySelector('#items_table tbody').innerHTML = '';
            existingItems.forEach(function (item) {
                append_row(item.stock_code, item.description, item.size_m, item.pannels);
            });
        }

        // Invoice change — reload rows from that invoice
        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;
            }

            get_items_for_invoice(hidden.value);
        });
    });

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

    function add_row() {
        append_row('', '', '0', '0');
    }

    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 = 'update_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>EDIT DELIVERY NOTE</h1>

    <input type="hidden" name="record_id" id="record_id" value="<?= $record_id ?>">

    <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" value="<?= htmlspecialchars($invoice_number) ?>" required>
            <input type="hidden" name="invoice_id" id="invoice_id" value="<?= htmlspecialchars($dn['quote_id'] ?? '') ?>">
        </div>
        <div class="column width_50">
            <label>NOTE</label>
            <input class="width_80" name="note" id="note" value="<?= htmlspecialchars($dn['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;">Loading...</td>
            </tr>
        </tbody>
    </table>

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

</div>