<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$html->prevent_enter_script();
// $html->check_user_type("ADMIN");

$db = new db_safeguard();
$results = $db->query("stock", "SELECT * FROM stock WHERE stock_type = 0");



$jobcard_numbers_res = $db->query("job_cards", "SELECT * FROM job_cards WHERE 1");
echo "<datalist id='job_cards_list'>";
while ($jobcard = $jobcard_numbers_res->fetch_assoc()) {
    echo "<option value='" . $jobcard['jc_number'] . "-" . $jobcard['project_name'] . "'>" . $jobcard['jc_number'] . "-" . $jobcard['project_name'] . "</option>";
}

$jobcard_numbers_res = $db->query("job_cards_tech", "SELECT * FROM job_cards_tech WHERE 1");
while ($jobcard = $jobcard_numbers_res->fetch_assoc()) {
    echo "<option value='" . $jobcard['jc_number'] . "-" . $jobcard['company_name'] . "'>" . $jobcard['jc_number'] . "-" . $jobcard['company_name'] . "</option>";
}
echo "</datalist>";

$jobcard_account = new select();
$jobcard_account->name("jobcard_acount_id");
$jobcard_account->id("jobcard_acount_id");
$jobcard_account->class("search_inputs");
$jobcard_account->add_option("", "JOB CARD ACCOUNT");
$jobcard_account->fill_from_db("job_card_accounts", "record_id", "name");
$jobcard_account->style("width: 80%;");

$po_number = new input();
$po_number->name("po_number");
$po_number->id("po_number");
$po_number->class("search_inputs");
$po_number->placeholder("PO Number");
$po_number->type("text");
$po_number->style("width: 80%;");

$jc_number = new input();
$jc_number->name("jc_number");
$jc_number->id("jc_number");
$jc_number->class("search_inputs");
$jc_number->placeholder("JC Number");
$jc_number->type("text");
$jc_number->datalist("job_cards_list");
$jc_number->onchange("split_jc_and_name(this)");
$jc_number->style("width: 80%;");

$jc_name = new input();
$jc_name->name("");
$jc_name->id("");
$jc_name->class("search_inputs job_card_name");
$jc_name->placeholder("");
$jc_name->type("text");
$jc_name->style("width: 80%;");
$jc_name->readonly();


$supplier = new select();
$supplier->name("supplier_id");
$supplier->id("supplier_id");
$supplier->class("search_inputs");
$supplier->add_option("", "Supplier");
$supplier->fill_from_db("suppliers", "record_id", "name");
$supplier->style("width: 80%;");

$order_date = new input();
$order_date->name("order_date");
$order_date->id("order_date");
$order_date->class("search_inputs");
$order_date->type("datetime-local");
$order_date->value(date("Y-m-d H:i", strtotime("+2 hours")));
$order_date->style("width: 80%;");

$ordered_for = new select();
$ordered_for->name("user_id");
$ordered_for->id("user_id");
$ordered_for->class("search_inputs");
$ordered_for->add_option("", "Order For");
$ordered_for->fill_from_db("users", "record_id", "username");
$ordered_for->style("width: 80%;");

$ordered_by = new select();
$ordered_by->name("user_created");
$ordered_by->id("user_created");
$ordered_by->class("search_inputs");
$ordered_by->add_option("", "Order By");
// $ordered_by->fill_from_db("users", "record_id", "username");
$ordered_by->add_option("3", "Kaylynn");
$ordered_by->add_option("12", "Chanay");
$ordered_by->add_option("19", "Claurika");
$ordered_by->style("width: 80%;");

$datalist = "";
while ($result = $results->fetch_assoc()) {
    $datalist .= "<option value='" . $result['record_id'] . " | " . $result['description'] . " | " . $result['cost_price'] . "'></option>";
}
$results = $db->query("stock", "SELECT * FROM stock WHERE stock_type = 1");

$datalist_non_stock = "";
while ($result = $results->fetch_assoc()) {
    $datalist_non_stock .= "<option value='" . $result['record_id'] . " | " . $result['description'] . " | " . $result['cost_price'] . "'></option>";
}
$results = $db->query("stock", "SELECT * FROM stock WHERE stock_type = 2");

$datalist_units = "";
while ($result = $results->fetch_assoc()) {
    $datalist_units .= "<option value='" . $result['record_id'] . " | " . $result['description'] . " | " . $result['cost_price'] . "'></option>";
}
?>


<form action="save_order.php" method="POST">
    <datalist id="stock">
        <?php
        echo $datalist;
        ?>
    </datalist>
    <datalist id="non_stock">
        <?php
        echo $datalist_non_stock; ?>
    </datalist>
    <datalist id="units">
        <?php
        echo $datalist_units; ?>
    </datalist>
    <div class="form_down">
        <h1>CREATE ORDER</h1>
        <div class="row">
            <div class="row" style="flex-direction: column;width:50%;">
                <?php
                $po_number->add();
                $jobcard_account->add();
                $jc_number->add();
                $jc_name->add();
                $supplier->add();
                ?>
            </div>
            <div class="row" style="flex-direction: column;width:50%;">
                <?php
                $order_date->add();
                $ordered_for->add();
                $ordered_by->add();
                ?>
                <input type="number" value="0" id="include_vat" hidden name="include_vat">
                <select name="warrenty" id="warrenty" class="search_inputs" style="width:80%;">
                    <option value="0">WARRANTY</option>
                    <option value="1">YES</option>
                    <option value="0">NO</option>
                </select>
            </div>
        </div>

        <table id="order_table" style="font-size:2vw">
            <tr>
                <th>Not Stock</th>
                <th>Item Description (double click to clear)</th>
                <th>Quantity</th>
                <th>Cost Price Ex.</th>
                <th>Action</th>
            </tr>
            <tbody id="order_table_body">
            </tbody>
        </table>
        <button type="submit" class="select_button" style="height:2vw;font-size:1.5vw" id="add_row">Add Row</button>
        <input type="text" id="counter" value="0" hidden name="counter">
        <script>
            document.getElementById("add_row").addEventListener("click", function () {
                event.preventDefault();
                counter = document.getElementById('counter').value;
                var table = document.getElementById('order_table');
                var row = table.insertRow(-1);
                row.innerHTML = `
            <td>
            <select id='stock_type_`+ counter + `' class='inputs' name='stock_type_` + counter + `' onchange="toggleStockList(` + counter + `)">\
            <option></option>
            <option value=0>STOCK</option>
            <option value=1>NON STOCK</option>
            <option value=2>UNITS</option>
            <option value=3>NO COUNTABLE</option>
            </select>
            </td>
            <td>
      <input type="text" class="inputs" name="item_description`+ counter + `" style='width: 35vw; font-size:0.5em; height: 3em;' id="item_description` + counter + `" onchange="extract_price(` + counter + `)" autocomplete="off" list="" ondblclick="this.value='';">
            </td>
          
            <td>
            <input type="number" onchange="calculate_total()" step="0.001" style='width: 10vw;' class="inputs" name="quantity`+ counter + `"
            id="quantity` + counter + `" value="">
            </td>
            <td>
                <input type="number" onchange="calculate_total()" step="0.001" style='width: 15vw;' class="inputs" name="cost_price`+ counter + `"
                    id="cost_price` + counter + `" value="">
            </td>
        <td>
            <button class="select_button" id="delete_row`+ counter + `"
                onclick="delete_row(` + counter + `)">Delete</button>
        </td>
        `;
                document.getElementById('counter').value = parseInt(document.getElementById('counter').value) + 1;
                document.getElementById('order_table').appendChild(row);
                counter++;
            });

            function delete_row(counter) {
                event.preventDefault();

                document.getElementById("stock_type_" + counter).hidden = true;
                document.getElementById("stock_type_" + counter).checked = false;
                document.getElementById("item_description" + counter).hidden = true;
                document.getElementById("item_description" + counter).value = "";
                document.getElementById("cost_price" + counter).hidden = true;
                document.getElementById("cost_price" + counter).value = "0";
                document.getElementById("quantity" + counter).hidden = true;
                document.getElementById("quantity" + counter).value = "0";
                document.getElementById("delete_row" + counter).hidden = true;
                calculate_total();

            }

            function extract_price(counter) {
                if (document.getElementById('item_description' + counter).value.includes("|")) {
                    var input = document.getElementById('item_description' + counter);
                    var parts = input.value.split(' | ');
                    document.getElementById('cost_price' + counter).value = parts[2];
                    input.value = parts[0] + " | " + parts[1];
                }
            }
        </script>

        <script>
            function toggleStockList(counter) {
                var select = document.getElementById('stock_type_' + counter);
                var input = document.getElementById('item_description' + counter);
                input.value = "";

                if (select.value == 0) {
                    input.removeAttribute('list');
                    input.setAttribute('list', 'stock');
                } else if (select.value == 1) {
                    input.removeAttribute('list');

                    input.setAttribute('list', 'non_stock');
                } else {
                    input.removeAttribute('list');

                    input.setAttribute('list', 'units');

                }
            }
        </script>
    </div>
    <div style="width: 100%; margin-top: 5vh;">
        <div class="row" style="width=100%;text-align: center;">
            <div class="column">
                <span style="font-weight:bold;">INCLUDE VAT CALCULATIONS</span>
                <input type="checkbox" name="vat_calculation" checked id="vat_calculation"
                    onclick="calculate_vat(this)">
            </div>
            <div class="column">
                <span style="font-weight:bold;">CLOSE ORDER AFTER CREATE</span>
                <input type="checkbox" name="close_order" id="close_order">
            </div>
        </div>
        <br>
        <br>
        <br>
        <div class="row">
            <div class="column">
                <span style="font-weight:bold;">Total Ex Vat: </span>
                <input type="number" id="total_ex_vat" step="0.001" class="inputs" value="0.00">
            </div>
            <div class="column">
                <span style="font-weight:bold;">Total Inc Vat: </span>
                <input type="number" id="total_inc_vat" step="0.001" value="0.00" class="inputs">
            </div>
            <div class="column">
                <input type="submit" class="select_button" id="submit" value="save">
            </div>
        </div>
    </div>
    <script>
        var vat_amount = 1.15;
        function calculate_vat(input) {
            if (vat_amount == 1.15) {
                vat_amount = 1;
                input.checked = false;
                document.getElementById("include_vat").value = 0;
            } else {
                vat_amount = 1.15;
                input.checked = true;
                document.getElementById("include_vat").value = 1;

            }
            calculate_total();
        }
        function calculate_total() {
            var total_ex_vat = 0;
            var total_inc_vat = 0;
            for (var i = 0; i < document.getElementById('counter').value; i++) {
                var cost_price = document.getElementById("cost_price" + i).value;
                var quantity = document.getElementById("quantity" + i).value;
                total_ex_vat += cost_price * quantity;
                total_inc_vat += cost_price * quantity * vat_amount;
                console.log(total_ex_vat);
            }
            document.getElementById("total_ex_vat").value = Number(total_ex_vat).toFixed(3);
            document.getElementById("total_inc_vat").value = Number(total_inc_vat).toFixed(3);
        }


        function split_jc_and_name(input) {
            if (input.value.includes("-")) {
                var parts = input.value.split('-');
                document.getElementById('jc_number').value = parts[0];
                document.getElementsByClassName('job_card_name')[0].value = parts[1];
            } else {
                document.getElementById('jc_number').value = "";
                document.getElementsByClassName('job_card_name')[0].value = "";
            }

        }
    </script>
</form>