<?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');

// 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 - $prev_liters;
    $prev_liters = $val;
    $xData[] = date('Y-m-d H:i:s', $current);

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

<style>
    body {
        margin-top: 1em;
        background-color: #f5f7fa;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .form-container {
        margin-bottom: 20px;
        padding: 10px;
        background: #ffffff;
        border-radius: 10px;
        box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
    }
</style>
<div class="form-container">
    <form method="get">
        <label>Start Date:</label>
        <input type="datetime-local" name="start_date" value="<?= $startDate ?>">
        &nbsp;&nbsp;
        <label>End Date:</label>
        <input type="datetime-local" name="end_date" value="<?= $endDate ?>">
        &nbsp;&nbsp;
        <button type="submit">Update</button>
    </form>
</div>
<table style="width: 70%">
    <thead>
        <tr>
            <th>Date</th>
            <th>Liters</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $i = 0;
        foreach ($xData as $k => $vX) { ?>
            <tr>
                <td><?= $vX ?></td>
                <td><?= $yData[$i] ?></td>
            </tr>
        <?php $i ++ ;} ?>
    </tbody>
</table>
