<?php

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

$html = new html("");

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

$c_notes_res = $db->query("credit_notes", "SELECT * FROM credit_notes WHERE 1 ORDER BY record_id DESC LIMIT 1");
if ($c_notes_res->num_rows == 0) {
    $credit_note_no = 1;
} else {
    $credit_note_no = $c_notes_res->num_rows + 1;
}

?>

<div class="column width_90 background_1 border_radius">
    <h1>CREDIT NOTE NO. <?php echo $credit_note_no ?></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" autocomplete="off" list="invoice_list" required>

            <input type="hidden" name="invoice_id" id="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 = "";
                    }
                });
            </script>
        </div>

    </div>
    <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>
            <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_1" step="0.01" name="amounts[]"
                        onchange="calculateTotals()">
                </td>
                <td><button class="width_100" onclick="delete_row(this)">DELETE</button></td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="1" style="text-align:right;color:black;">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>
        </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">BANK:
ACC. NO:
BRANCH:
NAME:
            </textarea>

        </div>
    </div>
    <script>
        let index = 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;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 subtotal = 0;
            totals.forEach(t => {
                amount = t.value.replace(/[^\d\.\-]/g, '');
                subtotal += parseFloat(amount) || 0;
            });
            let net_total = subtotal;
            document.getElementById("total").value = new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(net_total);
              document.getElementById("total").value = document.getElementById("total").value.replace(",", ".");
        }
    </script>


    <br>
    <button class="width_90" onclick="save('save_c_notes.php')">SAVE</button>
    <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 = {};

        // 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>