<?php

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

$html = new html("");

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

$supplier_orders_res = $db->query('supplier_orders', "SELECT * FROM supplier_orders WHERE record_id = '{$_GET['record_id']}'");
// echo "SELECT * FROM supplier_orders WHERE record_id = '{$_GET['record_id']}'";
$supplier_orders_data = $supplier_orders_res->fetch_assoc();

$supplier_id_res = $db->query('suppliers', "SELECT * FROM suppliers WHERE record_id = '{$supplier_orders_data['supplier_id']}'");
$supplier_id_data = $supplier_id_res->fetch_assoc();

$invoice_number_res = $db->query("invoices", "SELECT * FROM invoices WHERE record_id = '{$supplier_orders_data['invoice_id']}'");
$invoice_number_data = $invoice_number_res->fetch_assoc();

$function->get_stock_datalist_cost("stock_list");
?>

<script>
    function get_unit_of_measure(input, i) {
        let xhr = new XMLHttpRequest();
        xhr.open("POST", "get_unit_of_measure.ajax.php", true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText);
                document.getElementById("unit_of_measure_" + i).value = xhr.responseText.split(',')[0];
                document.getElementById("retail_price_" + i).value = xhr.responseText.split(',')[1];
                calculateRow(document.getElementById("retail_price_" + i), i);
            }
        };
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send("record_id=" + input.value);
    }

    function calculateRow(input, i) {
        let qty = parseFloat(document.querySelector(`#table #unit_of_measure_${i}`).parentNode.parentNode.querySelector("[name='qty[]']").value) || 0;
        let price = parseFloat(document.getElementById("retail_price_" + i).value) || 0;
        let total = qty * price;
        document.getElementById("total_" + i).value = total.toFixed(2);
        calculateTotals();
    }

    function calculateTotals() {
        let totals = document.querySelectorAll("[id^='total_']");
        let subtotal = 0;
        totals.forEach(t => {
            subtotal += parseFloat(t.value) || 0;
        });
        let vat = subtotal * 0.15;
        let net_total = subtotal + vat;

        document.getElementById("subtotal").value = subtotal.toFixed(2);
        document.getElementById("vat").value = vat.toFixed(2);
        document.getElementById("net_total").value = net_total.toFixed(2);
    }

</script>

<div class="column width_90 background_1 border_radius">

    <h1>SUPPLIER ORDERS <?php echo $supplier_orders_data['record_id']; ?></h1>
    <div class="row column_gap_2 width_80">
        <div class="column  width_50">
            <?php
            $function->get_suppliers_datalist('suppliers_list');
            ?>
            <input class="width_80" id='record_id' name='record_id' value='<?php echo $_GET['record_id']; ?>' hidden>
            <label>SUPPLER</label>
            <input class="width_80" id='supplier_id' hidden name='supplier_id' />
            <input class="width_80" id='code' name='code' hidden oninput="get_supplier_order(this.value)" />
            <input class="width_80" id='supplier_name' required name='supplier_name' autocomplete="off"
                onchange="get_supplier_code(this)" list="suppliers_list" />
            <script>
                function get_supplier_code(el) {
                    let selected = el.value;
                    let options = document.getElementById("suppliers_list").options;
                    let found = false;
                    for (let i = 0; i < options.length; i++) {
                        if (options[i].value == selected) {
                            found = true;
                            break;
                        }
                    }
                    if (found) {
                        let data = selected.split(":");
                        document.getElementById("supplier_id").value = data[1];
                        document.getElementById("supplier_name").value = data[0];
                        document.getElementById("code").value = data[2];
                    } else {
                        alert("Please select a Supplier from the list");
                        document.getElementById("supplier_id").value = '';
                        el.value = "";
                    }

                    if (selected === '') {
                        document.getElementById('supplier_code').value = '';
                        return;
                    }

                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "get_supplier_order.ajax.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            document.getElementById('supplier_order_no').value = xhr.responseText;
                            // console.log(xhr.responseText);
                        }
                    };

                    xhr.send("supplier_code=" + code.value);

                }
            </script>

            <script>
                document.getElementById("supplier_name").value = "<?php echo $supplier_id_data['name']; ?>";
                document.getElementById("supplier_id").value = "<?php echo $supplier_orders_data['supplier_id']; ?>";
                get_supplier_datalist(document.getElementById("supplier_id").value)
            </script>
        </div>
        <div class="column  width_50">
            <label>SUPPLIER CODE</label>
            <input class="width_80" id='supplier_order_no' readonly name='supplier_order_no' />
        </div>
        <script>
            document.getElementById("supplier_order_no").value = "<?php echo trim($supplier_orders_data['supplier_order_no']); ?>";
        </script>
        <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" name="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>
            <script>
                document.getElementById("invoice_name").value = "<?php echo $invoice_number_data['invoice_number']; ?>";
                document.getElementById("invoice_id").value = "<?php echo $supplier_orders_data['invoice_id']; ?>";
            </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>Colour & Code</th>
                <th>Description</th>
                <th>U.O.M</th>
                <th>Qty</th>
                <th>Size m</th>
                <th>Panels</th>
                <th>Amount</th>
                <th>Total</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <?php
            $supplier_orders_list_res = $db->query("supplier_order_list", "SELECT * FROM supplier_order_list WHERE supplier_order_id = '{$_GET['record_id']}'");
            $index = 1;
            while ($supplier_orders_list = $supplier_orders_list_res->fetch_assoc()) {

                // echo "SELECT * FROM stock WHERE record_id = '{$supplier_orders_list['stock_id']}'";
                $stock_data_res = $db->query("stock", "SELECT * FROM stock WHERE record_id = '{$supplier_orders_list['stock_id']}'");

                $stock_data = $stock_data_res->fetch_assoc();
                ?>
                <tr>
                    <td>
                        <input class="background_1  padding_minmal border_1"
                            style="color:white; width: 8vw;font-size: 0.9em;" id="stock_code_<?php echo $index; ?>"
                            onchange="get_unit_of_measure(this,<?php echo $index; ?>)" list="stock_list" name="stock_code[]"
                            value="<?php echo $stock_data['code']; ?>">
                    </td>
                    <td>
                        <input class=" background_1 padding_minmal border_1"
                            style="color:white;font-size: 0.9em;width:20vw;" name="stock_id[]"
                            id="stock_<?php echo $index; ?>" list="stock_list"
                            onchange="get_unit_of_measure(this,<?php echo $index; ?>)"
                            value=" <?php echo $stock_data['name']; ?>">
                    </td>
                    <td>
                        <input class="background_1  padding_minmal border_1" readonly
                            style="color:white; width: 6vw;font-size: 0.9em;" type="text"
                            id="unit_of_measure_<?php echo $index; ?>" name="unit_of_measure[]"
                            value="<?php echo $stock_data['unit_of_measure']; ?>">
                    </td>
                    <td>
                        <input class="background_1 width_90 padding_minmal border_1"
                            style="color:white; width:5vw;font-size: 0.9em;" type="number" min="0" step="0.001" name="qty[]"
                            oninput="calculateRow(this,<?php echo $index; ?>)" id="qty_<?php echo $index; ?>"
                            value="<?php echo $supplier_orders_list['qty']; ?>">
                    </td>
                    <td>
                        <input class="background_1 width_90 padding_minmal border_1"
                            style="color:white; width:5vw;font-size: 0.9em;" type="number" min="0" name="size_m[]"
                            id="sixe_m_<?php echo $index; ?>" value="<?php echo $supplier_orders_list['size_m']; ?>">
                    </td>
                    <td>
                        <input class="background_1 width_90 padding_minmal border_1"
                            style="color:white; width:5vw;font-size: 0.9em;" type="number" min="0" name="pannels[]"
                            id="pannels_<?php echo $index; ?>" value="<?php echo $supplier_orders_list['pannels']; ?>">
                    </td>
                    <td>
                        <input class="background_1 padding_minmal border_1" style="color:white;width:7vw;font-size: 0.9em;"
                            type="text" min="0" id="retail_price_<?php echo $index; ?>" step="0.01" name="price[]"
                            oninput="calculateRow(this,<?php echo $index; ?>)" inputmode="decimal"
                            value="<?php echo $stock_data['cost']; ?>">
                    </td>
                    <td>
                        <input class="background_1 padding_minmal border_1" style="color:white;width:9vw;font-size: 0.9em;"
                            type="text" id="total_<?php echo $index; ?>" readonly>
                    </td>
                    <td><button class="width_100" onclick="delete_row(this)">DELETE</button></td>
                </tr>
                <?php
                $index++;
            }

            ?>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="7" style="text-align:right;color:black;">Subtotal:</td>
                <td><input class="background_1 padding border_1" style="color:white;width:9vw;font-size: 0.9em;"
                        type="text" id="subtotal" readonly></td>
                <td></td>
            </tr>
            <tr>
                <td colspan="7" style="text-align:right;color:black;">VAT (15%):</td>
                <td><input class="background_1 padding border_1" style="color:white;width:9vw;font-size: 0.9em;"
                        type="text" id="vat" readonly>
                </td>
                <td></td>
            </tr>
            <tr>
                <td colspan="7" style="text-align:right;color:black;">Net Total:</td>
                <td><input class="background_1 padding border_1" style="color:white;width:9vw;font-size: 0.9em;"
                        type="text" id="net_total" readonly></td>
                <td></td>
            </tr>
        </tfoot>
    </table>
    <script>
        let index = <?php echo $index; ?>;
        get_supplier_datalist(document.getElementById("supplier_id").value);

        function delete_row(el) {
            var row = el.parentNode.parentNode;
            row.parentNode.removeChild(row);
            calculateTotals();
        }

        function add_row() {
            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; width: 8vw;font-size: 0.9em;" id="stock_code_${index}"
                    onchange="get_unit_of_measure(this,${index})" list="stock_list" name="stock_code[]">
            </td>
            <td>
                <input class=" background_1 padding_minmal border_1"
                    style="color:white;font-size: 0.9em;width:20vw;" name="stock_id[]" id="stock_${index}"
                    list="stock_list" onchange="get_unit_of_measure(this,${index})">
            </td>
            <td> 
                <input class="background_1 width_90 padding_minmal border_1" style="color:white; width:6vw;font-size: 0.9em;" type="text" id="unit_of_measure_${index}" name="unit_of_measure[]" oninput="get_unit_of_measure(this,${index})">
            </td>
            <td>
                <input class="background_1 width_90 padding_minmal border_1"
                    style="color:white; width:5vw;font-size: 0.9em;" type="number" min="0" value="0" step="0.001" name="qty[]" id="qty_${index}"
                    oninput="calculateRow(this,${index})">
            </td>
            <td>
                <input class="background_1 width_90 padding_minmal border_1"
                    style="color:white; width:5vw;font-size: 0.9em;" type="number" min="0" value="0"
                    name="size_m[]" id="size_m_${index}">
            </td>
            <td>
                <input class="background_1 width_90 padding_minmal border_1"
                    style="color:white; width:5vw;font-size: 0.9em;" type="number" min="0" value="0"    
                    name="pannels[]" id="pannels_${index}">
            </td>
            <td>
                <input class="background_1 padding_minmal border_1" style="color:white;width:7vw;font-size: 0.9em;"
                    type="text" min="0" value="0" id="retail_price_${index}" step="0.01" name="price[]"
                    oninput="calculateRow(this,${index})">
            </td>
            <td>
                <input class="background_1 padding_minmal border_1" style="color:white;width:9vw;font-size: 0.9em;"
                    type="text" id="total_${index}" readonly>
            </td>
            <td>
                <button class="width_100" onclick="delete_row(this)">DELETE</button>
            </td>
            
            </tr>
            `;
            index++;
        }

        function change_to_currency(input) {
            let value = parseFloat(
                input.value
                    .replace(/R/g, '')
                    .replace(/\s/g, '')
                    .replace(/\./g, '') // replace dot with empty string
                    .replace(/,/g, '.') // replace comma with dot
                    .replace(/[^\d\.\-]/g, '') // keep digits, dot, and minus only
            );

            if (isNaN(value)) value = 0;

            // Use a simple condition to show -R for negative numbers
            if (value < 0) {
                input.value = '-R ' + new Intl.NumberFormat('en-ZA', {
                    style: 'currency',
                    currency: 'ZAR',
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }).format(Math.abs(value)).replace('R', '').trim();
            } else {
                input.value = new Intl.NumberFormat('en-ZA', {
                    style: 'currency',
                    currency: 'ZAR',
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                }).format(value);
            }

            input.value = input.value.replace(",", ".");
        }

        function delete_row(el) {
            var row = el.parentNode.parentNode;
            row.parentNode.removeChild(row);
            calculateTotals();
        }

        function get_unit_of_measure(input, i) {
            data = input.value.split("~");
            // alert(data);
            document.getElementById("unit_of_measure_" + i).value = data[2];
            document.getElementById("stock_code_" + i).value = data[0];
            if (data[0] == "DISCOUNT") {
                document.getElementById("retail_price_" + i).value = "-R 0.00";
                document.getElementById("qty_" + i).value = "1";
            }
            let price = parseFloat(data[3].replace(/ /g, "").replace(/[^\d.]/g, '.')) || 0;
            console.log(data[3]);
            current_price = new Intl.NumberFormat('en-ZA', {
                style: 'currency',
                currency: 'ZAR',
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
                useGrouping: true,
                notation: 'standard',
                currencyDisplay: 'symbol',
                currencySign: 'standard',
                minimumSignificantDigits: 1
            }).format(price);
            // alert(price);
            document.getElementById("retail_price_" + i).value = current_price;
            document.getElementById("retail_price_" + i).value = document.getElementById("retail_price_" + i).value.replace(",", ".");
            document.getElementById("stock_" + i).value = data[1];

        }

        function calculateRow() {
            ind = index;
            for (let i = 1; i <= ind - 1; i++) {
                qty = parseFloat(document.getElementById("qty_" + i).value) || 0;
                console.log(qty);
                price = parseFloat(document.getElementById("retail_price_" + i).value.replace(/[^\d.-]/g, '')) || 0;
                console.log(price);
                let total = qty * price;
                console.log(total);
                document.getElementById("total_" + i).value = new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(total);
                document.getElementById("total_" + i).value = document.getElementById("total_" + i).value.replace(",", ".");
                calculateTotals();
            }

        }

        function calculateTotals() {
            let totals = document.querySelectorAll("[id^='total_']");
            let subtotal = 0;
            totals.forEach(t => {
                amount = t.value.replace(/[^\d\.\-]/g, '');
                subtotal += parseFloat(amount) || 0;
            });
            let vat = subtotal * 0.15;
            let net_total = subtotal + vat;

            document.getElementById("subtotal").value = new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(subtotal);
            document.getElementById("subtotal").value = document.getElementById("subtotal").value.replace(",", ".");
            document.getElementById("vat").value = new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(vat);
            document.getElementById("vat").value = document.getElementById("vat").value.replace(",", ".");
            document.getElementById("net_total").value = new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(net_total);
            document.getElementById("net_total").value = document.getElementById("net_total").value.replace(",", ".");
        }
        calculateRow();
    </script>
    <br>
    <button class="width_90" onclick="save('update_supplier_orders.php')">SAVE</button>
    <br>
</div>

<script>
    function open_pdf(url) {
        window.open(url);
    }

    function save(url) {
        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>