<?php

include "../../classes/app.class.php";
$app = new app();
$db = new DBMain();
$quote_id = $_GET['record_id']; // Assuming quote_id is passed as a query param
$quote = $db->get_quote_by_id($quote_id); // Assuming this function retrieves quote details by id
?>
<div class='container flex_container'>
    <!-- <h1>EDIT QUOTE</h1> -->
    <hr>
    <div class="container flex_container_content" style="border: 1px solid black;padding: 2%; border-radius: 5px;">
        <div class='flex_container'>
            <label>Quote Number:</label>
            <input style='width:100%;' id='quote_number' value='<?php echo $quote['quote_number']; ?>' readonly />
            <input style='width:100%; display: none;' id='record_id' value='<?php echo $quote['record_id']; ?>'
                readonly />
            <label>Quote Description:</label>
            <textarea style='width:100%;' id='quote_description' oninput="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $quote['description']; ?></textarea>
            <script>
                                    auto_adjust();
                                    function auto_adjust() {
                                        document.getElementById('quote_description').style.height = 'auto'; document.getElementById('quote_description').style.height = document.getElementById('quote_description').scrollHeight + 'px';
                                    }</script>
            <label>Client:</label>
            <select style='width:100%;' id='client'>
                <?php echo $db->get_clients_in_dropdown(); ?>
                <script> document.getElementById('client').value = '<?php echo $quote['client_id']; ?>';</script>

            </select>
        </div>
        <div class='flex_container'>
            <label>Items:</label>
            <table id='quote_items' style='width:100%'>
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Amount</th>
                        <th>Price</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $items = explode("|", $quote['items']);
                    $prices = explode("|", $quote['prices']);
                    $amounts = explode("|", $quote['amount']);
                    $count = count($items);
                    $i = 0;
                    foreach ($items as $item): ?>
                        <tr>
                            <td>
                            <textarea class='item' id="items<?php echo $i; ?>"
                                    style='resize: vertical; overflow: hidden; word-wrap: break-word;width:25vw; line-height: 1.5;'
                                    onchange='update_total()' rows="1"
                                    oninput="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';"><?php echo $item; ?></textarea>
                                <script>
                                    auto_adjust();
                                    function auto_adjust() {
                                        document.getElementById('items<?php echo $i; ?>').style.height = 'auto'; document.getElementById('items<?php echo $i; ?>').style.height = document.getElementById('items<?php echo $i; ?>').scrollHeight + 'px';
                                    }</script>
                            </td>
                            <td><input type='number' class='amount' style='width:5vw;' value='<?php echo $amounts[$i]; ?>'
                                    onchange='update_total()'></td>
                            <td><input type='number' class='price' style='width:8vw;' step="0.01" value='<?php echo $prices[$i]; ?>'
                                    onchange='update_total()'></td>
                            <td><button onclick="remove_line(this)">Remove</button></td>
                        </tr>
                        <?php $i++; endforeach; ?>

                </tbody>
            </table>
            <button onclick="add_line()">Add Line</button>
        </div>
        <div class='flex_container'>
            <label>Total:</label>
            <input type='number' id='total' readonly>
            <br>
            <label>VAT (15%):</label>
            <input type='number' id='vat' readonly>
            <br>
            <label>Total with VAT:</label>
            <input type='number' id='total_with_vat' readonly>
        </div>
    </div>
    <br>
    <button onclick="send_quote()" id='update_quote_btn'>SEND</button>
    <button onclick="update_return_admin_quote()" id='update_quote_btn'>SAVE & RETURN TO ADMIN</button>
    <button onclick="update_return_stock_quote()" id='update_quote_btn'>SAVE & RETURN TO STOCK</button>
</div>

<script>
    function add_line() {
        table = document.getElementById('quote_items');
        row = table.insertRow(-1);
        cell1 = row.insertCell(0);
        cell2 = row.insertCell(1);
        cell3 = row.insertCell(2);
        cell4 = row.insertCell(3);
        cell1.innerHTML = "  <textarea class='item' style='resize: vertical; overflow: hidden; word-wrap: break-word;width:25vw; line-height: 1.5;' onchange='update_total()' rows='1' oninput=\"this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px';\"></textarea>";
        cell2.innerHTML = "<input type='number' style='width:5vw;' class='amount' onchange='update_total()'>";
        cell3.innerHTML = "<input type='number' style='width:8vw;' step='0.01'  class='price' onchange='update_total()'>";
        cell4.innerHTML = "<button onclick=\"remove_line(this)\">Remove</button>";
        update_total();
    }


    function remove_line(obj) {
        row = obj.parentNode.parentNode;
        table = document.getElementById('quote_items');
        table.deleteRow(row.rowIndex);
        update_total();
    }
    update_total();
    function update_total() {
        total = 0;
        prices = document.getElementsByClassName('price');
        amounts = document.getElementsByClassName('amount');
        for (var i = 0; i < prices.length; i++) {
            total += Number(prices[i].value) * Number(amounts[i].value);
        }
        vat = total * 0.15;
        total_with_vat = total + vat;
        document.getElementById('total').value = total.toFixed(2);
        document.getElementById('vat').value = vat.toFixed(2);
        document.getElementById('total_with_vat').value = total_with_vat.toFixed(2);
    }

    function update_return_admin_quote() {
        quote_number = document.getElementById('quote_number').value;
        description = document.getElementById('quote_description').value;
        client_id = document.getElementById('client').value;
        items = document.getElementsByClassName('item');
        prices = document.getElementsByClassName('price');
        amounts = document.getElementsByClassName('amount');
        data = {
            record_id: document.getElementById('record_id').value,
            quote_number: quote_number,
            description: description,
            client_id: client_id,
            items: [],
            prices: [],
            amounts: [],
            stock: 1,
            admin: 0,
        };
        for (var i = 0; i < items.length; i++) {
            data.items.push(items[i].value);
            data.prices.push(prices[i].value);
            data.amounts.push(amounts[i].value);
        }
        var xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
            console.log(this.responseText);
            // alert(this.responseText);
            if (this.responseText == 1) {
                // alert('Quote updated successfully');
                window.location.href = "quotes.php";

            }
        }
        xhttp.open("POST", '../../ajax/quote/update_quote.php', true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("data=" + JSON.stringify(data));
    }

    function update_return_stock_quote() {
        quote_number = document.getElementById('quote_number').value;
        description = document.getElementById('quote_description').value;
        client_id = document.getElementById('client').value;
        items = document.getElementsByClassName('item');
        prices = document.getElementsByClassName('price');
        amounts = document.getElementsByClassName('amount');
        data = {
            record_id: document.getElementById('record_id').value,
            quote_number: quote_number,
            description: description,
            client_id: client_id,
            items: [],
            prices: [],
            amounts: [],
            stock: 0,
            admin: 0,
        };
        for (var i = 0; i < items.length; i++) {
            data.items.push(items[i].value);
            data.prices.push(prices[i].value);
            data.amounts.push(amounts[i].value);
        }
        var xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
            console.log(this.responseText);
            // alert(this.responseText);
            if (this.responseText == 1) {
                // alert('Quote updated successfully');
                window.location.href = "quotes.php";

            }
        }
        xhttp.open("POST", '../../ajax/quote/update_quote.php', true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("data=" + JSON.stringify(data));
    }

    function send_quote() {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "quote.pdf.php?type=F&record_id=" + document.getElementById('record_id').value + "", true);
        xhr.send();
        quote_number = document.getElementById('quote_number').value;
        description = document.getElementById('quote_description').value;
        client_id = document.getElementById('client').value;
        items = document.getElementsByClassName('item');
        prices = document.getElementsByClassName('price');
        amounts = document.getElementsByClassName('amount');
        data = {
            record_id: document.getElementById('record_id').value,
            quote_number: quote_number,
            description: description,
            client_id: client_id,
            items: [],
            prices: [],
            amounts: [],
            stock: 1,
            admin: 1,
            approved: 1,
            sent: 1,
        };
        for (var i = 0; i < items.length; i++) {
            data.items.push(items[i].value);
            data.prices.push(prices[i].value);
            data.amounts.push(amounts[i].value);
        }
        var xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
            console.log(this.responseText);
            // alert(this.responseText);
            if (this.responseText == "") {
                // alert('Quote updated successfully');
                window.location.href = "quotes.php";
            }
        }
        xhttp.open("POST", '../../ajax/quote/update_quote.php', true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("data=" + JSON.stringify(data));
    }
</script>