<?php

include "../../html.class.php";
include "../../classes/db.class.php";
include "../../functions.class.php";
$html = new html();
$functions = new functions();

$date = date('Y-m-d');

$latest_orders_res = $db->query("fuel_movement", "SELECT 
    fm.record_id AS record_id,
    fm.date_time_closed,
    fm.tank_id,
    fm.client_id,
    fm.amount,
    fm.fuel_price,
    fm.cash_type
FROM fuel_movement AS fm
LEFT JOIN clients AS c 
    ON c.record_id = fm.client_id 
    AND c.company_id = fm.company_id
WHERE 
    fm.company_id = {$_SESSION['company_id']}
    AND fm.amount > 50
    AND fm.tank_id IN (
        SELECT record_id 
        FROM tanks 
        WHERE site_id = 13 
          AND company_id = {$_SESSION['company_id']}
    )
    AND fm.date_time_closed BETWEEN '$date 00:00' AND '$date 23:59'
    AND (
        (c.exclude_from_reports != 1 AND fm.client_id != 0)
        OR (fm.client_id = 0 AND fm.status = 'MANUAL OVERRIDE')
    )
ORDER BY fm.date_imported DESC;");
?>
<style>
    body {
        display: flex;
        flex-direction: column;
        flex-wrap: nowrap;
        align-items: center;

    }
</style>
<div class="table-responsive">
    <table>
        <tr>
            <th>
                TANK
            </th>
            <th>
                DATE
            </th>
            <th>
                CLIENT
            </th>
            <th>
                AMOUNT (mL)
            </th>
            <th>
                VALUE (R)
            </th>
            <th>
                TYPE
            </th>


        </tr>

        <?php

        while ($latest_orders = $latest_orders_res->fetch_assoc()) {
            ?>

            <tr>
                <td>
                    <input class="table_input" readonly type='text'
                        value='<?php echo $functions->get_tank_name($latest_orders['tank_id']); ?>'>
                </td>
                <td>
                    <input class="table_input" readonly type='text'
                        value='<?php echo $latest_orders['date_time_closed']; ?>'>
                </td>
                <td>
                    <select class="table_input" disabled>
                        <?php $clients_res = $db->query("clients", "SELECT * FROM clients WHERE company_id = {$_SESSION['company_id']}"); ?>
                        <option value="<?php echo $latest_orders['client_id']; ?>">
                            <?php echo $functions->get_client_name($latest_orders['client_id']); ?>
                        </option>
                        <?php while ($client = $clients_res->fetch_assoc()) { ?>
                            <option value="<?php echo $client['record_id']; ?>"><?php echo $client['client_name']; ?></option>
                        <?php } ?>
                    </select>
                </td>
                <td>
                    <input class="table_input" readonly type='text'
                        value=' <?php echo number_format($latest_orders['amount'], 2); ?>'>
                </td>
                <td>
                    <input class="table_input" readonly type='text'
                        value=' <?php echo number_format(($latest_orders['amount'] / 1000) * $latest_orders['fuel_price'], 2); ?>'>
                </td>
                <td>
                    <select class="table_input"
                        onchange="change(this,'cash_type','<?php echo $latest_orders['record_id']; ?>')">
                        <?php if ($latest_orders['cash_type'] == 0) {
                            $type = "N/A";
                            ?>
                            <option value="<?php echo $latest_orders['type']; ?>"><?php echo $type; ?></option>
                            <option value="1">CASH</option>
                            <option value="3">EFT</option>
                            <option value="2">CARD</option>

                            <?php

                        } else if ($latest_orders['cash_type'] == 1) {
                            $type = "CASH";
                            ?>
                                <option value="<?php echo $latest_orders['type']; ?>"><?php echo $type; ?></option>
                                <option value="3">EFT</option>
                                <option value="2">CARD</option>
                                <option value="0">N/A</option>

                            <?php
                        } else if ($latest_orders['cash_type'] == 2) {
                            $type = "CARD";
                            ?>
                                    <option value="<?php echo $latest_orders['type']; ?>"><?php echo $type; ?></option>
                                    <option value="3">EFT</option>
                                    <option value="1">CASH</option>
                                    <option value="0">N/A</option>

                            <?php
                        } else {
                            $type = "EFT";
                            ?>
                                    <option value="<?php echo $latest_orders['type']; ?>"><?php echo $type; ?></option>
                                    <option value="2">CARD</option>
                                    <option value="1">CASH</option>
                                    <option value="0">N/A</option>

                            <?php
                        } ?>
                    </select>
                </td>

            </tr>
            <?php
        }
        ?>

    </table>
</div>

<script>
    function change(input, column_name, record_id) {
        if (confirm("Are you sure you want to change this detail?")) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var orig_color = input.style.backgroundColor;
                    console.log(this.responseText);
                    if (this.responseText == "1") {
                        input.style.transition = "background-color 1.5s ease";
                        input.style.backgroundColor = "green";
                        setTimeout(function () {
                            input.style.backgroundColor = orig_color;
                        }, 1500);

                    } else {
                        input.style.transition = "background-color 1.5s ease";
                        input.style.backgroundColor = "red";
                        setTimeout(function () {
                            input.style.backgroundColor = orig_color;
                        }, 1500);
                        alert(this.responseText);
                    }
                }
            };
            xmlhttp.open("POST", "change_details.ajax.php", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send("value=" + input.value + "&column_name=" + column_name + "&record_id=" + record_id);
        }
    }
</script>

<div class="spacer"></div>


<script>
    let wakeLock = null;
    let lastInteraction = Date.now();
    const INACTIVITY_LIMIT = 2 * 60 * 1000; // 2 minutes

    // --- Request Wake Lock ---
    async function requestWakeLock() {
        try {
            if ('wakeLock' in navigator) {
                wakeLock = await navigator.wakeLock.request('screen');
                console.log('✅ Screen Wake Lock active.');

                wakeLock.addEventListener('release', () => {
                    console.log('⚠️ Wake Lock was released.');
                });

                document.addEventListener('visibilitychange', async () => {
                    if (wakeLock !== null && document.visibilityState === 'visible') {
                        wakeLock = await navigator.wakeLock.request('screen');
                        console.log('🔄 Wake Lock re-acquired.');
                    }
                });
            } else {
                console.warn('❌ Wake Lock API not supported.');
            }
        } catch (err) {
            console.error('Wake Lock error:', err);
        }
    }

    // --- Track User Interaction ---
    function resetTimer() {
        lastInteraction = Date.now();
    }

    // --- Check Inactivity ---
    function checkInactivity() {
        const now = Date.now();
        if (now - lastInteraction >= INACTIVITY_LIMIT) {
            console.log('⏰ No activity for 2 minutes. Refreshing...');
            location.reload(); // refresh the current page
        }
    }

    // --- Initialize ---
    function initKeepAliveSystem() {
        // Track user activity
        ['click', 'mousemove', 'keypress', 'touchstart'].forEach(event => {
            document.addEventListener(event, resetTimer);
        });

        // Start inactivity checker
        setInterval(checkInactivity, 10000); // check every 10 seconds

        // Require user interaction to enable wake lock
        document.addEventListener('click', requestWakeLock, { once: true });
    }

    initKeepAliveSystem();
</script>