<?php
session_start(); // Начинаем сессию

// Инициализация переменной $error
$error = "";


error_reporting(E_ALL);
ini_set('display_errors', 1);

// Подключаем базу
include('includes/db.php');

// Токен тестового датчика из дампа
$device_token = 'esp32_BME280_v0.5';

/* ===== 1. ОДНА ПОСЛЕДНЯЯ ЗАПИСЬ ===== */

$last_stmt = $conn->prepare("
    SELECT temperature, humidity, pressure, created_at
    FROM sensor_data
    WHERE device_token = ?
    ORDER BY created_at DESC
    LIMIT 1
");

$last_stmt->bind_param("s", $device_token);
$last_stmt->execute();
$last_result = $last_stmt->get_result();
$last = $last_result->fetch_assoc();


/* ===== 2. ПОСЛЕДНИЕ 20 ДЛЯ ГРАФИКА ===== */

$list_stmt = $conn->prepare("
    SELECT
        DATE_FORMAT(created_at, '%Y-%m-%d %H:00:00') AS created_at,
        AVG(temperature) AS temperature,
        AVG(humidity) AS humidity,
        AVG(pressure) AS pressure
    FROM sensor_data
    WHERE device_token = ?
      AND created_at >= NOW() - INTERVAL 24 HOUR
    GROUP BY DATE_FORMAT(created_at, '%Y-%m-%d %H')
    ORDER BY created_at ASC
");


$list_stmt->bind_param("s", $device_token);
$list_stmt->execute();
$list_res = $list_stmt->get_result();

$labels   = [];
$temps    = [];
$humids   = [];
$press_mm = [];

while ($r = $list_res->fetch_assoc()) {

    // защита от пустых значений, чтобы не ругался strtotime
    if (empty($r['created_at'])) {
        continue;
    }

    $labels[]   = date('H:i', strtotime($r['created_at']));
    $temps[]    = round($r['temperature'], 2);
    $humids[]   = round($r['humidity'], 2);
    $press_mm[] = round($r['pressure'] * 0.75006, 1); // гПа -> мм рт. ст.
}


?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP32 Терминал</title>
    <!-- Подключение стилей -->
    <link rel="stylesheet" href="style.css">
    <!-- Меню / шапка -->
    <?php include('templates/header.php'); ?>
    <!-- Chart.js для графика -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>

   <div class="container">

       <!-- Таблица с ОДНОЙ последней записью -->
       <div class="terminal">
            <div class="terminal-header">
                Консоль устройства: <?php echo htmlspecialchars($device_token); ?>
            </div>
            <div class="terminal-body">
                <div class="code-block">
                    <div class="console-line">
                        &gt; Последние показания датчика:
                    </div>
                    <table class="sensor-table">
                        <thead>
                            <tr>
                                <th>Время</th>
                                <th>Темп., °C</th>
                                <th>Влажн., %</th>
                                <th>Давл., hPa</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$last): ?>
                                <tr>
                                    <td colspan="4">Нет данных в таблице sensor_data</td>
                                </tr>
                            <?php else: ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($last['created_at']); ?></td>
                                    <td><?php echo htmlspecialchars($last['temperature']); ?></td>
                                    <td><?php echo htmlspecialchars($last['humidity']); ?></td>
                                    <td><?php echo htmlspecialchars($last['pressure']); ?></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

       <!-- Вкладки для переключения графиков -->
       <div class="tabs">
           <button class="tab-button" onclick="showGraph('temperature')">Температура</button>
           <button class="tab-button" onclick="showGraph('humidity')">Влажность</button>
           <button class="tab-button" onclick="showGraph('pressure')">Давление</button>
       </div>
       <!-- Графики -->
       <div id="temperature" class="graph-container" style="display: block;">
           <canvas id="temperatureChart"></canvas>
       </div>
       <div id="humidity" class="graph-container" style="display: none;">
           <canvas id="humidityChart"></canvas>
       </div>
       <div id="pressure" class="graph-container" style="display: none;">
           <canvas id="pressureChart"></canvas>
       </div>

        <!-- Auth Block -->
<div class="auth-block" style="max-width:400px; margin:40px auto; display: <?php echo isset($_SESSION['user_id']) ? 'none' : 'block'; ?>;">
  <center><h2>Вход</h2>
  <?php if ($error): ?>
    <p style="color:#ff4477; margin-bottom:15px;"><?php echo htmlspecialchars($error); ?></p>
  <?php endif; ?>
  <form method="POST" action="https://ioxs.ru/pages/login.php">
    <label for="email">Почта  </label>
    <input class="tab-buttons" type="email" name="email" id="email" placeholder="Введите email" required autocomplete="username">
    <br><br><label for="password">Пароль</label>
    <input class="tab-buttons" type="password" name="password" id="password" placeholder="Введите пароль" required autocomplete="current-password">
    <br><br><button class="tab-buttons" type="submit">Войти</button>
  </form>
  <p style="margin-top:15px; font-size:14px;">Ещё нет аккаунта? <a href="/pages/register.php">Зарегистрироваться</a></p></center>
</div>


    </div>


    <?php include('templates/footer.php'); ?>


 <!-- JS для графиков -->
    <script>
    const labels = <?php echo json_encode($labels, JSON_UNESCAPED_UNICODE); ?>;
    const temps  = <?php echo json_encode($temps, JSON_UNESCAPED_UNICODE); ?>;
    const humids = <?php echo json_encode($humids, JSON_UNESCAPED_UNICODE); ?>;
    const pressMM = <?php echo json_encode($press_mm, JSON_UNESCAPED_UNICODE); ?>;

    // Графики
    let temperatureChart, humidityChart, pressureChart;

    // Функция для отображения нужного графика
    function showGraph(graphType) {
        // Скрываем все графики
        document.getElementById('temperature').style.display = 'none';
        document.getElementById('humidity').style.display = 'none';
        document.getElementById('pressure').style.display = 'none';

        // Показываем только выбранный график
        document.getElementById(graphType).style.display = 'block';

        // Инициализация графиков, если они еще не были созданы
        if (graphType === 'temperature' && !temperatureChart) {
            const ctx = document.getElementById('temperatureChart').getContext('2d');
            temperatureChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Температура, °C',
                        data: temps,
                        borderWidth: 2,
                        tension: 0.2,
                        borderColor: '#00ffff',
                        pointRadius: 2
                    }]
                },
                options: {
                    scales: {
                        x: {
                            ticks: { color: '#00FF00' },
                            grid: { color: '#004400' }
                        },
                        y: {
                            ticks: { color: '#00FF00' },
                            grid: { color: '#004400' }
                        }
                    }
                }
            });
        }

        if (graphType === 'humidity' && !humidityChart) {
            const ctx = document.getElementById('humidityChart').getContext('2d');
            humidityChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Влажность, %',
                        data: humids,
                        borderWidth: 2,
                        tension: 0.2,
                        borderColor: '#ff66ff',
                        pointRadius: 2
                    }]
                },
                options: {
                    scales: {
                        x: {
                            ticks: { color: '#00FF00' },
                            grid: { color: '#004400' }
                        },
                        y: {
                            ticks: { color: '#00FF00' },
                            grid: { color: '#004400' }
                        }
                    }
                }
            });
        }

        if (graphType === 'pressure' && !pressureChart) {
            const ctx = document.getElementById('pressureChart').getContext('2d');
            pressureChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Давление, мм рт. ст.',
                        data: pressMM,
                        borderWidth: 2,
                        tension: 0.2,
                        borderColor: '#ffcc33',
                        pointRadius: 2
                    }]
                },
                options: {
                    scales: {
                        x: {
                            ticks: { color: '#00FF00' },
                            grid: { color: '#004400' }
                        },
                        y: {
                            ticks: { color: '#00FF00' },
                            grid: { color: '#004400' }
                        }
                    }
                }
            });
        }
    }

    // Изначально показываем график температуры
    showGraph('temperature');
    </script>

</body>
</html>

