<?php
session_start();
require_once 'config/database.php';

// Get user info
$user_id = $_SESSION['user_id'];
$sql = "SELECT username, email, role FROM users WHERE id = $user_id";
$result = $con->query($sql);
$user = $result ? $result->fetch_assoc() : null;

// If user not found, create empty user array to prevent sidebar errors
if (!$user) {
    $user = [
        'username' => 'Unknown',
        'email' => '',
        'role' => 'user'
    ];
}

// Layout variables
$page_title = 'DMAppsESP - Real-time Dashboard';
$breadcrumb_title = 'Real-time Dashboard';
$current_page = 'dashboard';
$extra_css = '<style>
    .realtime-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        position: relative;
    }
    .status-indicator {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 5px;
        animation: pulse 2s infinite;
    }
    .status-online { background-color: #28a745; }
    .status-offline { background-color: #dc3545; }
    .status-warning { background-color: #ffc107; }
    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.5; }
        100% { opacity: 1; }
    }
    .sensor-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
    }
    .sensor-item {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        text-align: center;
        border-left: 4px solid #007bff;
    }
    .sensor-value {
        font-size: 24px;
        font-weight: bold;
        color: #007bff;
    }
    .sensor-unit {
        font-size: 14px;
        color: #6c757d;
    }
    .chart-container {
        height: 300px;
        position: relative;
    }
    .alert-item {
        border-left: 4px solid #dc3545;
        padding: 10px;
        margin-bottom: 10px;
        background: #f8d7da;
        border-radius: 5px;
    }
    .alert-item.warning {
        border-left-color: #ffc107;
        background: #fff3cd;
    }
    .alert-item.info {
        border-left-color: #17a2b8;
        background: #d1ecf1;
    }
    .connection-status {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 10px 20px;
        border-radius: 20px;
        font-weight: bold;
        z-index: 1000;
    }
    .connection-status.connected {
        background: #d4edda;
        color: #155724;
    }
    .connection-status.disconnected {
        background: #f8d7da;
        color: #721c24;
    }
</style>';

$extra_js = '<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
let ws = null;
let charts = {};
let connectionStatus = false;

// WebSocket bağlantısı
function connectWebSocket() {
    const protocol = window.location.protocol === \'https:\' ? \'wss://\' : \'ws://\';
    const wsUrl = protocol + window.location.host + \':8080\';
    
    ws = new WebSocket(wsUrl);
    
    ws.onopen = function() {
        console.log(\'WebSocket bağlantısı kuruldu\');
        connectionStatus = true;
        updateConnectionStatus(true);
        
        // Cihaz listesini iste
        sendWebSocketMessage({
            type: \'get_devices\'
        });
    };
    
    ws.onmessage = function(event) {
        const data = JSON.parse(event.data);
        handleWebSocketMessage(data);
    };
    
    ws.onclose = function() {
        console.log(\'WebSocket bağlantısı kapandı\');
        connectionStatus = false;
        updateConnectionStatus(false);
        
        // 5 saniye sonra tekrar bağlanmayı dene
        setTimeout(connectWebSocket, 5000);
    };
    
    ws.onerror = function(error) {
        console.error(\'WebSocket hatası:\', error);
        connectionStatus = false;
        updateConnectionStatus(false);
    };
}

function handleWebSocketMessage(data) {
    switch(data.type) {
        case \'device_list\':
            updateDeviceList(data.devices);
            break;
        case \'sensor_data\':
            updateSensorData(data);
            break;
        case \'device_status\':
            updateDeviceStatus(data);
            break;
        case \'alert\':
            addAlert(data);
            break;
        case \'analytics\':
            updateAnalytics(data);
            break;
    }
}

function sendWebSocketMessage(message) {
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify(message));
    }
}

function updateConnectionStatus(connected) {
    const statusElement = document.getElementById(\'connectionStatus\');
    if (connected) {
        statusElement.className = \'connection-status connected\';
        statusElement.textContent = \'Bağlı\';
    } else {
        statusElement.className = \'connection-status disconnected\';
        statusElement.textContent = \'Bağlı Değil\';
    }
}

function updateDeviceList(devices) {
    const container = document.getElementById(\'deviceList\');
    let html = \'\';
    
    devices.forEach(device => {
        const statusClass = device.status === \'online\' ? \'status-online\' : \'status-offline\';
        html += \'<div class="col-md-4 mb-3">\';
        html += \'<div class="card">\';
        html += \'<div class="card-body">\';
        html += \'<h6 class="card-title"><span class="status-indicator \' + statusClass + \'"></span>\' + device.name + \'</h6>\';
        html += \'<p class="card-text">\' + device.device_id + \'</p>\';
        html += \'<p class="card-text"><small>Model: \' + device.esp_model + \'</small></p>\';
        html += \'<p class="card-text"><small>Mod: \' + device.current_mode + \'</small></p>\';
        html += `<button class="btn btn-sm btn-primary" onclick="selectDevice(${device.id})">Detaylar</button>`;
        html += \'</div></div></div>\';
    });
    
    container.innerHTML = html;
}

function updateSensorData(data) {
    // Sensör değerlerini güncelle
    const sensorElement = document.getElementById(\'sensor-\' + data.sensor_code);
    if (sensorElement) {
        const valueElement = sensorElement.querySelector(\'.sensor-value\');
        if (valueElement) {
            valueElement.textContent = data.value;
        }
    }
    
    // Grafikleri güncelle
    updateSensorCharts(data);
}

function updateDeviceStatus(data) {
    // Cihaz durumunu güncelle
    const deviceElement = document.getElementById(\'device-\' + data.device_id);
    if (deviceElement) {
        const statusIndicator = deviceElement.querySelector(\'.status-indicator\');
        if (statusIndicator) {
            statusIndicator.className = \'status-indicator status-\' + data.status;
        }
    }
}

function addAlert(alert) {
    const container = document.getElementById(\'alertsContainer\');
    const alertClass = alert.level === \'error\' ? \'alert-item\' : 
                        alert.level === \'warning\' ? \'alert-item warning\' : \'alert-item info\';
    
    const alertHtml = \'<div class="\' + alertClass + \'">\';
    alertHtml += \'<strong>\' + alert.title + \'</strong>\';
    alertHtml += \'<br><small>\' + alert.message + \'</small>\';
    alertHtml += \'<br><small class="text-muted">\' + alert.timestamp + \'</small>\';
    alertHtml += \'</div>\';
    
    container.insertAdjacentHTML(\'afterbegin\', alertHtml);
    
    // En fazla 10 alert göster
    const alerts = container.querySelectorAll(\'.alert-item\');
    if (alerts.length > 10) {
        alerts[alerts.length - 1].remove();
    }
}

function updateAnalytics(data) {
    // Grafikleri güncelle
    updateCharts(data);
}

function selectDevice(deviceId) {
    // Seçilen cihazın detaylarını göster
    sendWebSocketMessage({
        type: \'get_device_details\',
        device_id: deviceId
    });
}

function updateSensorCharts(data) {
    // Sensör grafiklerini güncelle
    if (charts.sensorChart) {
        const now = new Date();
        const timeLabel = now.getHours() + \':\' + now.getMinutes() + \':\' + now.getSeconds();
        
        // Yeni veriyi ekle
        if (charts.sensorChart.data.labels.length > 20) {
            charts.sensorChart.data.labels.shift();
            charts.sensorChart.data.datasets.forEach(dataset => {
                dataset.data.shift();
            });
        }
        
        charts.sensorChart.data.labels.push(timeLabel);
        
        // Mevcut dataseti bul veya oluştur
        let dataset = charts.sensorChart.data.datasets.find(d => d.label === data.sensor_code);
        if (!dataset) {
            dataset = {
                label: data.sensor_code,
                data: [],
                borderColor: getRandomColor(),
                backgroundColor: getRandomColor(0.2),
                tension: 0.1
            };
            charts.sensorChart.data.datasets.push(dataset);
        }
        
        dataset.data.push(parseFloat(data.value));
        charts.sensorChart.update();
    }
}

function updateCharts(data) {
    // Ana grafikleri güncelle
    if (data.deviceChart) {
        updateDeviceChart(data.deviceChart);
    }
}

function updateDeviceChart(chartData) {
    if (charts.deviceChart) {
        charts.deviceChart.data.labels = chartData.labels;
        charts.deviceChart.data.datasets[0].data = chartData.online;
        charts.deviceChart.data.datasets[1].data = chartData.offline;
        charts.deviceChart.update();
    }
}

function getRandomColor(alpha = 1) {
    const colors = [
        `rgba(255, 99, 132, ${alpha})`,
        `rgba(54, 162, 235, ${alpha})`,
        `rgba(255, 206, 86, ${alpha})`,
        `rgba(75, 192, 192, ${alpha})`,
        `rgba(153, 102, 255, ${alpha})`,
        `rgba(255, 159, 64, ${alpha})`
    ];
    return colors[Math.floor(Math.random() * colors.length)];
}

function initializeCharts() {
    // Sensör verileri grafiği
    const sensorCtx = document.getElementById(\'sensorChart\').getContext(\'2d\');
    charts.sensorChart = new Chart(sensorCtx, {
        type: \'line\',
        data: {
            labels: [],
            datasets: []
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: \'Sensör Verileri (Gerçek Zamanlı)\'
                }
            },
            scales: {
                x: {
                    display: true,
                    title: {
                        display: true,
                        text: \'Zaman\'
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: \'Değer\'
                    }
                }
            }
        }
    });
    
    // Cihaz durumu grafiği
    const deviceCtx = document.getElementById(\'deviceChart\').getContext(\'2d\');
    charts.deviceChart = new Chart(deviceCtx, {
        type: \'line\',
        data: {
            labels: [],
            datasets: [{
                label: \'Aktif Cihazlar\',
                data: [],
                borderColor: \'rgb(75, 192, 192)\',
                backgroundColor: \'rgba(75, 192, 192, 0.2)\',
                tension: 0.1
            }, {
                label: \'Pasif Cihazlar\',
                data: [],
                borderColor: \'rgb(255, 99, 132)\',
                backgroundColor: \'rgba(255, 99, 132, 0.2)\',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: \'Cihaz Durumu\'
                }
            }
        }
    });
}

// Sayfa yüklendiğinde başlat
document.addEventListener(\'DOMContentLoaded\', function() {
    initializeCharts();
    connectWebSocket();
});

// Sayfa kapatıldığında WebSocket bağlantısını kapat
window.addEventListener(\'beforeunload\', function() {
    if (ws) {
        ws.close();
    }
});
</script>';

require_once 'layouts/header.php';
?>

<div class="connection-status" id="connectionStatus">
    🔴 Bağlı Değil
</div>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1 class="h3 mb-4">Real-time Dashboard</h1>
            
            <!-- Cihaz Durumu -->
            <div class="realtime-card">
                <h5>Cihaz Durumu</h5>
                <div class="row" id="deviceList">
                    <div class="col-12 text-center">
                        <p class="text-muted">Cihazlar yükleniyor...</p>
                    </div>
                </div>
            </div>
            
            <!-- Sensör Verileri -->
            <div class="realtime-card">
                <h5>Sensör Verileri (Gerçek Zamanlı)</h5>
                <div class="sensor-grid" id="sensorGrid">
                    <div class="sensor-item">
                        <div class="sensor-value" id="sensor-TEMP">--</div>
                        <div class="sensor-unit">Sıcaklık (°C)</div>
                    </div>
                    <div class="sensor-item">
                        <div class="sensor-value" id="sensor-HUM">--</div>
                        <div class="sensor-unit">Nem (%)</div>
                    </div>
                    <div class="sensor-item">
                        <div class="sensor-value" id="sensor-PRESS">--</div>
                        <div class="sensor-unit">Basınç (hPa)</div>
                    </div>
                    <div class="sensor-item">
                        <div class="sensor-value" id="sensor-RPM">--</div>
                        <div class="sensor-unit">Devir/dakika</div>
                    </div>
                    <div class="sensor-item">
                        <div class="sensor-value" id="sensor-POWER">--</div>
                        <div class="sensor-unit">Güç (W)</div>
                    </div>
                    <div class="sensor-item">
                        <div class="sensor-value" id="sensor-VOLT">--</div>
                        <div class="sensor-unit">Voltaj (V)</div>
                    </div>
                </div>
            </div>
            
            <!-- Grafikler -->
            <div class="row">
                <div class="col-md-6">
                    <div class="realtime-card">
                        <div class="chart-container">
                            <canvas id="sensorChart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="realtime-card">
                        <div class="chart-container">
                            <canvas id="deviceChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Uyarılar -->
            <div class="realtime-card">
                <h5>Sistem Uyarıları</h5>
                <div id="alertsContainer">
                    <p class="text-muted">Yeni uyarı bekleniyor...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once 'layouts/footer.php'; ?>
</body>
</html>
