<?php
session_start();
include "../classes/html_items.php";
include "../classes/db.class.php";
include "../functions.class.php";
include "../classes/dashboard.class.php";
$functions = new functions();
$dash = new dash_items();
echo DashboardWidget::includeAssets();
// Tank info
$tank_res = $db->query("tanks", "SELECT * FROM tanks WHERE record_id = 1 LIMIT 1");
$tank = $tank_res->fetch_assoc();

// Default time window
$defaultEnd = date('Y-m-d\TH:i', strtotime('+2 hours'));  // now formatted for input
$defaultStart = date('Y-m-d\TH:i', strtotime('+0 hours'));

// Handle GET parameters if set
$startDate = $_GET['start_date'] ?? $defaultStart;
$endDate = $_GET['end_date'] ?? $defaultEnd;

$xData = [];
$yData = [];

$current = strtotime($endDate);
$start = strtotime($startDate);

$prev_liters = 0;
while ($current >= $start) {

    $next = $current - (5 * 60);  // 5 min earlier

    $startStr = date('Y-m-d H:i:s', $current);
    $endStr = date('Y-m-d H:i:s', $next);

    $res = $db->query(
        "tank_level_log",
        "SELECT AVG(distance) AS avg_distance
         FROM tank_level_log
         WHERE date_time_measured BETWEEN '$endStr' AND '$startStr'"
    );

    $avgDist = 0;
    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        $avgDist = $row['avg_distance'];
    }

    if (!is_numeric($avgDist)) {
        $avgDist = 0;
    }

    // Convert to liters
    $converted = $functions->calculate_horizontal_cylinder_volume(
        $tank['radius_mm'],
        ($tank['radius_mm'] * 2) - ($avgDist - 1),
        $tank['length_mm']
    );

    $val = floatval($converted['fluid_volume_liters']);
    if (!is_finite($val))
        $val = 0;

    // Append values
    $yData[] = $val;
    $vX_comb[] = $val - $prev_liters;
    $prev_liters = $val;
    $xData[] = date('Y-m-d H:i:s', $current);

    // Move to next step
    $current = $next;
}
?>

<style>
    body {
        margin: 0;
        font-family: Arial, sans-serif;
        background-color: #eef2f5;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 1rem;
    }

    .form-box {
        width: 100%;
        max-width: 800px;
        background: #ffffff;
        padding: 1rem 1.5rem;
        border-radius: 10px;
        box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
        display: flex;
        flex-direction: column;
        gap: 10px;
        margin-bottom: 1rem;
    }

    .form-box label {
        font-weight: bold;
        font-size: 1.1rem;
    }

    .form-box input {
        width: 100%;
        padding: 0.6rem;
        font-size: 1.5rem;
        border-radius: 6px;
        border: 1px solid #ccd2d8;
    }

    .form-box button {
        background-color: #0066cc;
        color: #fff;
        padding: 0.7rem;
        border: none;
        border-radius: 6px;
        font-size: 1.5rem;
        cursor: pointer;
        width: 100%;
        transition: background 0.25s;
    }

    .form-box button:hover {
        background-color: #004a99;
    }

    #linechart-box {
        width: 100%;
        max-width: 1000px;
        background: #ffffff;
        border-radius: 10px;
        padding: 0.8rem;
        box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
    }

    #linechart {
        width: 100%;
        height: 50vh;
        min-height: 300px;
    }

    /* Desktop layout */
    @media (min-width: 768px) {
        .form-box {
            flex-direction: row;
            align-items: center;
            flex-wrap: wrap;
            justify-content: space-between;
        }

        .form-box label {
            width: 100%;
        }

        .form-box input {
            width: calc(50% - 0.5rem);
        }

        .form-box button {
            width: auto;
            margin-left: auto;
            flex-shrink: 0;
            padding: 0.65rem 1.5rem;
        }
    }
</style>

<div class="container_home">
    <div class="data_containers">
        <div class="small_line"></div>
        <h1>TANK LEVELS</h1>
        <?php
        $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE 1 ORDER BY record_id ASC");
        while ($tank = $tanks_res->fetch_assoc()) {
            $dash->tank($tank['record_id'], "#");
        }
        ?>
    </div>
</div>

<div class="spacer"></div>

<?php exit; ?>
<form method="get" class="form-box">
    <label>Start Date:</label>
    <input type="datetime-local" name="start_date" value="<?= $startDate ?>">
    <label>End Date:</label>
    <input type="datetime-local" name="end_date" value="<?= $endDate ?>">
    <button type="submit">Update</button>
    </div>
    <div id="linechart-box">
        <div id="linechart"></div>
    </div>

    <!-- <table style="width: 70%; margin-left: auto; margin-right: auto;">
        <thead>
            <tr>
                <th colspan="2">Testing Perposes only (Liter > 5 est. between measurements)</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $i = 0;
            foreach ($vX_comb as $k => $vX) {
                if ($i == 0) {
                    $i++;
                    continue;
                }
                if ($vX <= 5) {
                    $i++;
                    continue;
                }
                ?>
                <tr>
                    <td><?= $xData[$i] ?></td>
                    <td><?= $vX ?> L</td>
                </tr>
                <?php $i++;
            } ?>
        </tbody>
    </table> -->

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script>
        google.charts.load('current', { packages: ['corechart'] });
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            const xData = [<?php foreach ($xData as $v)
                echo "'$v',"; ?>];
            const yData = [<?php foreach ($yData as $v)
                echo "$v,"; ?>];

            const data = new google.visualization.DataTable();
            data.addColumn('datetime', 'Time');
            data.addColumn('number', 'Volume (L)');

            for (let i = 0; i < xData.length; i++) {
                const val = (!isFinite(yData[i])) ? 0 : yData[i];
                data.addRow([new Date(xData[i]), val]);
            }

            const options = {
                title: 'Tank Levels Over Time',
                legend: { position: 'bottom' },
                curveType: 'none',     // 🔥 NO smoothing!
                hAxis: { title: 'Time', format: 'HH:mm' },
                vAxis: { title: 'Liters' },
                explorer: { actions: ['dragToZoom', 'rightClickToReset'] }
            };

            const chart = new google.visualization.LineChart(document.getElementById('linechart'));
            chart.draw(data, options);
        }
    </script>