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

// $html->check_user_type("ADMIN");

$db = new db_safeguard();
$results = $db->query("stock", "SELECT * FROM stock WHERE 1");
$costs_res = $db->query("costs", "SELECT * FROM costs WHERE record_id  = {$_GET['record_id']}");
$costs = $costs_res->fetch_assoc();

if ($costs['jc_number'] != "") {
    $jobcard_res_1 = $db->query("job_cards", "SELECT * FROM job_cards WHERE jc_number = '{$costs['jc_number']}'");

    if ($jobcard_res_1->num_rows == 0) {

        $jobcard_res_2 = $db->query("job_cards_tech", "SELECT * FROM job_cards_tech WHERE jc_number = '{$costs['jc_number']}'");
        if ($jobcard_res_2->num_rows == 0) {

            $jobcard_res_2 = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE `name` = '{$costs['jc_number']}'");
            $accounts = $jobcard_res_2->fetch_assoc();
            $job_card_name = $accounts['name'];
        } else {

            $tech = $jobcard_res_2->fetch_assoc();
            $job_card_name = $tech['company_name'];

        }
    } else {
        $project = $jobcard_res_1->fetch_assoc();
        $job_card_name = $project['project_name'];

    }
} else {
    $job_card_name = $project['N/A'];

}

$record_id = new input();
$record_id->name("record_id");
$record_id->id("record_id");
$record_id->type("hidden");
$record_id->readonly();
$record_id->required();
$record_id->value($_GET['record_id']);


$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("job_card_account_id");
$jobcard_account->id("job_card_account_id");
$jobcard_account->class("search_inputs");
$jobcard_account->add_option("", "JOB CARD ACCOUNT");
$job_card_account_res = $db->query("job_card_accounts", "SELECT * FROM job_card_accounts WHERE `status` = 1");
while ($job_card_account = $job_card_account_res->fetch_assoc()) {
    $jobcard_account->add_option($job_card_account['record_id'], $job_card_account['name'] . " : " . $job_card_account['description']);
}
$jobcard_account->style("width: 80%;");
$jobcard_account->value_from_db("costs", "job_card_account_id", "record_id = {$_GET['record_id']}");

$name = new input();
$name->name("name");
$name->id("name");
$name->class("search_inputs");
$name->placeholder("NAME");
$name->type("text");
$name->style("width: 80%;");
$name->value_from_db("costs", "name", "record_id = {$_GET['record_id']}");

$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->value_from_db("costs", "jc_number", "record_id = {$_GET['record_id']}");
$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->value($job_card_name);
$jc_name->style("width: 80%;");
$jc_name->readonly();


$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%;");
$order_date->value_from_db("costs", "date_time_created", "record_id = {$_GET['record_id']}");


?>


<form action="update_cost.php" method="POST">

    <div>
        <div class="form_down">
            <h1>EDIT COST</h1>
            <div class="row">
                <div class="row" style="flex-direction: column;width:50%;">
                    <?php
                    $record_id->add();
                    $name->add();
                    $order_date->add();

                    ?>
                </div>
                <div class="row" style="flex-direction: column;width:50%;">
                    <?php

                    $jobcard_account->add();
                    $jc_number->add();
                    $jc_name->add();
                    ?>
                    <input type="number" value="<?php echo $costs['include_vat']; ?>" id="include_vat" hidden
                        name="include_vat">

                </div>
            </div>

            <table id="order_table" style="font-size:2vw">
                <tr>
                    <th>Item Description (double click to clear)</th>
                    <th>Quantity</th>
                    <th>Cost Price Ex.</th>
                    <th>Action</th>
                </tr>

                <?php
                $index = 0;
                $order_items_res = $db->query("cost_items", "SELECT * FROM cost_items WHERE cost_id = {$_GET['record_id']} ORDER BY record_id ASC");
                while ($order_item = $order_items_res->fetch_assoc()) {
                    echo "<tr>";
                    echo "<td><input type='text' class='inputs'  autocomplete='off' ondblclick='this.value=\"\";'  style='width: 35vw;overflow-wrap: break-word; font-size:0.5em;' name='item_description$index' onchange='extract_price($index)' id='item_description$index' value='" . $order_item['name'] . "'></td>";
                    echo "<td><input type='number' onchange='calculate_total()' step='0.001' style='width: 10vw;' class='inputs' name='quantity$index' id='quantity$index' value='" . $order_item['quantity'] . "'></td>";
                    echo "<td><input type='number' onchange='calculate_total()' step='0.001' style='width: 15vw;' class='inputs' name='cost_price$index' id='cost_price$index' value='" . $order_item['purchase_price_ex'] . "'></td>";
                    echo "<td><button class='select_button' id='delete_row$index' onclick='delete_row($index)'>Delete</button></td>";
                    echo "</tr>";
                    $index++;
                }


                ?>
                <tbody id="order_table_body">
                </tbody>
            </table>
            <button type="submit" class="select_button" style="height:2vw;font-size:1.5vw" id="add_row" s>Add
                Row</button>
            <input type="text" id="counter" value="<?php echo $index; ?>" hidden name="counter">
            <script>
                document.getElementById("add_row").addEventListener("click", function () {
                    event.preventDefault();
                    counter = document.getElementById('counter').value;
                    var row = document.createElement('tr');
                    row.innerHTML = `
            <td>
            <input type="text" class="inputs" style='width: 35vw;' name="item_description`+ counter + `" onchange="extract_price(` + counter + `)" id="item_description` + counter + `" autocomplete="off"  ondblclick="this.value='';">
            </td>
          
            <td>
                <input type="number" step="0.01" onchange="calculate_total()" style='width: 10vw;' class="inputs" name="quantity`+ counter + `"
                    id="quantity` + counter + `" value="">
            </td>
        <td>
            <input type="number" step="0.01" onchange="calculate_total()" class="inputs" style='width: 15vw;' 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_body').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>
            <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;

            if (document.getElementById('include_vat').value == 1) {
                var vat_amount = 1.15;
                document.getElementById("vat_calculation").checked = true;
            } else {
                var vat_amount = 1;
                document.getElementById("vat_calculation").checked = false;

            }
            function calculate_vat(input) {
                if (vat_amount == 1.15) {
                    vat_amount = 1;
                    document.getElementById("include_vat").value = 0;
                } else {
                    vat_amount = 1.15;
                    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);
            }

            calculate_total();


            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>
    </div>
</form>
