<?php
include "classes/app.class.php";
$tank_id = $_GET['id'] ?? 0;

// Placeholder for your data fetching logic
// $data = $db->query("tank_history", "SELECT date_time, current_liters FROM history WHERE tank_id = $tank_id AND date_time >= NOW() - INTERVAL 1 DAY ORDER BY date_time ASC");
// $labels = ["08:00", "10:00", ...];
// $values = [5000, 4800, ...];

$tank = $db->query("tanks", "SELECT * FROM tanks WHERE record_id = $tank_id");
$tank = $tank->fetch_assoc();
$name = $tank['name'];
$radius = $tank['radius_mm'];
$length = $tank['length_mm'];
$tank_type = $tank['tank_type'];
$add_to_distance = $tank['add_to_distance'];
// 1. Get the raw logs for the last 24 hours in ONE query
// We group by the date and hour to get one entry per hour
$sql = "SELECT * FROM tank_level_log 
        WHERE tank_id = $tank_id 
        AND date_time_measured >= NOW() - INTERVAL 24 HOUR 
        GROUP BY DATE(date_time_measured), HOUR(date_time_measured) 
        ORDER BY date_time_measured ASC";

$logs_res = $db->query("tank_level_log", $sql);

$labels = [];
$values = [];
$func = new functions();

while ($log = $logs_res->fetch_assoc()) {
    $distance = $log['distance'] ?? 0;

    // Perform your volume calculation
    $calc = $func->calculate_horizontal_cylinder_volume(
        $radius,
        ($radius * 2) - ($distance + $add_to_distance),
        $length
    );

    // Format the time for the graph (e.g., "14:00")
    $labels[] = date("H:i", strtotime($log['date_time_measured']));
    $values[] = round($calc['fluid_volume_liters']);
}

// Convert to JSON for the Javascript Chart
$js_labels = json_encode($labels);
$js_values = json_encode($values);
?>
<!DOCTYPE html>
<html lang="en">


<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
    :root {
        --apple-blue: #007AFF;
        --apple-bg: #F5F5F7;
    }

    body {
        background-color: var(--apple-bg);
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    }

    .chart-container {
        background: white;
        border-radius: 18px;
        padding: 20px;
        margin: 15px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        height: 60vh;
        /* Responsive height */
    }

    .header-nav {
        display: flex;
        align-items: center;
        padding: 20px 15px;
        gap: 15px;
    }

    .btn-back {
        background: #E8E8ED;
        border: none;
        padding: 8px 15px;
        border-radius: 20px;
        font-weight: 600;
        color: #000;
        cursor: pointer;
        text-decoration: none;
        font-size: 14px;
    }

    .stats-summary {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 15px;
        margin: 0 15px 15px 15px;
    }

    .stat-card {
        background: white;
        padding: 15px;
        border-radius: 14px;
        text-align: center;
    }

    .stat-card small {
        color: #86868B;
        display: block;
        font-size: 12px;
        margin-bottom: 5px;
    }

    .stat-card span {
        font-size: 18px;
        font-weight: 700;
        color: #1D1D1F;
    }
</style>

<body>

    <div class="header-nav">
        <a href="dashboard.php" class="btn-back">← Back</a>
        <h2 style="margin:0; font-size: 20px;">24h History</h2>
    </div>


    <div class="stats-summary">
        <div class="stat-card">
            <span><?php echo $tank['name']; ?></span>
        </div>
    </div>


    <div class="stats-summary">
        <div class="stat-card">
            <small>HIGHEST LEVEL</small>
            <span id="stat-max"></span>
        </div>
        <div class="stat-card">
            <small>LOWEST LEVEL</small>
            <span id="stat-min"></span>
        </div>
    </div>

    <div class="chart-container">
        <canvas id="tankChart"></canvas>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            renderTankChart();
        });

        function renderTankChart() {
            const ctx = document.getElementById('tankChart').getContext('2d');

            // --- ADD YOUR DATA HERE ---
            const xLabels = <?php echo $js_labels; ?>;
            const yValues = <?php echo $js_values; ?>;
            // ---------------------------

            // Update stats
            document.getElementById('stat-max').innerText = Math.max(...yValues).toLocaleString() + ' L';
            document.getElementById('stat-min').innerText = Math.min(...yValues).toLocaleString() + ' L';

            // Create Gradient (Fade effect under line)
            const gradient = ctx.createLinearGradient(0, 0, 0, 400);
            gradient.addColorStop(0, 'rgba(0, 122, 255, 0.2)');
            gradient.addColorStop(1, 'rgba(0, 122, 255, 0)');

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: xLabels,
                    datasets: [{
                        label: 'Liters',
                        data: yValues,
                        borderColor: '#007AFF',
                        borderWidth: 3,
                        pointBackgroundColor: '#fff',
                        pointBorderColor: '#007AFF',
                        pointRadius: 0, // Hidden by default
                        pointHoverRadius: 6, // Shows on hover
                        tension: 0.4, // This creates the smooth Apple curve
                        fill: true,
                        backgroundColor: gradient
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false } // Hide legend
                    },
                    scales: {
                        x: {
                            grid: { display: false },
                            ticks: { color: '#86868B', font: { size: 11 } }
                        },
                        y: {
                            grid: { color: '#F2F2F7' },
                            ticks: {
                                color: '#86868B',
                                font: { size: 11 },
                                callback: function (value) { return value + 'L'; }
                            }
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index',
                    }
                }
            });
        }
    </script>
    <div class="spacer"></div>
</body>

</html>