<?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}"
);
?>


<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 = "";
                    }
                });
            </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;">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"><?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 subtotal = 0;

            totals.forEach(t => {
                let amount = parseFloat(t.value) || 0;
                subtotal += amount;
            });

            document.getElementById("total").value =
                new Intl.NumberFormat('en-ZA', {
                    style: 'currency',
                    currency: 'ZAR'
                }).format(subtotal);
            document.getElementById("total").value = document.getElementById("total").value.replace(",", ".");
        }
        window.onload = calculateTotals;
    </script>


    <br>
    <?php if ($_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 = {};

        // 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>