<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
// $html->check_user_type("ADMIN");
$db = new db_safeguard();

$jobcard_value = $_GET['record_id'];

$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_no");
$invoice->required();
$invoice->id("invoice_no");
$invoice->value_from_db("jobcards", "invoice_id", "jc_no = $jobcard_value");

$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");

$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_label = new label();
$amount_label->for("amount");
$amount_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");
$break_found->value_from_db("jobcards", "break_found_on", "jc_no = $jobcard_value");

$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");
$estimated_liters->value_from_db("jobcards", "estimated_liters", "jc_no = $jobcard_value");

$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->value_from_db("jobcards", "deposite_amount", "jc_no = $jobcard_value");

$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");

$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");

$add_row_btn = new button();
$add_row_btn->value("ADD ROW");
$add_row_btn->onclick("add_row()");

$submit_btn = new button();
$submit_btn->value("UPDATE INVOICE");
$submit_btn->onclick("update_invoice(), update_jobcard()");

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>";
}

$invoice_no_res = $db->query("invoice", "SELECT invoice_id FROM invoice ORDER BY invoice_id DESC ");
$invoice_no = $invoice_no_res->fetch_assoc()['invoice_id'];

$invoices_res = $db->query("invoice", "SELECT * FROM invoice WHERE invoice_id = $invoice_no");

$i = 0;
echo $invoice_res->num_rows;
while ($row = $invoices_res->fetch_assoc()) {
    $invoice_data = "
    <div style='display: flex; flex-direction: row; border-top: 2px solid black; width: 78.5vw;'>
        <div style='width: 100%; height: 4vw;'>
            <input type='number' name='quantity_$i' id='quantity_$i' style='width: 100%; height: 4vw; font-size: 2vw;' value='{$row['quantity']}'>
        </div>
        <div style='width: 100%;'>
            <input type='number' name='meters_$i' id='meters_$i' style='width: 100%; height: 4vw; font-size: 2vw;' value='{$row['meters']}'>
        </div>
        <div style='width: 100%;'>
            <select name='description_$i' id='description_$i' style='width: 100%; height: 4vw; font-size: 2vw;' value='{$row['description']}'>
                <?php echo $description_list; ?>
            </select>
        </div>
        <div style='width: 100%;'>
            <input type='number' name='amount_$i' id='amount_$i' style='width: 100%; height: 4vw; font-size: 2vw;' value='{$row['amount']}'>
        </div>
        <div>
            <button type='button' style='width: 100%; height: 4vw; font-size: 2vw;' onclick='delete_row($i)'>X</button>
        </div>
    </div>
    ";
    $i++;
}

?>

<div class="form_down">
    <h1>EDIT 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" value="">
                <?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_label->add();
                ?>
            </div>
        </div>

        <?php
        echo $invoice_data;
        ?>
    </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();
    ?>
</div>

<script>
    i = 1;

    // function getAmountByType(typeName) {
    //     const match = types.find(t => t.name === typeName);
    //     return match ? match.amount : '';
    // }

    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;
        description.id = "description_" + i;

        // 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;
            // amount.value = getAmountByType(selectedType);
        });

        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;
        // const amount = getAmountByType(selectedType);
        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);
    }

    calculate_total();
    calculate_balance();

</script>

<?php

$update_invoice_ajax = new js_ajax();
$update_invoice_ajax->function_name("update_invoice");
$update_invoice_ajax->submit_btn_id("submit_btn");
$update_invoice_ajax->update("invoices");

$update_jobcard_ajax = new js_ajax();
$update_jobcard_ajax->function_name("update_jobcard");
$update_jobcard_ajax->submit_btn_id("submit_btn");
$update_jobcard_ajax->update("jobcards");