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

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

$credit_note_id = (int) ($_GET['record_id'] ?? 0);
if ($credit_note_id <= 0) {
    die("Invalid credit note");
}

/* Load credit note */
$c_note_res = $db->query(
    "credit_notes",
    "SELECT * FROM credit_notes WHERE record_id = {$credit_note_id} LIMIT 1"
);

if ($c_note_res->num_rows == 0) {
    die("Credit note not found");
}
$credit_note = $c_note_res->fetch_assoc();

/* Load credit note rows */
$list_res = $db->query(
    "credit_notes_list",
    "SELECT * FROM credit_notes_list WHERE credit_note_id = {$credit_note_id}"
);

/* Load invoice subtotal */
$invoice_id = $credit_note['invoice_id'];
$inv_list_res = $db->query("invoice_list", "SELECT * FROM invoice_list WHERE invoice_id = '$invoice_id'");
$invoice_subtotal = 0;
while ($inv_row = $inv_list_res->fetch_assoc()) {
    $price = floatval(preg_replace('/[^0-9\.\-]/', '', $inv_row['price']));
    $qty   = floatval($inv_row['qty']);
    $invoice_subtotal += $price * $qty;
}
?>

<div class="column width_90 background_1 border_radius">
    <h1>CREDIT NOTE NO. <?php echo $credit_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($credit_note['invoice_id']); ?>" autocomplete="off"
                list="invoice_list" required>

            <input type="hidden" name="invoice_id" id="invoice_id" value="<?php echo $credit_note['invoice_id']; ?>">
            <script>
                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;
                    }

                    // fetch invoice total when invoice changes
                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "/app/c_notes/get_invoice_total.ajax.php", true);
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            let data = JSON.parse(xhr.responseText);
                            document.getElementById("invoice_subtotal").value = data.subtotal;
                            calculateTotals();
                        }
                    };
                    xhr.send("invoice_id=" + encodeURIComponent(hidden.value));
                });
            </script>
        </div>

    </div>
    <input type="hidden" name="record_id" value="<?php echo $credit_note_id; ?>">
    <br>
    <button class="width_90" onclick="add_row()">ADD NEW ROW</button>
    <br>
    <table class="width_80" id="table">
        <thead>
            <tr>
                <th>Description</th>
                <th>Amount</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;font-size:0.9em;width:40vw;"
                            name="descriptions[]" value="<?php echo htmlspecialchars($row['name']); ?>">
                    </td>
                    <td>
                        <input class="background_1 padding_minmal border_1" style="color:white;width:10vw;font-size:0.9em;"
                            type="text" id="amount_<?php echo $index; ?>" name="amounts[]"
                            value="<?php echo number_format($row['amount'], 2, '.', ''); ?>" onchange="calculateTotals()">
                    </td>
                    <td>
                        <button class="width_100" onclick="delete_row(this)">DELETE</button>
                    </td>
                </tr>
            <?php } ?>
        </tbody>
        <tfoot>
            <tr>
                <td style="text-align:right;color:black;">Invoice Subtotal:</td>
                <td>
                    <input class="background_1 padding border_1" style="color:white;width:10vw;font-size:0.9em;"
                        type="text" id="invoice_subtotal" value="R <?php echo number_format($invoice_subtotal, 2, '.', ','); ?>" readonly>
                </td>
                <td></td>
            </tr>
            <tr>
                <td style="text-align:right;color:black;">Credit Note Total:</td>
                <td>
                    <input class="background_1 padding border_1" style="color:white;width:10vw;font-size:0.9em;"
                        type="text" id="total" readonly>
                </td>
                <td></td>
            </tr>
            <tr>
                <td style="text-align:right;color:black;">Balance After Credit:</td>
                <td>
                    <input class="background_1 padding border_1" style="color:white;width:10vw;font-size:0.9em;"
                        type="text" id="balance" readonly>
                </td>
                <td></td>
            </tr>
        </tfoot>
    </table>

    <div class="row column_gap_2 width_80">
        <div class="column  width_100">
            <label>CLIENT BANKING DETAILS</label>
            <textarea name="note" id="note" class="width_100" rows="4"><?php echo $credit_note['client_banking_details']; ?>
            </textarea>
        </div>
    </div>

    <script>
        let index = <?php echo $index; ?>;

        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;font-size: 0.9em;width:40vw;" name="descriptions[]" />
            </td>
            <td>
                <input class="background_1 padding_minmal border_1" style="color:white;width:10vw;font-size: 0.9em;"
                    type="text" min="0" value="0" id="amount_${index}" step="0.01" name="amounts[]"
                 onchange="calculateTotals()">
            </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 calculateTotals() {
            let totals = document.querySelectorAll("[id^='amount_']");
            let credit_total = 0;

            totals.forEach(t => {
                let amount = parseFloat(t.value) || 0;
                credit_total += amount;
            });

            let invoice_subtotal_raw = document.getElementById("invoice_subtotal").value.replace(/[^\d\.\-]/g, '');
            let invoice_subtotal = parseFloat(invoice_subtotal_raw) || 0;
            let balance = invoice_subtotal - credit_total;

            document.getElementById("total").value = new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(credit_total).replace(",", ".");
            document.getElementById("balance").value = new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(balance).replace(",", ".");
        }

        window.onload = calculateTotals;
    </script>

    <br>
    <?php if (isset($_GET['from_invoice']) && $_GET['from_invoice'] == 1) { ?>
        <button class="width_90" onclick="save('update_c_notes.php?send_to_invoice=1')">SAVE</button>
        <br>
    <?php } else { ?>
        <button class="width_90" onclick="save('update_c_notes.php')">SAVE</button>
        <br>
    <?php } ?>
    <br>

</div>

<script>
    function save(url) {
        invoice_id = document.getElementById('invoice_id').value
        if (invoice_id == '') {
            alert('Please fill in all required fields');
            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>