<?php

include "../../root.class.php";
$html = new html();
$html->add_styles_page();

$db = new db_safeguard();
$get_user_trans = $db->query("fuel_movement", "SELECT * FROM fuel_movement WHERE user_id = {$_SESSION['user_id']} AND (`status` = 'AUTHORISED' OR `status` = 'INI')");
if ($get_user_trans->num_rows > 0) {
    $data = $get_user_trans->fetch_assoc();
    ?>

    <script>
        window.location.href = 'diesel_transaction.php?transaction_number=<?php echo $data['record_id']; ?>&order_id=<?php echo $data['order_id']; ?>';</script>

    <?php
}

$client_id = new select();
$client_id->id("client_id");
$client_id->name("client_id");
$client_id->required();
$client_id->style("width: 80%;font-size:3em;");
$client_id->class("inputs");
$client_id->fill_from_db("clients", 'record_id', 'client_name', "company_id = {$_SESSION['company_id']} AND `client_status` = 1 ORDER BY client_name ASC");

$barcodeReader = new barcodeReader();

?>


<div class="form_down">
    <label style="font-size: 3em;">SELECT CLIENT</label>
    <?php
    $client_id->add();
    ?>
    <label style="font-size: 3em;">SCAN PUMP</label>
    <?php if ($_SESSION['username'] == "DEV") { ?>
    <input type="text" class='inputs' id="barcode" name="barcode">
    <?php } else { ?>
    <input type="text" class='inputs' hidden id="barcode" name="barcode">

        <?php } ?>
    <?php
    $barcodeReader->add_js_function_to_call("go_to_diesel_order()");
    $barcodeReader->add_button("barcode");
    ?>

    <?php if ($_SESSION['username'] == "DEV") { ?>
        <button onclick="go_to_diesel_order()" class="submit_btn">GO</button>
    <?php } else { ?>
        <button onclick="go_to_diesel_order()" hidden class="submit_btn">GO</button>

    <?php } ?>
</div>

<script>
    function go_to_diesel_order() {
        let client_id = document.getElementById("client_id").value;
        let barcode = document.getElementById("barcode").value;
        console.log(client_id);
        console.log(barcode);
        let formData = new FormData();
        formData.append('client_id', client_id);
        formData.append('barcode', barcode);

        fetch('diesel_order.ajax.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.text())
            .then(data => {
                console.log(data);
                if (data.includes("transaction_number=")) {
                    window.location = data;
                } else {
                    // Handle error or missing transaction number
                    console.error('Transaction number not received');
                }
            })
            .catch(error => console.error('Error:', error));
    }
</script>