<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
// $html->check_user_type("ADMIN");
$db = new db_safeguard();

//get the last invoice number and add 1 to it
if ($db->query("invoice", "SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1") == 0) {
    $invoice_no = 1;
} else {
    $invoice_res = $db->query("invoice", "SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
    $invoice_no = $invoice_res->fetch_assoc()['invoice_id'] + 1;
}

$invoice_no_label = new label();
$invoice_no_label->for("invoice_no");
$invoice_no_label->value("INVOICE NO");

$invoice = new input();
$invoice->class("inputs");
$invoice->type("number");
$invoice->name("invoice_id");
$invoice->required();
$invoice->id("invoice_id");
$invoice->value($invoice_no);

$quantity_label = new label();
$quantity_label->for("quantity");
$quantity_label->value("QTY");

$description_label = new label();
$description_label->for("description");
$description_label->value("DESCRIPTION");

$meters_label = new label();
$meters_label->for("meters");
$meters_label->value("METERS");

$amount_qty_label = new label();
$amount_qty_label->for("amount_qty");
$amount_qty_label->value("AMOUNT");

$break_found_label = new label();
$break_found_label->for("break_found");
$break_found_label->value("BREAK FOUND ON");

$break_found = new input();
$break_found->class("inputs");
$break_found->type("number");
$break_found->name("break_found_on");
$break_found->required();
$break_found->id("break_found_on");

$estimated_liters_label = new label();
$estimated_liters_label->for("estimated_liters");
$estimated_liters_label->value("ESTIMATED LITERS (PER HOUR)");

$estimated_liters = new input();
$estimated_liters->class("inputs");
$estimated_liters->type("number");
$estimated_liters->name("estimated_liters");
$estimated_liters->required();
$estimated_liters->id("estimated_liters");

$total_amount_label = new label();
$total_amount_label->for("total_amount_label");
$total_amount_label->value("TOTAL");

$total_amount = new input();
$total_amount->class("inputs");
$total_amount->type("number");
$total_amount->name("total_amount");
$total_amount->required();
$total_amount->onchange("calculate_total()");
$total_amount->id("total_amount");
$total_amount->readonly();

$deposite_paid_label = new label();
$deposite_paid_label->for("deposite_paid");
$deposite_paid_label->value("DEPOSITE PAID");

$deposite_paid = new input();
$deposite_paid->class("inputs");
$deposite_paid->type("number");
$deposite_paid->name("deposite_amount");
$deposite_paid->required();
$deposite_paid->id("deposite_amount");
$deposite_paid->onchange("calculate_balance()");

$balance_label = new label();
$balance_label->for("balance");
$balance_label->value("BALANCE");

$balance = new input();
$balance->class("inputs");
$balance->type("number");
$balance->name("balance");
$balance->required();
$balance->id("balance");
$balance->readonly();

$total_paid_label = new label();
$total_paid_label->for("total_paid");
$total_paid_label->value("TOTAL PAID");

$total_paid = new input();
$total_paid->class("inputs");
$total_paid->type("number");
$total_paid->name("total_paid");
$total_paid->required();
$total_paid->id("total_paid");

$jobcard_id_label = new label();
$jobcard_id_label->for("jobcard_id_label");
$jobcard_id_label->value("FOR JOBCARD");

$jobcard_id = new select();
$jobcard_id->class("inputs");
$jobcard_id->name("jobcard_id");
$jobcard_id->required();
$jobcard_id->id("jobcard_id");
$jobcard_id->fill_from_db("jobcards", "record_id", "record_id");

$add_row_btn = new button();
$add_row_btn->value("ADD ROW");
$add_row_btn->onclick("add_row()");

$submit_btn = new button();
$submit_btn->value("ADD INVOICE");
// $submit_btn->onclick("add_invoice()");
$submit_btn->onclick("ajax_function()");

//create a function that gets the specific column caled type from the prices table
function type_price($type)
{
    $db = new db_safeguard();

    $type_res = $db->query("prices", "SELECT * FROM prices WHERE type = '$type'");
    $type_name = $type_res->fetch_assoc()['name'];

    return $type_name;
}

function all_types_names_ids()
{
    $db = new db_safeguard();
    $type_res = $db->query("prices", "SELECT MIN(record_id) AS record_id, type FROM prices GROUP BY type");

    $types = [];

    while ($row = $type_res->fetch_assoc()) {
        $types[] = [
            "id" => $row['record_id'],
            "name" => $row['type']
        ];
    }

    return $types;
}

function all_types_amount()
{
    $db = new db_safeguard();
    $type_res = $db->query("prices", "SELECT amount_per_liter FROM prices");

    $types = [];

    while ($row = $type_res->fetch_assoc()) {
        $types[] = [
            "amount" => $row['amount']
        ];
    }

    return $types;
}

$all_types = all_types_amount();
$all_types = all_types_names_ids();

$jc_list = "<option></option>";

$jobacard_res = $db->query("jobcards", "SELECT jc_no FROM jobcards WHERE invoice_id = 0");

while ($jocards = $jobacard_res->fetch_assoc()) {
    $jc_list = $jc_list . "<option value='{$jocards['jc_no']}'>{$jocards['jc_no']}</option>";
}

// $description_list = "<option></option>";

// $description_res = $db->query("prices", "SELECT type FROM prices GROUP BY type");

// while ($description = $description_res->fetch_assoc()) {
//     $description_list = $description_list . "<option style = 'font-size: 2vw;'>{$description['type']}</option>";
// }

?>

<div class="form_down">
    <h1>CREATE INVOICE</h1>

    <div style="display: flex; justify-content: space-between; width: 50%;">
        <div style="display:flex; flex-direction: column;">
            <?php
            $invoice_no_label->add();
            $invoice->add();
            ?>
        </div>
        <div style="display:flex; flex-direction: column;">
            <?php
            $jobcard_id_label->add();
            // $jobcard_id->add();
            ?>
            <select name="jobcard_id" id="jobcard_id" class="inputs">
                <?php echo $jc_list; ?>
            </select>
        </div>
    </div>


    <br>
    <div id="new_row" style="display: flex; flex-direction: column;border: 2px solid black;width: 80%;">
        <div style="display: flex; flex-direction: row; align-items: center;height: 4vw;">
            <div style="border-right: 2px solid black;width: 25%;">
                <?php
                $quantity_label->add();
                ?>
            </div>
            <div style="width: 25%;border-right: 2px solid black;">
                <?php
                $meters_label->add();
                ?>
            </div>
            <div style="width: 25%;border-right: 2px solid black;">
                <?php
                $description_label->add();
                ?>
            </div>
            <div style="width: 25%;">
                <?php
                $amount_qty_label->add();
                ?>
            </div>
        </div>
        <!-- <div style="display: flex; flex-direction: row; align-items: center;height: 4vw; width: 100%;">
            <div style="border: 2px solid black;width: 100%;">
                <input type="number" id="quantity_0" style = "width:100%; height: 4vw; font-size: 2vw;">
            </div>
            <div style="width: 100%;border: 2px solid black;">
                <input type="number" id="meters_0" style = "width:100%; height: 4vw; font-size: 2vw;">
            </div>
            <div style="width: 100%;border: 2px solid black;">
                <select name="description" id="description_0" style = "width:100%; height: 4vw; font-size: 2vw;">
                    <option value="" > Description</option>
                    <php
                        echo $description_list;
                    ?>
                </select>
            </div>
            <div style="width: 100%; border: 2px solid black;">
                <input type="number" id="amount_qty_0" style = "width:100%; height: 4vw; font-size: 2vw;">
            </div>
        </div> -->
    </div>

    <div style="display: flex; flex-direction: row; width: 80.4%;justify-content: space-between;">
        <div style="display: flex; flex-direction: column; justify-content: space-around; width: 50%; height: 20%;">
            <div style="display: flex; flex-direction: row; width: 100%;align-items: baseline;">
                <?php
                $break_found_label->add();
                $break_found->add();
                ?>
            </div>
            <div style="display: flex; flex-direction: row; width: 100%;align-items: baseline;">
                <?php
                $estimated_liters_label->add();
                $estimated_liters->add();
                ?>
            </div>
        </div>
        <div
            style="display: flex; flex-direction: row; border-bottom: 2px solid black; border-left: 2px solid black; border-right: 2px solid black; justify-content: space-around; width: 33%;">
            <div style="display: flex; flex-direction: column;justify-content: space-around;">
                <?php
                $total_amount_label->add();
                $deposite_paid_label->add();
                $balance_label->add();
                $total_paid_label->add();
                ?>
            </div>
            <div style="display: flex; flex-direction: column;justify-content: space-around;">

            </div>
            <div style="display: flex; flex-direction: column;justify-content: space-around;width: 100%;">
                <?php
                $total_amount->add();
                $deposite_paid->add();
                $balance->add();
                $total_paid->add();
                ?>
            </div>
        </div>
    </div>
    <?php
    $add_row_btn->add();
    ?>
    <br>
    <?php
    $submit_btn->add();

    // get all the quantity, meters, description and amount and store the values in an array
    // $invioce_data = [];

    // $i = 1;
    // while (isset($_POST["quantity_" . $i])) {
    //     $invioce_data[] = [
    //         "quantity" => $_POST["quantity_" . $i],
    //         "meters" => $_POST["meters_" . $i],
    //         "description" => $_POST["description_" . $i],
    //         "amount" => $_POST["amount_qty_" . $i]
    //     ];
    //     $i++;
    // }

    ?>
</div>

<script>
    i = 1;

    function add_row() {

        const types = <?php echo json_encode($all_types); ?>;

        var row = document.createElement("div");
        row.style.display = "flex";
        row.style.flexDirection = "row";
        row.style.borderTop = "2px solid black";
        row.style.width = "78.5vw";

        var column_1 = document.createElement("div");
        column_1.style.width = "100%";
        column_1.style.height = "4vw";

        var column_2 = document.createElement("div");
        column_2.style.width = "100%";

        var column_3 = document.createElement("div");
        column_3.style.width = "100%";

        var column_4 = document.createElement("div");
        column_4.style.width = "100%";

        var column_5 = document.createElement("div");

        var quantity = document.createElement("input");
        quantity.type = "number";
        quantity.name = "quantity" + i;
        quantity.id = "quantity" + i;
        quantity.style.width = "100%";
        quantity.style.height = "4vw";
        quantity.style.fontSize = "2vw";
        quantity.required = true;

        var meters = document.createElement("input");
        meters.type = "number";
        meters.name = "meters" + i;
        meters.id = "meters" + i;
        meters.style.width = "100%";
        meters.style.height = "4vw";
        meters.style.fontSize = "2vw";
        meters.required = true;

        var description = document.createElement("select");
        description.type = "dropdown";
        description.name = "description" + i;
        description.id = "description" + i;
        description.style.width = "100%";
        description.style.height = "4vw";
        description.style.fontSize = "2vw";
        description.required = true;

        // Default option
        let defaultOption = new Option("Description", "");
        description.add(defaultOption);

        // Populate using the `types` array from PHP
        types.forEach(function (type) {
            description.add(new Option(type.name, type.name)); // value is type name
        });

        var amount = document.createElement("input");
        amount.type = "number";
        amount.name = "amount" + i;
        amount.id = "amount" + i;
        amount.style.width = "100%";
        amount.style.height = "4vw";
        amount.style.fontSize = "2vw";
        amount.addEventListener("change", calculate_total);
        amount.required = true;

        description.addEventListener("change", function () {
            const selectedType = this.value;
        });

        var delete_btn = document.createElement("button");
        delete_btn.type = "button";
        delete_btn.innerHTML = "X";
        delete_btn.style.width = "100%";
        delete_btn.style.height = "4vw";
        delete_btn.style.fontSize = "2vw";
        delete_btn.addEventListener("click", function () {
            row.remove();
        });

        column_1.appendChild(quantity);
        column_2.appendChild(meters);
        column_3.appendChild(description);
        column_4.appendChild(amount);
        column_5.appendChild(delete_btn);

        row.appendChild(column_1);
        row.appendChild(column_2);
        row.appendChild(column_3);
        row.appendChild(column_4);
        row.appendChild(column_5);

        document.getElementById("new_row").appendChild(row);

        i++;
    }

    function get_amount() {
        const selectedType = document.getElementById("description" + i).value;
        document.getElementById("amount" + i).value = amount;
    }

    function calculate_total() {
        let total = 0;

        for (let j = 0; j < i; j++) {
            const amountInput = document.getElementById("amount" + j);
            const quantityInput = document.getElementById("quantity" + j);

            const amount = amountInput ? parseFloat(amountInput.value) : 0;
            const quantity = quantityInput ? parseFloat(quantityInput.value) : 0;

            if (!isNaN(amount) && !isNaN(quantity)) {
                total += amount * quantity;
            }
        }

        document.getElementById("total_amount").value = total.toFixed(2);

        i++;
    }

    function calculate_balance() {
        const totalAmount = parseFloat(document.getElementById("total_amount").value);
        const depositeAmount = parseFloat(document.getElementById("deposite_amount").value);
        const balance = totalAmount - depositeAmount;
        document.getElementById("balance").value = balance.toFixed(2);
    }

    function getAllquantity() {
        var quantity = [];
        for (let j = 0; j < i; j++) {
            quantity.push(document.getElementById("quantity" + j).value);
        }
        // const quantity = values.join(',');
        return quantity;
    }

    function getAllmeters() {
        var meters = [];
        for (let j = 0; j < i; j++) {
            meters.push(document.getElementById("meters" + j).value);
        }
        return meters;
    }

    function getAlldescription() {
        var description = [];
        for (let j = 0; j < i; j++) {
            description.push(document.getElementById("description" + j).value);
        }
        return description;
    }

    function getAllamount() {
        var amount = [];
        for (let j = 0; j < i; j++) {
            amount.push(document.getElementById("amount" + j).value);
        }
        return amount;
    }


    function ajax_function() {

        var jobcard_id = document.getElementById("jobcard_id").value;
        var invoice_id = document.getElementById("invoice_id").value;
        var quality = getAllquantity();
        var meters = getAllmeters();
        var description = getAlldescription();
        var amount = getAllamount();
        var break_found_on = document.getElementById("break_found_on").value;
        var estimated_liters = document.getElementById("estimated_liters").value;
        var total_amount = document.getElementById("total_amount").value;
        var deposite_amount = document.getElementById("deposite_amount").value;
        var balance = document.getElementById("balance").value;
        var total_paid = document.getElementById("total_paid").value;

        var formData = new FormData();
        formData.append("jobcard_id", jobcard_id);
        formData.append("invoice_id", invoice_id);
        formData.append("quality", quality);
        formData.append("meters", meters);
        formData.append("description", description);
        formData.append("amount", amount);
        formData.append("break_found_on", break_found_on);
        formData.append("estimated_liters", estimated_liters);
        formData.append("total_amount", total_amount);
        formData.append("deposite_amount", deposite_amount);
        formData.append("balance", balance);
        formData.append("total_paid", total_paid);

        var xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
            if (this.responseText != 1) {
                alert(this.responseText);

            } else {
                alert("Invoice added successfully");
                window.location.href = "..invoices/home.php";
            }
        };
        xhttp.open("POST", "../invoices/add_invoices.ajax.php");
        xhttp.send(formData);

    }

</script>

<?php

// $invoice_ajax = new js_ajax();
// $invoice_ajax->function_name("add_invoice");
// $invoice_ajax->submit_btn_id("submit");
// $invoice_ajax->insert("invoice");
// $invoice_ajax->on_success("INVOICE ADDED SUCCESSFULLY");

// $update_ajax = new js_ajax();
// $update_ajax->function_name("update_jobcard");
// $update_ajax->submit_btn_id("submit");
// $update_ajax->update("jobcards");
// $update_ajax->add_column_and_value("invoice_id={$_POST['record_id']},");