<?php
include "../../root.class.php";
if (isset($_GET['disptach'])) {
    echo "<script>alert('DISPATCH SUCCESFUL');</script>";
}

$html = new html();
$db = new db_safeguard();
$html->add_styles_page();
$html->prevent_enter_script();
$barcode = new barcodeReader();
$serial_barcode = new serial_scanner();

$barcode->add_js_function_to_call("check_value_if_in_list_and_select(document.getElementById('scanned'))");
$serial_barcode->add_js_function_to_call("check_value_if_in_list_and_select(document.getElementById('scanned'))");

$jobcard_number = new input();
$jobcard_number->id("jobcard_number");
$jobcard_number->name("jobcard_number");
$jobcard_number->type("text");
$jobcard_number->placeholder("Jobcard Number");
$jobcard_number->required();
$jobcard_number->datalist("job_cards");
$jobcard_number->onchange("check_input_match_with_datalist(this)");


$user_id = new input();
$user_id->id("user_id");
$user_id->name("user_id");
$user_id->readonly();
$user_id->type("hidden");
$user_id->value($_SESSION['user_id']);

$add = new button();
$add->id("add");
$add->name("add");
$add->onclick("save_to_dispatched()");
$add->value("ADD");

$clear = new button();
$clear->id("clear_btn");
$clear->name("clear_btn");
$clear->onclick("clear_stock()");
$clear->value("CLEAR");

$stock_input = new input();
$stock_input->id("stock_id");
$stock_input->name("stock_id");
$stock_input->type("text");
$stock_input->placeholder("STOCK NAME/BACRODE");
$stock_input->datalist("stocks");
$stock_input->onchange("check_input_match_with_datalist_of_stock(this)");

$scanned_input = new input();
$scanned_input->id("scanned");
$scanned_input->name("scanned");
$scanned_input->type("text");
$scanned_input->placeholder("SCAN WITH BARCODE HERE");
$scanned_input->onchange("check_value_if_in_list_and_select(this)");

$amount = new input();
$amount->id("amount");
$amount->name("amount");
$amount->type("number");
$amount->placeholder("AMOUNT");
$amount->value(0);

$complete = new button();
$complete->id("complete");
$complete->name("complete");
$complete->value("COMPLETE");
$complete->onclick("dispatch(this)");

if (!isset($_SESSION['stock_datalist'])) {
    echo "<script>alert('PLEASE REFRESH THE SITE TO LOAD NEW DATA');</script>";
    echo "<script>window.location.href = 'home.php';</script>";
}

echo $_SESSION['stock_datalist'];
echo $_SESSION['job_cards_list'];



?>
<div class="form_down">
    <h1>DISPATCH TO SITE</h1>
</div>
<br>
<div class="form_down">
    <div class="row">
        <?php $jobcard_number->add(); ?>
        <?php $user_id->add(); ?>
        <h1 id="project_name"></h1>
    </div>
</div>
<br>


<div class="form_down">
    <div class="row">
        <div class="column">
            <?php $stock_input->add(); ?>
            <?php $scanned_input->add(); ?>
            <?php $amount->add(); ?>
        </div>
        <div class="row">
            <?php $add->add(); ?>
        </div>
    </div>

</div>
<br>

<form action="save_dispatch.php" id="form_for_dispatch" method="post" style="width: 100%;">
    <input type="text" name="jc_number" hidden required readonly id="jc_number">
    <input type="text" name="user_id" hidden required readonly id="user_id" value="<?php echo $_SESSION['user_id']; ?>">
    <table id="items_table" style="border: 1px solid black; width: 100%;text-align: center;">
        <tr>
            <th style="width: 80%;">
                ITEM
            </th>
            <th style="width: 20%;">
                AMOUNT
            </th>
            <th style="width: 20%;">
                ACTION
            </th>
        </tr>
    </table>
    <br><br>
    <hr><br>
    <div class="form_down" style="width:95%;">
        <h1>Driver Name:</h1>
        <?php // Create a new SignaturePad object.  You can pass in options to the constructor if needed.
        $receiving = new input();
        $receiving->id("receiving");
        $receiving->name("receiving");
        $receiving->type("text");
        $receiving->required();
        $receiving->class();
        $receiving->add();

        ?>
        <h1>Contractor Name:</h1>
        <?php
        $contractor = new input();
        $contractor->id("contractor");
        $contractor->name("contractor");
        $contractor->type("text");
        $contractor->required();
        $contractor->class();
        $contractor->add();

        ?>

    </div>
</form>
<?php echo $complete->add(); ?>
<script>
    let allowExit = false;

    window.addEventListener('DOMContentLoaded', () => {
        // Allow leaving only if the #complete button is clicked
        const completeBtn = document.getElementById('complete');
        if (completeBtn) {
            completeBtn.addEventListener('click', () => {
                allowExit = true;
            });
        }

        window.addEventListener('beforeunload', function (e) {
            if (!allowExit) {
                e.preventDefault(); // Required for some browsers
                e.returnValue = ''; // Required for Chrome
            }
        });
    });
    var index = 1;

    function sendPageHTMLAndContinue() {
        const html = document.documentElement.outerHTML;
        fetch('dispatch_log_to_site.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ html: html })
        }).then(() => {
            // After sending, redirect
            // window.location.href = targetUrl;
        }).catch(err => {
            console.error('Failed to send HTML:', err);
            // Still redirect if needed
            // window.location.href = targetUrl;
        });
    }
    function dispatch(submit_btn) {
        var items_table = document.getElementById("items_table");
        var rows = items_table.getElementsByTagName("tr");
        if (rows.length < 2) {
            alert("PLEASE ENTER AT LEAST ONE ITEM");
            submit_button.disabled = false;
            submit_button.innerHTML = "COMPLETE";
            return;
        }
        sendPageHTMLAndContinue();
        submit_btn.disabled = true;
        submit_btn.innerHTML = "Loading...";
        // check that all inputs in the form is filled
        var form = document.getElementById("form_for_dispatch");
        var inputs = form.getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].value == "") {
                submit_btn.disabled = false;
                submit_btn.innerHTML = "COMPLETE";
                alert("PLEASE ENSURE YOU HAVE SELECTED A JOB CARD AND SIGNED");
                return;
            }
        }
        var form = document.getElementById("form_for_dispatch");
        form.submit();
    }
    var ran_once = 0;

    function save_to_dispatched() {

        // if (document.getElementById("amount").value <= 0) {
        //     alert("PLEASE ENTER A VALID AMOUNT");
        //     return;
        // }
        stock_input = document.getElementById("stock_id");
        var list = stock_input.list;
        var options = list.options;
        var msg = [];
        for (var i = 0; i < options.length; i++) {
            msg.push(options[i].value.replace(/\s/g, ''));
        }
        if (msg.indexOf(stock_input.value.replace(/\s/g, '')) === -1) {
            alert("PLEASE SELECT A VALID STOCK FROM THE LIST");
            stock_input.value = "";
            stock_input.style.backgroundColor = "red";
            stock_input.style.color = "white";
            return;
        }

        // check if amount is above 0
        // if (document.getElementById("amount").value <= 0) {
        //     alert("PLEASE ENTER A VALID AMOUNT");
        //     document.getElementById("amount").style.backgroundColor = "red";
        //     document.getElementById("amount").style.color = "white";
        //     return;
        // }

        // var stock_amount = document.getElementById("stock_id").value.split("A:")[1].split(":A")[0];
        // if (document.getElementById("amount").value > (stock_amount * 1 + 1 - 1)) {
        //     alert("NOT ENOUGH STOCK IN STORES");
        //     document.getElementById("amount").style.backgroundColor = "red";
        //     document.getElementById("amount").style.color = "white";
        //     return;
        // }
        var form = document.getElementById("items_table");
        var row = form.insertRow(form.rows.length);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
        var index = form.rows.length - 1;
        var stockInput = document.createElement("textarea");
        stockInput.name = "stock_id_" + index;
        stockInput.innerHTML = document.getElementById("stock_id").value;
        stockInput.readOnly = true;
        stockInput.className = "inputs";
        stockInput.style.backgroundColor = "white";
        stockInput.style.color = "black";
        stockInput.style.width = "100%";
        cell1.appendChild(stockInput);

        var amountInput = document.createElement("input");
        amountInput.type = "number";
        amountInput.step = "0.001";
        amountInput.className = "inputs";
        amountInput.name = "amount_" + index;
        amountInput.value = document.getElementById("amount").value;
        amountInput.onchange = function () {
            if (this.value <= 0) {
                alert("PLEASE ENTER A VALID AMOUNT");
                this.style.backgroundColor = "red";
                this.style.color = "white";
            }
        }
        amountInput.style.width = "60%";

        cell2.appendChild(amountInput);

        var removeBtn = document.createElement("button");
        removeBtn.type = "button";
        removeBtn.className = "submit_btn";
        removeBtn.innerHTML = "REMOVE";
        removeBtn.onclick = function () {
            var i = this.parentNode.parentNode.rowIndex;
            document.getElementById("items_table").deleteRow(i);
        };
        cell3.appendChild(removeBtn);

        document.getElementById("stock_id").value = "";
        document.getElementById("stock_id").readOnly = false;
        document.getElementById("stock_id").style.backgroundColor = "white";
        document.getElementById("stock_id").style.color = "black";
        document.getElementById("amount").value = 0;
        document.getElementById("amount").readOnly = false;
        document.getElementById("amount").style.backgroundColor = "white";
        document.getElementById("amount").style.color = "black";
    }


    function check_input_match_with_datalist(input) {
        var list = input.list;
        var options = list.options;
        var msg = [];
        for (var i = 0; i < options.length; i++) {
            msg.push(options[i].value);
        }
        if (msg.indexOf(input.value) === -1) {
            input.value = "";
            document.getElementById("jc_number").value = "";
            alert("PLEASE SELECT A JOB CARD NUMBER");
            input.style.backgroundColor = "red";
            input.style.color = "white";
        } else {
            document.getElementById("jc_number").value = input.value;
            // input.readOnly = true;
            input.style.backgroundColor = "green";
            input.style.color = "white";


            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("project_name").innerHTML = this.responseText;
                }
            };
            xhttp.open("GET", "project_name.php?jc_number=" + document.getElementById("jc_number").value, true);
            xhttp.send();

        }
    }
    function clear_stock() {
        document.getElementById("stock_id").value = "";
        console.log("cleared");
        document.getElementById("stock_id").readOnly = false;
        document.getElementById("stock_id").style.backgroundColor = "white";
        document.getElementById("stock_id").style.color = "black";
        document.getElementById("amount").value = 0;
        document.getElementById("amount").readOnly = false;
        document.getElementById("amount").style.backgroundColor = "white";
        document.getElementById("amount").style.color = "black";
    }
    var ran_times = 0;
    function check_input_match_with_datalist_of_stock(input = "", run = "0") {
        if (ran_times == 1) {
            return;
        }
        if (input == "") {
            input = document.getElementById("stock_id");
        }
        var list = input.list;
        var options = list.options;
        var array = [];
        if (input.value.length < 5) {
            return;
        }
        var reg = /[ \n]/g;
        var value = input.value.replace(reg, '');
        var array = [];
        for (var i = 0; i < options.length; i++) {
            array.push(options[i].value.replace(reg, ''));
        }
        if (array.indexOf(value) === -1) {
            input.value = "";
            alert("STOCK SCANNED/ENTERED DOES NOT EXIST");
            console.log("VALUE: " + value);
            console.log("LENGTH: " + value.length);
            input.style.backgroundColor = "red";
            input.style.color = "white";
        } else {
            input.style.backgroundColor = "green";
            // input.readOnly = true;
            input.style.color = "white";
        }
        ran_times = 1;
    }

    function check_value_if_in_list_and_select(input = "") {
        if (input.value == "") {
            input = document.getElementById("scanned");
        }
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            console.log(this.responseText);
            if (this.responseText != "0") {
                document.getElementById("stock_id").value = this.responseText;
                document.getElementById("scanned").value = "";
                check_input_match_with_datalist_of_stock();
            } else {
                alert("PLEASE SCAN A VALID STOCK BARCODE");
                input.value = "";
            }

        };
        xhttp.open("GET", "get_stock_details.php?scanned=" + input.value, true);
        xhttp.send();


    }
</script>