<?php
/**
 * Admin - Telemetry Dashboard - Advanced Monitoring
 */
require_once '../config.php';
$admin = isAdminLogged();

// 1. Global KPIs
$kpis = [];

// Active Instances (Last 1h)
$stmt = $pdo->query("SELECT COUNT(DISTINCT instance_id) as c FROM telemetry WHERE recorded_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$kpis['active_instances'] = $stmt->fetch()['c'];

// Total Heartbeats (24h)
$stmt = $pdo->query("SELECT COUNT(*) as total FROM telemetry WHERE event_type IN ('heartbeat', 'verify') AND recorded_at > DATE_SUB(NOW(), INTERVAL 1 DAY)");
$kpis['heartbeats_24h'] = $stmt->fetch()['total'];

$stmt = $pdo->query("
    SELECT t.name, COUNT(*) as hits, MAX(i.server_url) as server_url
    FROM telemetry tl
    JOIN instances i ON tl.instance_id = i.id
    JOIN tenants t ON i.tenant_id = t.id
    WHERE tl.recorded_at > DATE_SUB(NOW(), INTERVAL 1 DAY)
    GROUP BY t.id, t.name
    ORDER BY hits DESC
    LIMIT 5
");
$topTenants = $stmt->fetchAll();

// Versions Distribution
$stmt = $pdo->query("
    SELECT version, COUNT(*) as count 
    FROM instances 
    WHERE is_active = 1 
    GROUP BY version 
    ORDER BY count DESC
");
$versions = $stmt->fetchAll();

// 2. Activity Chart Data (Last 7 Days)
$chartData = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as total 
        FROM telemetry 
        WHERE event_type IN ('heartbeat', 'verify') AND DATE(recorded_at) = ?
    ");
    $stmt->execute([$date]);
    $chartData['labels'][] = date('d/m', strtotime($date));
    $chartData['values'][] = $stmt->fetch()['total'];
}

// 3. Detailed Instance Status
$stmt = $pdo->query("
    SELECT i.*, t.name as tenant_name, t.code as tenant_code,
           (SELECT recorded_at FROM telemetry WHERE instance_id = i.id ORDER BY recorded_at DESC LIMIT 1) as last_activity,
           (SELECT client_ip FROM telemetry WHERE instance_id = i.id ORDER BY recorded_at DESC LIMIT 1) as last_ip
    FROM instances i
    JOIN tenants t ON i.tenant_id = t.id
    ORDER BY i.last_heartbeat DESC
");
$instances = $stmt->fetchAll();

$currentPage = 'telemetry';
$pageTitle = 'Monitoring - License Server';
?>
<?php include 'includes/header.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- Sidebar -->
    <?php include 'includes/sidebar.php'; ?>

    <!-- Main Content -->
    <main class="ml-60 p-8">
        <div class="max-w-7xl mx-auto">
            
            <div class="flex justify-between items-center mb-8">
                <div>
                    <h1 class="text-2xl font-bold text-slate-800">System Monitoring</h1>
                    <p class="text-slate-500 text-sm">Vue globale de l'activité des instances</p>
                </div>
                <div class="flex items-center gap-2">
                    <span class="relative flex h-3 w-3">
                      <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                      <span class="relative inline-flex rounded-full h-3 w-3 bg-emerald-500"></span>
                    </span>
                    <span class="text-sm font-medium text-emerald-600">Live</span>
                </div>
            </div>

            <!-- KPI Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <div class="bg-white rounded-xl p-6 border border-slate-200 shadow-sm">
                    <div class="flex items-center justify-between mb-2">
                        <p class="text-slate-500 text-sm font-medium">Instances Actives</p>
                        <i class="fa-solid fa-server text-indigo-500 bg-indigo-50 p-2 rounded-lg"></i>
                    </div>
                    <p class="text-3xl font-bold text-slate-800"><?= $kpis['active_instances'] ?></p>
                    <p class="text-xs text-emerald-600 mt-1 font-medium"><i class="fa-solid fa-arrow-up"></i> Temps réel (1h)</p>
                </div>
                
                <div class="bg-white rounded-xl p-6 border border-slate-200 shadow-sm">
                    <div class="flex items-center justify-between mb-2">
                        <p class="text-slate-500 text-sm font-medium">Requêtes (24h)</p>
                        <i class="fa-solid fa-bolt text-amber-500 bg-amber-50 p-2 rounded-lg"></i>
                    </div>
                    <p class="text-3xl font-bold text-slate-800"><?= number_format($kpis['heartbeats_24h']) ?></p>
                    <p class="text-xs text-slate-400 mt-1">Total Heartbeats</p>
                </div>

                <div class="bg-white rounded-xl p-6 border border-slate-200 shadow-sm">
                    <div class="flex items-center justify-between mb-2">
                        <p class="text-slate-500 text-sm font-medium">Versions</p>
                        <i class="fa-solid fa-code-branch text-purple-500 bg-purple-50 p-2 rounded-lg"></i>
                    </div>
                    <div class="flex flex-wrap gap-2 mt-2">
                        <?php foreach ($versions as $v): ?>
                            <span class="bg-purple-50 text-purple-700 px-2 py-1 rounded-md text-xs font-bold border border-purple-100">
                                v<?= $v['version'] ?: '1.0' ?> <span class="text-purple-400 mx-1">|</span> <?= $v['count'] ?>
                            </span>
                        <?php endforeach; ?>
                        <?php if(empty($versions)) echo '<span class="text-xs text-slate-400">Aucune donnée</span>'; ?>
                    </div>
                </div>

                <div class="bg-white rounded-xl p-6 border border-slate-200 shadow-sm">
                    <div class="flex items-center justify-between mb-2">
                        <p class="text-slate-500 text-sm font-medium">Santé Système</p>
                        <i class="fa-solid fa-heart-pulse text-emerald-500 bg-emerald-50 p-2 rounded-lg"></i>
                    </div>
                    <p class="text-3xl font-bold text-emerald-600">100%</p>
                    <p class="text-xs text-emerald-600 mt-1 font-medium">Opérationnel</p>
                </div>
            </div>

            <!-- Charts & Lists -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
                <!-- Main Chart -->
                <div class="lg:col-span-2 bg-white rounded-xl p-6 border border-slate-200 shadow-sm">
                    <h3 class="font-bold text-slate-800 mb-4 flex items-center gap-2">
                        <i class="fa-solid fa-chart-area text-indigo-500"></i>
                        Piles d'activité (7 jours)
                    </h3>
                    <div class="h-64">
                        <canvas id="activityChart"></canvas>
                    </div>
                </div>

                <!-- Top Tenants -->
                <div class="bg-white rounded-xl p-6 border border-slate-200 shadow-sm">
                    <h3 class="font-bold text-slate-800 mb-4 flex items-center gap-2">
                        <i class="fa-solid fa-trophy text-amber-500"></i>
                        Top Clients (Activité)
                    </h3>
                    <div class="space-y-4">
                        <?php foreach ($topTenants as $index => $t): ?>
                            <div class="flex items-center justify-between p-3 bg-slate-50 rounded-lg hover:bg-slate-100 transition-colors">
                                <div class="flex items-center gap-3">
                                    <div class="w-8 h-8 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center font-bold text-xs">
                                        <?= $index + 1 ?>
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-slate-700"><?= htmlspecialchars($t['name']) ?></p>
                                        <p class="text-xs text-slate-400 max-w-[150px] truncate"><?= htmlspecialchars($t['server_url'] ?: 'No URL') ?></p>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <p class="text-sm font-bold text-slate-800"><?= number_format($t['hits']) ?></p>
                                    <p class="text-[10px] text-slate-400 uppercase">Req.</p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <?php if (empty($topTenants)): ?>
                            <div class="text-center py-8 text-slate-400 text-sm italic">Aucune donnée</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Detailed Instance Status Table -->
            <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
                <div class="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
                    <h3 class="font-bold text-slate-800 flex items-center gap-2">
                        <i class="fa-solid fa-list-ul text-slate-400"></i>
                        Statut des Instances
                    </h3>
                    <button class="text-xs text-indigo-600 font-medium hover:underline" onclick="location.reload()">
                        <i class="fa-solid fa-rotate-right mr-1"></i> Rafraîchir
                    </button>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-slate-50 border-b border-slate-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">Client / Instance</th>
                                <th class="px-6 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">Environnement</th>
                                <th class="px-6 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">Dernier IP</th>
                                <th class="px-6 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider">Dernier Contact</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <?php foreach ($instances as $instance): 
                                $isOnline = !empty($instance['last_heartbeat']) && strtotime($instance['last_heartbeat']) > strtotime('-5 minutes');
                            ?>
                                <tr class="hover:bg-slate-50 transition-colors">
                                    <td class="px-6 py-4">
                                        <div class="flex items-center gap-3">
                                            <div class="w-10 h-10 rounded-lg <?= $isOnline ? 'bg-emerald-100 text-emerald-600' : 'bg-slate-100 text-slate-400' ?> flex items-center justify-center text-xl">
                                                <i class="fa-brands fa-laravel"></i>
                                            </div>
                                            <div>
                                                <p class="text-sm font-bold text-slate-800"><?= htmlspecialchars($instance['tenant_name']) ?></p>
                                                <p class="text-xs text-slate-400 font-mono"><?= htmlspecialchars($instance['tenant_code']) ?></p>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="px-2.5 py-1 rounded-full text-xs font-medium border <?= $instance['environment'] === 'production' ? 'bg-purple-50 text-purple-700 border-purple-100' : 'bg-slate-100 text-slate-600 border-slate-200' ?>">
                                            <?= ucfirst($instance['environment'] ?: 'Production') ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <?php if ($isOnline): ?>
                                            <span class="flex items-center gap-2 text-emerald-600 text-xs font-bold bg-emerald-50 px-3 py-1 rounded-full w-fit">
                                                <span class="relative flex h-2 w-2">
                                                  <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                                                  <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
                                                </span>
                                                ONLINE
                                            </span>
                                        <?php else: ?>
                                            <span class="flex items-center gap-2 text-slate-500 text-xs font-bold bg-slate-100 px-3 py-1 rounded-full w-fit">
                                                <span class="h-2 w-2 rounded-full bg-slate-400"></span>
                                                OFFLINE
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-6 py-4 text-xs font-mono text-slate-500">
                                        <?= htmlspecialchars($instance['last_ip'] ?: 'Unknown') ?>
                                    </td>
                                    <td class="px-6 py-4">
                                        <p class="text-sm font-medium text-slate-700">
                                            <?= $instance['last_heartbeat'] ? date('H:i:s', strtotime($instance['last_heartbeat'])) : '-' ?>
                                        </p>
                                        <p class="text-xs text-slate-400">
                                            <?= $instance['last_heartbeat'] ? date('d/m/Y', strtotime($instance['last_heartbeat'])) : 'Jamais' ?>
                                        </p>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </main>

    <script>
        // Chart.js Configuration
        const ctx = document.getElementById('activityChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?= json_encode($chartData['labels']) ?>,
                datasets: [{
                    label: 'Requêtes journalières',
                    data: <?= json_encode($chartData['values']) ?>,
                    borderColor: '#4f46e5',
                    backgroundColor: 'rgba(79, 70, 229, 0.1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    pointBackgroundColor: '#fff',
                    pointBorderColor: '#4f46e5',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: '#1e293b',
                        padding: 12,
                        titleFont: { size: 13 },
                        bodyFont: { size: 13 },
                        displayColors: false,
                        cornerRadius: 8
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: { color: '#f1f5f9', drawBorder: false },
                        ticks: { font: { size: 11 }, color: '#64748b' }
                    },
                    x: {
                        grid: { display: false },
                        ticks: { font: { size: 11 }, color: '#64748b' }
                    }
                },
                interaction: {
                    intersect: false,
                    mode: 'index',
                },
            }
        });
    </script>
</body>
</html>
