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

// Layout variables
$page_title = 'DMAppsESP - Analitik Dashboard';
$breadcrumb_title = 'Analitikler';
$current_page = 'analytics';
$extra_css = '<style>
    .chart-container {
        position: relative;
        height: 400px;
        margin-bottom: 30px;
    }
    .stat-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        border-radius: 10px;
        margin-bottom: 20px;
    }
    .stat-card h3 {
        margin: 0 0 10px 0;
        font-size: 18px;
    }
    .stat-card .number {
        font-size: 32px;
        font-weight: bold;
    }
    .chart-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }
    .time-filter {
        margin-bottom: 20px;
    }
    .export-btn {
        background: #28a745;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        margin: 5px;
    }
    .export-btn:hover {
        background: #218838;
    }
</style>';

$extra_js = '<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Chart.js grafikleri
let deviceChart, sensorChart, userChart;

document.addEventListener(\'DOMContentLoaded\', function() {
    loadAnalytics();
    
    // Zaman filtresi değişiminde verileri yenile
    document.getElementById(\'timeFilter\').addEventListener(\'change\', loadAnalytics);
});

function loadAnalytics() {
    const timeFilter = document.getElementById(\'timeFilter\').value;
    
    // İstatistikleri yükle
    fetch(\'api/analytics.php?action=stats&period=\' + timeFilter)
        .then(response => response.json())
        .then(data => {
            updateStatCards(data);
        });
    
    // Cihaz grafiği
    fetch(\'api/analytics.php?action=device_chart&period=\' + timeFilter)
        .then(response => response.json())
        .then(data => {
            updateDeviceChart(data);
        });
    
    // Sensör grafiği
    fetch(\'api/analytics.php?action=sensor_chart&period=\' + timeFilter)
        .then(response => response.json())
        .then(data => {
            updateSensorChart(data);
        });
    
    // Kullanıcı grafiği
    fetch(\'api/analytics.php?action=user_chart&period=\' + timeFilter)
        .then(response => response.json())
        .then(data => {
            updateUserChart(data);
        });
}

function updateStatCards(data) {
    document.getElementById(\'totalDevices\').textContent = data.total_devices || 0;
    document.getElementById(\'activeDevices\').textContent = data.active_devices || 0;
    document.getElementById(\'totalUsers\').textContent = data.total_users || 0;
    document.getElementById(\'totalSensors\').textContent = data.total_sensors || 0;
    document.getElementById(\'dataPoints\').textContent = data.data_points || 0;
    document.getElementById(\'avgResponseTime\').textContent = data.avg_response_time || 0;
}

function updateDeviceChart(data) {
    const ctx = document.getElementById(\'deviceChart\').getContext(\'2d\');
    
    if (deviceChart) {
        deviceChart.destroy();
    }
    
    deviceChart = new Chart(ctx, {
        type: \'line\',
        data: {
            labels: data.labels,
            datasets: [{
                label: \'Aktif Cihazlar\',
                data: data.active_devices,
                borderColor: \'rgb(75, 192, 192)\',
                backgroundColor: \'rgba(75, 192, 192, 0.2)\',
                tension: 0.1
            }, {
                label: \'Çevrimdışı Cihazlar\',
                data: data.offline_devices,
                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\'
                }
            }
        }
    });
}

function updateSensorChart(data) {
    const ctx = document.getElementById(\'sensorChart\').getContext(\'2d\');
    
    if (sensorChart) {
        sensorChart.destroy();
    }
    
    sensorChart = new Chart(ctx, {
        type: \'bar\',
        data: {
            labels: data.labels,
            datasets: [{
                label: \'Sıcaklık\',
                data: data.temperature,
                backgroundColor: \'rgba(255, 99, 132, 0.8)\'
            }, {
                label: \'Nem\',
                data: data.humidity,
                backgroundColor: \'rgba(54, 162, 235, 0.8)\'
            }, {
                label: \'Basınç\',
                data: data.pressure,
                backgroundColor: \'rgba(255, 206, 86, 0.8)\'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: \'Sensör Verileri\'
                }
            }
        }
    });
}

function updateUserChart(data) {
    const ctx = document.getElementById(\'userChart\').getContext(\'2d\');
    
    if (userChart) {
        userChart.destroy();
    }
    
    userChart = new Chart(ctx, {
        type: \'doughnut\',
        data: {
            labels: data.labels,
            datasets: [{
                data: data.values,
                backgroundColor: [
                    \'rgba(255, 99, 132, 0.8)\',
                    \'rgba(54, 162, 235, 0.8)\',
                    \'rgba(255, 206, 86, 0.8)\'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: \'Kullanıcı Dağılımı\'
                }
            }
        }
    });
}

function exportData(format) {
    const timeFilter = document.getElementById(\'timeFilter\').value;
    window.open(\'api/export.php?type=analytics&format=\' + format + \'&period=\' + timeFilter, \'_blank\');
}
</script>';

require_once 'layouts/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <h1 class="h3 mb-4">Analitik Dashboard</h1>
            
            <!-- Zaman Filtresi -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="time-filter">
                        <label for="timeFilter" class="form-label">Zaman Aralığı:</label>
                        <select class="form-select" id="timeFilter">
                            <option value="today">Bugün</option>
                            <option value="week" selected>Son 7 Gün</option>
                            <option value="month">Son 30 Gün</option>
                            <option value="quarter">Son 3 Ay</option>
                            <option value="year">Son 1 Yıl</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-6 text-end">
                    <button class="export-btn" onclick="exportData('pdf')">PDF İndir</button>
                    <button class="export-btn" onclick="exportData('excel')">Excel İndir</button>
                    <button class="export-btn" onclick="exportData('csv')">CSV İndir</button>
                </div>
            </div>
            
            <!-- İstatistik Kartları -->
            <div class="row">
                <div class="col-md-2">
                    <div class="stat-card">
                        <h3>Toplam Cihaz</h3>
                        <div class="number" id="totalDevices">0</div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="stat-card">
                        <h3>Aktif Cihaz</h3>
                        <div class="number" id="activeDevices">0</div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="stat-card">
                        <h3>Kullanıcı</h3>
                        <div class="number" id="totalUsers">0</div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="stat-card">
                        <h3>Sensör</h3>
                        <div class="number" id="totalSensors">0</div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="stat-card">
                        <h3>Veri Noktası</h3>
                        <div class="number" id="dataPoints">0</div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="stat-card">
                        <h3>Ort. Yanıt Süresi</h3>
                        <div class="number" id="avgResponseTime">0ms</div>
                    </div>
                </div>
            </div>
            
            <!-- Grafikler -->
            <div class="row">
                <div class="col-md-6">
                    <div class="chart-card">
                        <div class="chart-container">
                            <canvas id="deviceChart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="chart-card">
                        <div class="chart-container">
                            <canvas id="sensorChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-4">
                    <div class="chart-card">
                        <div class="chart-container">
                            <canvas id="userChart"></canvas>
                        </div>
                    </div>
                </div>
                <div class="col-md-8">
                    <div class="chart-card">
                        <h5>En Aktif Cihazlar</h5>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Cihaz Adı</th>
                                        <th>Model</th>
                                        <th>Son Görülme</th>
                                        <th>Veri Sayısı</th>
                                        <th>Durum</th>
                                    </tr>
                                </thead>
                                <tbody id="activeDevicesTable">
                                    <!-- JavaScript ile doldurulacak -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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