<?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 - Advanced Analytics';
$breadcrumb_title = 'Advanced Analytics';
$current_page = 'analytics';
$extra_css = '<style>
    .analytics-container {
        background: white;
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }
    .analytics-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        flex-wrap: wrap;
        gap: 10px;
    }
    .analytics-filters {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        align-items: center;
    }
    .analytics-filters select,
    .analytics-filters input {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-size: 14px;
    }
    .analytics-filters button {
        padding: 8px 16px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 14px;
        transition: background-color 0.3s;
    }
    .analytics-filters .btn-primary {
        background: #007bff;
        color: white;
    }
    .analytics-filters .btn-primary:hover {
        background: #0056b3;
    }
    .analytics-filters .btn-secondary {
        background: #6c757d;
        color: white;
    }
    .analytics-filters .btn-secondary:hover {
        background: #5a6268;
    }
    .analytics-filters .btn-success {
        background: #28a745;
        color: white;
    }
    .analytics-filters .btn-success:hover {
        background: #218838;
    }
    .metrics-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }
    .metric-card {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        border-left: 4px solid #007bff;
        transition: all 0.3s ease;
    }
    .metric-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 15px rgba(0,123,255,0.2);
    }
    .metric-value {
        font-size: 32px;
        font-weight: bold;
        color: #333;
        margin-bottom: 5px;
    }
    .metric-label {
        font-size: 14px;
        color: #6c757d;
        margin-bottom: 10px;
    }
    .metric-change {
        font-size: 12px;
        font-weight: bold;
    }
    .metric-change.positive {
        color: #28a745;
    }
    .metric-change.negative {
        color: #dc3545;
    }
    .charts-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }
    .chart-container {
        background: white;
        border-radius: 10px;
        padding: 20px;
        border: 1px solid #dee2e6;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .chart-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 15px;
        text-align: center;
    }
    .chart-wrapper {
        position: relative;
        height: 300px;
    }
    .device-comparison {
        background: white;
        border-radius: 10px;
        padding: 20px;
        border: 1px solid #dee2e6;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .device-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
    }
    .device-table th,
    .device-table td {
        padding: 12px;
        text-align: left;
        border-bottom: 1px solid #dee2e6;
    }
    .device-table th {
        background-color: #f8f9fa;
        font-weight: 600;
        color: #333;
    }
    .device-table tr:hover {
        background-color: #f8f9fa;
    }
    .status-badge {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
        color: white;
    }
    .status-badge.online {
        background-color: #28a745;
    }
    .status-badge.offline {
        background-color: #dc3545;
    }
    .status-badge.warning {
        background-color: #ffc107;
        color: #212529;
    }
    .progress-ring {
        display: inline-block;
        position: relative;
        width: 60px;
        height: 60px;
    }
    .progress-ring svg {
        transform: rotate(-90deg);
    }
    .progress-ring-circle {
        fill: none;
        stroke-width: 4;
        stroke-linecap: round;
    }
    .progress-ring-bg {
        stroke: #e9ecef;
    }
    .progress-ring-fill {
        stroke: #007bff;
        transition: stroke-dashoffset 0.5s ease;
    }
    .progress-ring-text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 12px;
        font-weight: bold;
        color: #333;
    }
    .loading {
        text-align: center;
        padding: 40px;
        color: #6c757d;
    }
    .loading .spinner {
        border: 4px solid #f3f3f3;
        border-top: 4px solid #007bff;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        animation: spin 1s linear infinite;
        margin: 0 auto 15px;
    }
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    .error-message {
        background: #f8d7da;
        border: 1px solid #f5c6cb;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        color: #721c24;
    }
</style>';

$extra_js = '<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<script>
let charts = {};
let analyticsData = {};

// Sayfa yüklendiğinde başlat
document.addEventListener("DOMContentLoaded", function() {
    initializeCharts();
    loadAnalyticsData();
    
    // Filtre değişiminde verileri yenile
    document.getElementById("refreshData").addEventListener("click", loadAnalyticsData);
    document.getElementById("exportData").addEventListener("click", exportData);
});

function initializeCharts() {
    // Sensör verileri grafiği
    const sensorCtx = document.getElementById("sensorTrendChart").getContext("2d");
    charts.sensorTrend = new Chart(sensorCtx, {
        type: "line",
        data: {
            labels: [],
            datasets: []
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: "Sensor Trends (Last 30 Days)"
                },
                legend: {
                    display: true,
                    position: "top"
                },
                tooltip: {
                    mode: "index",
                    intersect: false
                }
            },
            scales: {
                x: {
                    display: true,
                    title: {
                        display: true,
                        text: "Date"
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: "Value"
                    }
                }
            }
        }
    });

    // Sistem performansı grafiği
    const perfCtx = document.getElementById("performanceChart").getContext("2d");
    charts.performance = new Chart(perfCtx, {
        type: "radar",
        data: {
            labels: ["CPU", "Memory", "Storage", "Network", "Sensors", "Uptime"],
            datasets: [{
                label: "System Performance",
                data: [],
                backgroundColor: "rgba(0, 123, 255, 0.2)",
                borderColor: "rgba(0, 123, 255, 1)",
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: "System Performance"
                }
            },
            scales: {
                r: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });

    // Kullanıcı aktivitesi grafiği
    const activityCtx = document.getElementById("activityChart").getContext("2d");
    charts.activity = new Chart(activityCtx, {
        type: "bar",
        data: {
            labels: [],
            datasets: [{
                label: "User Activity",
                data: [],
                backgroundColor: "rgba(40, 167, 69, 0.8)",
                borderColor: "rgba(40, 167, 69, 1)",
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: "User Activity (Last 7 Days)"
                }
            },
            scales: {
                x: {
                    display: true,
                    title: {
                        display: true,
                        text: "Date"
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: "Activity Count"
                    }
                }
            }
        }
    });

    // Veri kalitesi grafiği
    const qualityCtx = document.getElementById("qualityChart").getContext("2d");
    charts.quality = new Chart(qualityCtx, {
        type: "doughnut",
        data: {
            labels: ["Good", "Fair", "Poor", "Error"],
            datasets: [{
                data: [],
                backgroundColor: [
                    "rgba(40, 167, 69, 0.8)",
                    "rgba(255, 193, 7, 0.8)",
                    "rgba(255, 152, 0, 0.8)",
                    "rgba(220, 53, 69, 0.8)"
                ],
                borderColor: [
                    "rgba(40, 167, 69, 1)",
                    "rgba(255, 193, 7, 1)",
                    "rgba(255, 152, 0, 1)",
                    "rgba(220, 53, 69, 1)"
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: "Data Quality Distribution"
                },
                legend: {
                    position: "bottom"
                }
            }
        }
    });
}

function loadAnalyticsData() {
    const period = document.getElementById("periodFilter").value;
    const device = document.getElementById("deviceFilter").value;
    const sensor = document.getElementById("sensorFilter").value;
    
    const params = new URLSearchParams({
        period: period,
        device: device,
        sensor: sensor
    });
    
    fetch("api/analytics.php?action=advanced&" + params)
        .then(response => response.json())
        .then(data => {
            analyticsData = data;
            updateMetrics(data.metrics);
            updateCharts(data);
            updateDeviceTable(data.devices);
        })
        .catch(error => {
            console.error("Analytics data loading error:", error);
            showError("Failed to load analytics data");
        });
}

function updateMetrics(metrics) {
    document.getElementById("totalDevices").textContent = metrics.totalDevices || 0;
    document.getElementById("activeDevices").textContent = metrics.activeDevices || 0;
    document.getElementById("totalSensors").textContent = metrics.totalSensors || 0;
    document.getElementById("dataPoints").textContent = metrics.dataPoints || 0;
    
    // Progress ring güncelleme
    updateProgressRing("deviceHealth", metrics.deviceHealth || 0);
    updateProgressRing("systemHealth", metrics.systemHealth || 0);
}

function updateProgressRing(elementId, percentage) {
    const ring = document.getElementById(elementId);
    const circle = ring.querySelector(".progress-ring-fill");
    const text = ring.querySelector(".progress-ring-text");
    
    const radius = 26;
    const circumference = 2 * Math.PI * radius;
    const offset = circumference - (percentage / 100) * circumference;
    
    circle.style.strokeDashoffset = offset;
    text.textContent = percentage + "%";
}

function updateCharts(data) {
    // Sensör trend grafiği
    if (data.sensorTrend) {
        charts.sensorTrend.data.labels = data.sensorTrend.labels;
        charts.sensorTrend.data.datasets = data.sensorTrend.datasets;
        charts.sensorTrend.update();
    }
    
    // Performans grafiği
    if (data.performance) {
        charts.performance.data.datasets[0].data = data.performance;
        charts.performance.update();
    }
    
    // Aktivite grafiği
    if (data.activity) {
        charts.activity.data.labels = data.activity.labels;
        charts.activity.data.datasets[0].data = data.activity.values;
        charts.activity.update();
    }
    
    // Kalite grafiği
    if (data.quality) {
        charts.quality.data.datasets[0].data = data.quality;
        charts.quality.update();
    }
}

function updateDeviceTable(devices) {
    const tbody = document.getElementById("deviceTableBody");
    tbody.innerHTML = "";
    
    devices.forEach(device => {
        const row = tbody.insertRow();
        row.innerHTML = `
            <td>${device.name}</td>
            <td>${device.device_id}</td>
            <td>${device.esp_model}</td>
            <td><span class="status-badge ${device.status}">${device.status}</span></td>
            <td>${device.sensors}</td>
            <td>${device.last_seen}</td>
            <td>
                <button class="btn btn-sm btn-primary" onclick="viewDevice(${device.id})">View</button>
            </td>
        `;
    });
}

function exportData() {
    const format = document.getElementById("exportFormat").value;
    const period = document.getElementById("periodFilter").value;
    const device = document.getElementById("deviceFilter").value;
    const sensor = document.getElementById("sensorFilter").value;
    
    const params = new URLSearchParams({
        format: format,
        period: period,
        device: device,
        sensor: sensor
    });
    
    window.open("api/analytics.php?action=export&" + params, "_blank");
}

function viewDevice(deviceId) {
    window.location.href = "device_detail.php?id=" + deviceId;
}

function showError(message) {
    const errorDiv = document.getElementById("errorMessage");
    errorDiv.textContent = message;
    errorDiv.style.display = "block";
    
    setTimeout(() => {
        errorDiv.style.display = "none";
    }, 5000);
}
</script>';

require_once 'layouts/header.php';
?>

<div class="analytics-container">
    <div class="analytics-header">
        <h2 class="mb-0">Advanced Analytics</h2>
        <div class="analytics-filters">
            <select id="periodFilter">
                <option value="7">Last 7 Days</option>
                <option value="30" selected>Last 30 Days</option>
                <option value="90">Last 90 Days</option>
                <option value="365">Last Year</option>
            </select>
            <select id="deviceFilter">
                <option value="">All Devices</option>
                <!-- Devices will be loaded via JavaScript -->
            </select>
            <select id="sensorFilter">
                <option value="">All Sensors</option>
                <!-- Sensors will be loaded via JavaScript -->
            </select>
            <select id="exportFormat">
                <option value="csv">CSV</option>
                <option value="excel">Excel</option>
                <option value="pdf">PDF</option>
            </select>
            <button class="btn btn-primary" id="refreshData">🔄 Refresh</button>
            <button class="btn btn-success" id="exportData">📥 Export</button>
        </div>
    </div>
    
    <div id="errorMessage" class="error-message" style="display: none;"></div>
    
    <!-- Metrics Grid -->
    <div class="metrics-grid">
        <div class="metric-card">
            <div class="metric-value" id="totalDevices">0</div>
            <div class="metric-label">Total Devices</div>
            <div class="metric-change positive">+12% from last month</div>
        </div>
        <div class="metric-card">
            <div class="metric-value" id="activeDevices">0</div>
            <div class="metric-label">Active Devices</div>
            <div class="metric-change positive">+8% from last month</div>
        </div>
        <div class="metric-card">
            <div class="metric-value" id="totalSensors">0</div>
            <div class="metric-label">Total Sensors</div>
            <div class="metric-change positive">+15% from last month</div>
        </div>
        <div class="metric-card">
            <div class="metric-value" id="dataPoints">0</div>
            <div class="metric-label">Data Points</div>
            <div class="metric-change positive">+25% from last month</div>
        </div>
        <div class="metric-card">
            <div class="progress-ring" id="deviceHealth">
                <svg width="60" height="60">
                    <circle class="progress-ring-circle progress-ring-bg" cx="30" cy="30" r="26"></circle>
                    <circle class="progress-ring-circle progress-ring-fill" cx="30" cy="30" r="26"></circle>
                </svg>
                <div class="progress-ring-text">0%</div>
            </div>
            <div class="metric-label">Device Health</div>
        </div>
        <div class="metric-card">
            <div class="progress-ring" id="systemHealth">
                <svg width="60" height="60">
                    <circle class="progress-ring-circle progress-ring-bg" cx="30" cy="30" r="26"></circle>
                    <circle class="progress-ring-circle progress-ring-fill" cx="30" cy="30" r="26"></circle>
                </svg>
                <div class="progress-ring-text">0%</div>
            </div>
            <div class="metric-label">System Health</div>
        </div>
    </div>
    
    <!-- Charts Grid -->
    <div class="charts-grid">
        <div class="chart-container">
            <div class="chart-title">Sensor Trends</div>
            <div class="chart-wrapper">
                <canvas id="sensorTrendChart"></canvas>
            </div>
        </div>
        <div class="chart-container">
            <div class="chart-title">System Performance</div>
            <div class="chart-wrapper">
                <canvas id="performanceChart"></canvas>
            </div>
        </div>
        <div class="chart-container">
            <div class="chart-title">User Activity</div>
            <div class="chart-wrapper">
                <canvas id="activityChart"></canvas>
            </div>
        </div>
        <div class="chart-container">
            <div class="chart-title">Data Quality</div>
            <div class="chart-wrapper">
                <canvas id="qualityChart"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Device Comparison Table -->
    <div class="device-comparison">
        <h3>Device Comparison</h3>
        <table class="device-table">
            <thead>
                <tr>
                    <th>Device Name</th>
                    <th>Device ID</th>
                    <th>Model</th>
                    <th>Status</th>
                    <th>Sensors</th>
                    <th>Last Seen</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="deviceTableBody">
                <tr>
                    <td colspan="7" class="text-center">
                        <div class="loading">
                            <div class="spinner"></div>
                            <div>Loading device data...</div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

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