<?php

include "../../classes/autoload.php";

$terms_res = $db->query("terms", "SELECT * FROM terms WHERE document_type = 'quote'");
$terms_by_type = []; $notes_by_type = [];
while ($t = $terms_res->fetch_assoc()) {
    $terms_by_type[$t['order_type']] = $t['terms'];
    $notes_by_type[$t['order_type']] = $t['notes'];
}
$supply_install_terms = $terms_by_type['SUPPLY & INSTALL'] ?? '';
$supply_terms         = $terms_by_type['SUPPLY'] ?? '';
$delivery_terms       = $terms_by_type['SUPPLY & DELIVERY'] ?? '';
$supply_install_notes = $notes_by_type['SUPPLY & INSTALL'] ?? '';
$supply_notes         = $notes_by_type['SUPPLY'] ?? '';
$delivery_notes       = $notes_by_type['SUPPLY & DELIVERY'] ?? '';

$html = new html("");

$app = new inner_app();
$app->quick_bar("/app/quotes/");
$app->app_start();
$function->get_stock_datalist("stock_list");

$quote_no_res = $db->query("quotes", "SELECT * FROM quotes WHERE 1 ORDER BY record_id DESC LIMIT 1");
if ($quote_no_res->num_rows == 0) {
    $quote_no = 1;
} else {
    $quote_no = $quote_no_res->fetch_assoc();
    $quote_no = $quote_no['quote_number'] + 1;
}



?>

<div class="column width_90 background_1 border_radius">
    <h1>QUOTE NO. <?php echo $quote_no ?></h1>
    <div class="row column_gap_2 width_80">
        <div class="column  width_50">
            <input type="text" hidden name="quote_number" value="<?php echo $quote_no ?>">
            <?php
            $function->get_clients_datalist('clients_list');
            ?>
            <label>CLIENT</label>
            <input class="width_80" id='client_id' hidden name='client_id' />
            <input class="width_80" id='client_name' required name='client_name' autocomplete="off"
                onchange="get_client_name(this)" list="clients_list" />
            <script>
                function get_client_name(el) {
                    let selected = el.value;
                    let options = document.getElementById("clients_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("client_id").value = data[1];
                        document.getElementById("client_name").value = data[0];
                    } else {
                        alert("Please select a client from the list");
                        document.getElementById("client_id").value = '';
                        el.value = "";
                    }
                }
            </script>
        </div>
        <div class="column  width_50">
            <label>ORDER TYPE</label>
            <select name="order_type" onchange="change_terms(this.value)" id="order_type">
                <option></option>
                <option>SUPPLY</option>
                <option>SUPPLY & INSTALL</option>
                <option>SUPPLY & DELIVERY</option>
            </select>

        </div>
    </div>
    <div class="row column_gap_2 width_80" id="additional_delivery_details" style="display:none;">
        <div class="column  width_100">
            <label>ADDITIONAL DELIVERY DETAILS</label>
            <textarea name="additional_delivery_details" class="width_100" rows="2"></textarea>
        </div>
    </div>
    <div class="row column_gap_2 width_80" style="display:none;">
        <div class="column  width_100">
            <label>AREA</label>
            <textarea name="area" class="width_100" rows="2"></textarea>
        </div>
    </div>

    <div class="row column_gap_2 width_80">
        <div class="column  width_100">
            <label>SUBJECT</label>
            <textarea name="subject" class="width_100"
                rows="4">PLEASE ALLOW TWO WEEKS FOR DELIVERY OF STOCK AFTER DEPOSIT IS DONE</textarea>
        </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>
            <tr>
                <td>
                    <input class="background_1  padding_minmal border_1"
                        style="color:white; width: 8vw;font-size: 0.9em;" id="stock_code_1"
                        onchange="get_unit_of_measure(this,1)" 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_1"
                        list="stock_list" onchange="get_unit_of_measure(this,1)">
                </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_1"
                        name="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" value="0" name="qty[]"
                        oninput="calculateRow(this,1)" id="qty_1">
                </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[]">
                </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[]">
                </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_1" step="0.01" name="price[]"
                        oninput="calculateRow(this,1)" onchange="change_to_currency(this)">
                </td>
                <td>
                    <input class="background_1 padding_minmal border_1" style="color:white;width:9vw;font-size: 0.9em;"
                        type="text" id="total_1" readonly>
                </td>
                <td><button class="width_100" onclick="delete_row(this)">DELETE</button></td>
            </tr>
        </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>
    <div class="row column_gap_2 width_80">
        <div class="column  width_100">
            <label>IMPORTANT NOTES</label>
            <textarea name="note" id="note" class="width_100" rows="10"></textarea>

        </div>
    </div>
    <div class="row column_gap_2 width_80">
        <div class="column  width_100">
            <label>TERMS</label>
            <textarea name="terms" id="terms" class="width_100" rows="8"></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; 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" 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[]">
            </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[]">
            </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})"  onchange="change_to_currency(this)">
            </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>
            `;
        }
        function change_to_currency(input) {
            let value = parseFloat(
                input.value
                    .replace(/R/g, '')
                    .replace(/\s/g, '')
                    .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'
                }).format(Math.abs(value)).replace('R', '').trim();
            } else {
                input.value = new Intl.NumberFormat('en-ZA', {
                    style: 'currency',
                    currency: 'ZAR'
                }).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("~");
            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]);
            console.log(price);
            document.getElementById("retail_price_" + i).value = new Intl.NumberFormat('en-ZA', { style: 'currency', currency: 'ZAR' }).format(price);
            document.getElementById("retail_price_" + i).value = document.getElementById("retail_price_" + i).value.replace(",", ".");
            document.getElementById("stock_" + i).value = data[1];

        }
        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.replace(/[^\d\-\.]/g, '')) || 0;
            let total = qty * price;
            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(",", ".");
        }
    </script>



    <textarea id="supply_install_terms_data" style="display:none"><?php echo htmlspecialchars($supply_install_terms); ?></textarea>
    <textarea id="supply_terms_data" style="display:none"><?php echo htmlspecialchars($supply_terms); ?></textarea>
    <textarea id="delivery_terms_data" style="display:none"><?php echo htmlspecialchars($delivery_terms); ?></textarea>
    <textarea id="supply_install_notes_data" style="display:none"><?php echo htmlspecialchars($supply_install_notes); ?></textarea>
    <textarea id="supply_notes_data" style="display:none"><?php echo htmlspecialchars($supply_notes); ?></textarea>
    <textarea id="delivery_notes_data" style="display:none"><?php echo htmlspecialchars($delivery_notes); ?></textarea>
    <br>
    <button class="width_90" onclick="save('save_quotes.php')">SAVE</button>
    <br>
    <button class="width_90" onclick="window.location.href='../../default_app_data/terms/edit_quote_terms.php'">EDIT DEFAULT QUOTE TERMS</button>
    <br>

</div>

<script>
    function save(url) {
        client_id = document.getElementById('client_id').value
        order_type = document.getElementById('order_type').value
        if (client_id == '' || order_type == '') {
            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>
<script>
    function change_terms(val) {
        var siTerms  = document.getElementById("supply_install_terms_data").value;
        var supTerms = document.getElementById("supply_terms_data").value;
        var delTerms = document.getElementById("delivery_terms_data").value;
        var siNotes  = document.getElementById("supply_install_notes_data").value;
        var supNotes = document.getElementById("supply_notes_data").value;
        var delNotes = document.getElementById("delivery_notes_data").value;
        if (val == "SUPPLY & INSTALL") {
            document.getElementById("additional_delivery_details").style.display = "none";
            document.getElementById("note").value = siTerms;
            document.getElementById("terms").value = siNotes;
        } else if (val == "SUPPLY & DELIVERY") {
            document.getElementById("additional_delivery_details").style.display = "block";
            document.getElementById("note").value = delTerms;
            document.getElementById("terms").value = delNotes;
        } else {
            document.getElementById("additional_delivery_details").style.display = "block";
            document.getElementById("note").value = supTerms;
            document.getElementById("terms").value = supNotes;
        }
    }
    window.addEventListener('load', function() {
        var val = document.getElementById('order_type').value;
        if (val) change_terms(val);
    });
</script>