<?php
/**
 * Admin Dashboard - Premium Modern Design
 */
require_once '../config.php';
$admin = isAdminLogged();

// ==========================================
// FETCH ALL DASHBOARD STATISTICS
// ==========================================

// Tenants Stats
$stmt = $pdo->query("SELECT COUNT(*) as total, 
    SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
    SUM(CASE WHEN status = 'trial' THEN 1 ELSE 0 END) as trial,
    SUM(CASE WHEN status = 'suspended' THEN 1 ELSE 0 END) as suspended
    FROM tenants");
$stats['tenants'] = $stmt->fetch();

// Instances Stats
$stmt = $pdo->query("SELECT COUNT(*) as total,
    SUM(CASE WHEN last_heartbeat > DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 ELSE 0 END) as online,
    SUM(CASE WHEN last_heartbeat <= DATE_SUB(NOW(), INTERVAL 1 HOUR) OR last_heartbeat IS NULL THEN 1 ELSE 0 END) as offline
    FROM instances WHERE is_active = 1");
$stats['instances'] = $stmt->fetch();

// Subscriptions Stats
$stmt = $pdo->query("SELECT COUNT(*) as total FROM subscriptions WHERE status = 'active'");
$stats['subscriptions'] = $stmt->fetch();

// Module Stats
$stmt = $pdo->query("SELECT COUNT(*) as total FROM modules");
$stats['modules'] = $stmt->fetch();

// Advertising Stats
$adStats = ['total_ads' => 0, 'total_views' => 0, 'total_clicks' => 0];
try {
    $stmt = $pdo->query("SELECT COUNT(*) as total_ads, SUM(views) as total_views, SUM(clicks) as total_clicks FROM server_ads WHERE is_active = 1");
    $adStats = $stmt->fetch() ?: $adStats;
} catch (Exception $e) {}

// Recent Activity (Last 10 heartbeats)
$stmt = $pdo->query("SELECT t.name, t.code, i.server_url, i.last_heartbeat
    FROM instances i 
    JOIN tenants t ON i.tenant_id = t.id 
    WHERE i.is_active = 1 
    ORDER BY i.last_heartbeat DESC LIMIT 8");
$recentActivity = $stmt->fetchAll();

// Expiring Soon (Next 30 days)
$stmt = $pdo->query("SELECT t.name, t.code, s.expires_at, s.plan_type
    FROM subscriptions s 
    JOIN tenants t ON s.tenant_id = t.id 
    WHERE s.status = 'active' AND s.expires_at BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
    ORDER BY s.expires_at ASC LIMIT 5");
$expiringSoon = $stmt->fetchAll();

// New Clients (Last 7 days)
$stmt = $pdo->query("SELECT COUNT(*) as count FROM tenants WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
$newClients = $stmt->fetch()['count'] ?? 0;

// Suspended Clients
$suspendedCount = $stats['tenants']['suspended'] ?? 0;

// Weekly Activity Trend (for chart)
$weeklyTrend = [];
try {
    $stmt = $pdo->query("
        SELECT DATE(last_heartbeat) as date, COUNT(DISTINCT tenant_id) as active_tenants
        FROM instances 
        WHERE last_heartbeat >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        GROUP BY DATE(last_heartbeat)
        ORDER BY date ASC
    ");
    $weeklyTrend = $stmt->fetchAll();
} catch (Exception $e) {}

$currentPage = 'dashboard';
$pageTitle = 'Dashboard - License Server';
?>
<?php include 'includes/header.php'; ?>
    
    <?php include 'includes/sidebar.php'; ?>

    <main class="ml-60 p-8">
        <div class="max-w-7xl mx-auto">
            
            <!-- Header with Welcome -->
            <div class="flex justify-between items-start mb-8">
                <div>
                    <h1 class="text-3xl font-black text-slate-800 dark:text-white">
                        Bonjour, <span class="bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent"><?= htmlspecialchars($admin['username']) ?></span> 👋
                    </h1>
                    <p class="text-slate-500 dark:text-slate-400 mt-1">Vue d'ensemble du système de licences</p>
                </div>
                <div class="flex items-center gap-3">
                    <span class="text-xs text-slate-400 dark:text-slate-500"><?= date('l d F Y', strtotime('now')) ?></span>
                    <div class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
                    <span class="text-xs font-medium text-emerald-600 dark:text-emerald-400">Système Opérationnel</span>
                </div>
            </div>

            <!-- Main KPIs Grid -->
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
                
                <!-- Clients Total -->
                <div class="gradient-border">
                    <div class="p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-xl flex items-center justify-center shadow-lg shadow-indigo-200">
                                <i class="fa-solid fa-building text-white text-sm"></i>
                            </div>
                        </div>
                        <div class="text-3xl font-black text-slate-800 dark:text-white"><?= $stats['tenants']['total'] ?? 0 ?></div>
                        <div class="text-xs text-slate-500 dark:text-slate-400 font-medium">Clients Total</div>
                        <div class="mt-2 flex items-center gap-2">
                            <span class="text-[10px] font-bold px-1.5 py-0.5 rounded bg-emerald-100 dark:bg-emerald-900 text-emerald-700 dark:text-emerald-300"><?= $stats['tenants']['active'] ?? 0 ?> actifs</span>
                        </div>
                    </div>
                </div>

                <!-- Instances Online -->
                <div class="bg-white dark:bg-slate-800 rounded-2xl p-5 border border-slate-100 dark:border-slate-700 shadow-sm">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center">
                            <i class="fa-solid fa-server text-emerald-600 text-sm"></i>
                        </div>
                        <div class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
                    </div>
                    <div class="text-3xl font-black text-slate-800 dark:text-white"><?= $stats['instances']['online'] ?? 0 ?></div>
                    <div class="text-xs text-slate-500 dark:text-slate-400 font-medium">En Ligne</div>
                    <div class="mt-2 text-[10px] text-slate-400"><?= $stats['instances']['total'] ?? 0 ?> instances total</div>
                </div>

                <!-- Abonnements -->
                <div class="bg-white rounded-2xl p-5 border border-slate-100 shadow-sm">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center">
                            <i class="fa-solid fa-file-contract text-blue-600 text-sm"></i>
                        </div>
                    </div>
                    <div class="text-3xl font-black text-slate-800 dark:text-white"><?= $stats['subscriptions']['total'] ?? 0 ?></div>
                    <div class="text-xs text-slate-500 dark:text-slate-400 font-medium">Abonnements</div>
                </div>

                <!-- Trial -->
                <div class="bg-white rounded-2xl p-5 border border-slate-100 shadow-sm">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center">
                            <i class="fa-solid fa-flask text-amber-600 text-sm"></i>
                        </div>
                    </div>
                    <div class="text-3xl font-black text-slate-800 dark:text-white"><?= $stats['tenants']['trial'] ?? 0 ?></div>
                    <div class="text-xs text-slate-500 dark:text-slate-400 font-medium">En Essai</div>
                </div>

                <!-- Nouveaux (7j) -->
                <div class="bg-white rounded-2xl p-5 border border-slate-100 shadow-sm">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-10 h-10 bg-teal-100 rounded-xl flex items-center justify-center">
                            <i class="fa-solid fa-user-plus text-teal-600 text-sm"></i>
                        </div>
                    </div>
                    <div class="text-3xl font-black text-slate-800 dark:text-white">+<?= $newClients ?></div>
                    <div class="text-xs text-slate-500 dark:text-slate-400 font-medium">Nouveaux (7j)</div>
                </div>

                <!-- Suspendus -->
                <div class="bg-white rounded-2xl p-5 border border-slate-100 shadow-sm <?= $suspendedCount > 0 ? 'ring-2 ring-red-200' : '' ?>">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-10 h-10 bg-red-100 rounded-xl flex items-center justify-center">
                            <i class="fa-solid fa-ban text-red-600 text-sm"></i>
                        </div>
                    </div>
                    <div class="text-3xl font-black <?= $suspendedCount > 0 ? 'text-red-600' : 'text-slate-800' ?>"><?= $suspendedCount ?></div>
                    <div class="text-xs text-slate-500 dark:text-slate-400 font-medium">Suspendus</div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-6 border border-slate-100 dark:border-slate-700 shadow-sm mb-8">
                <h3 class="font-bold text-slate-800 dark:text-white mb-4"><i class="fa-solid fa-bolt text-amber-500 mr-2"></i>Actions Rapides</h3>
                <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
                    <a href="tenants.php" class="flex flex-col items-center gap-2 p-4 rounded-xl bg-slate-50 dark:bg-slate-700 hover:bg-indigo-50 dark:hover:bg-slate-600 border border-transparent transition-all group">
                        <div class="w-10 h-10 bg-indigo-100 dark:bg-indigo-900 rounded-xl flex items-center justify-center group-hover:bg-indigo-200 transition-colors">
                            <i class="fa-solid fa-plus text-indigo-600 dark:text-indigo-400"></i>
                        </div>
                        <span class="text-xs font-medium text-slate-600 dark:text-slate-300">Nouveau Client</span>
                    </a>
                    <a href="subscriptions.php" class="flex flex-col items-center gap-2 p-4 rounded-xl bg-slate-50 hover:bg-blue-50 hover:border-blue-200 border border-transparent transition-all group">
                        <div class="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center group-hover:bg-blue-200 transition-colors">
                            <i class="fa-solid fa-file-signature text-blue-600"></i>
                        </div>
                        <span class="text-xs font-medium text-slate-600">Abonnements</span>
                    </a>
                    <a href="modules.php" class="flex flex-col items-center gap-2 p-4 rounded-xl bg-slate-50 hover:bg-purple-50 hover:border-purple-200 border border-transparent transition-all group">
                        <div class="w-10 h-10 bg-purple-100 rounded-xl flex items-center justify-center group-hover:bg-purple-200 transition-colors">
                            <i class="fa-solid fa-puzzle-piece text-purple-600"></i>
                        </div>
                        <span class="text-xs font-medium text-slate-600">Modules</span>
                    </a>
                    <a href="plans.php" class="flex flex-col items-center gap-2 p-4 rounded-xl bg-slate-50 hover:bg-emerald-50 hover:border-emerald-200 border border-transparent transition-all group">
                        <div class="w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center group-hover:bg-emerald-200 transition-colors">
                            <i class="fa-solid fa-tags text-emerald-600"></i>
                        </div>
                        <span class="text-xs font-medium text-slate-600">Plans</span>
                    </a>
                    <a href="advertising.php" class="flex flex-col items-center gap-2 p-4 rounded-xl bg-slate-50 hover:bg-rose-50 hover:border-rose-200 border border-transparent transition-all group">
                        <div class="w-10 h-10 bg-rose-100 rounded-xl flex items-center justify-center group-hover:bg-rose-200 transition-colors">
                            <i class="fa-solid fa-rectangle-ad text-rose-600"></i>
                        </div>
                        <span class="text-xs font-medium text-slate-600">Publicité</span>
                    </a>
                    <a href="telemetry.php" class="flex flex-col items-center gap-2 p-4 rounded-xl bg-slate-50 hover:bg-cyan-50 hover:border-cyan-200 border border-transparent transition-all group">
                        <div class="w-10 h-10 bg-cyan-100 rounded-xl flex items-center justify-center group-hover:bg-cyan-200 transition-colors">
                            <i class="fa-solid fa-chart-simple text-cyan-600"></i>
                        </div>
                        <span class="text-xs font-medium text-slate-600">Télémétrie</span>
                    </a>
                </div>
            </div>

            <!-- Two Column Layout -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
                
                <!-- Recent Activity Feed -->
                <div class="bg-white rounded-2xl p-6 border border-slate-100 shadow-sm">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="font-bold text-slate-800">
                            <i class="fa-solid fa-clock-rotate-left text-indigo-500 mr-2"></i>Activité en Direct
                        </h3>
                        <span class="text-xs text-slate-400">Dernière heure</span>
                    </div>
                    <div class="space-y-3 max-h-[300px] overflow-y-auto">
                        <?php if (empty($recentActivity)): ?>
                            <p class="text-slate-400 text-sm italic py-8 text-center">Aucune activité récente</p>
                        <?php else: ?>
                            <?php foreach ($recentActivity as $activity): 
                                $isOnline = $activity['last_heartbeat'] && strtotime($activity['last_heartbeat']) > strtotime('-1 hour');
                            ?>
                                <div class="flex items-center justify-between p-3 bg-slate-50 rounded-xl hover:bg-slate-100 transition-colors">
                                    <div class="flex items-center gap-3">
                                        <div class="w-8 h-8 rounded-lg bg-indigo-100 flex items-center justify-center text-indigo-600 text-xs font-bold">
                                            <?= strtoupper(substr($activity['code'] ?? $activity['name'], 0, 2)) ?>
                                        </div>
                                        <div>
                                            <p class="text-slate-700 font-medium text-sm"><?= htmlspecialchars($activity['name']) ?></p>
                                            <p class="text-slate-400 text-[10px] flex items-center gap-1">
                                                <i class="fa-solid fa-globe"></i>
                                                <?= htmlspecialchars($activity['server_url'] ?? 'N/A') ?>
                                            </p>
                                        </div>
                                    </div>
                                    <div class="text-right">
                                        <span class="flex items-center gap-1 text-xs <?= $isOnline ? 'text-emerald-600' : 'text-slate-400' ?>">
                                            <span class="w-1.5 h-1.5 rounded-full <?= $isOnline ? 'bg-emerald-500' : 'bg-slate-300' ?>"></span>
                                            <?= $activity['last_heartbeat'] ? date('H:i', strtotime($activity['last_heartbeat'])) : 'N/A' ?>
                                        </span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Expiring Soon -->
                <div class="bg-white rounded-2xl p-6 border border-slate-100 shadow-sm">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="font-bold text-slate-800">
                            <i class="fa-solid fa-calendar-xmark text-amber-500 mr-2"></i>Expirations Proches
                        </h3>
                        <span class="text-xs text-slate-400">30 prochains jours</span>
                    </div>
                    <div class="space-y-3">
                        <?php if (empty($expiringSoon)): ?>
                            <div class="text-center py-8">
                                <div class="w-16 h-16 bg-emerald-50 rounded-full flex items-center justify-center mx-auto mb-3">
                                    <i class="fa-solid fa-check text-emerald-500 text-2xl"></i>
                                </div>
                                <p class="text-slate-500 text-sm">Aucune expiration dans les 30 jours</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($expiringSoon as $exp): 
                                $daysLeft = (strtotime($exp['expires_at']) - time()) / 86400;
                                $urgency = $daysLeft <= 7 ? 'red' : ($daysLeft <= 14 ? 'amber' : 'slate');
                            ?>
                                <div class="flex items-center justify-between p-3 bg-<?= $urgency ?>-50 rounded-xl border border-<?= $urgency ?>-100">
                                    <div class="flex items-center gap-3">
                                        <div class="w-8 h-8 rounded-lg bg-<?= $urgency ?>-100 flex items-center justify-center text-<?= $urgency ?>-600 text-xs font-bold">
                                            <?= strtoupper(substr($exp['code'] ?? $exp['name'], 0, 2)) ?>
                                        </div>
                                        <div>
                                            <p class="text-slate-700 font-medium text-sm"><?= htmlspecialchars($exp['name']) ?></p>
                                            <p class="text-[10px] text-slate-400 uppercase"><?= $exp['plan_type'] ?? 'N/A' ?></p>
                                        </div>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-xs font-bold text-<?= $urgency ?>-600"><?= date('d/m/Y', strtotime($exp['expires_at'])) ?></p>
                                        <p class="text-[10px] text-<?= $urgency ?>-500"><?= round($daysLeft) ?> jours</p>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Advertising Stats -->
            <?php if ($adStats['total_ads'] > 0): ?>
            <div class="bg-gradient-to-r from-rose-500 to-orange-500 rounded-2xl p-6 text-white mb-8">
                <div class="flex justify-between items-center">
                    <div>
                        <h3 class="font-bold text-lg mb-1"><i class="fa-solid fa-rectangle-ad mr-2"></i>Publicité</h3>
                        <p class="text-rose-100 text-sm">Performance des annonces actives</p>
                    </div>
                    <a href="ad_analytics.php" class="bg-white/20 hover:bg-white/30 px-4 py-2 rounded-lg text-sm font-medium transition-colors">
                        Voir Analytics <i class="fa-solid fa-arrow-right ml-1"></i>
                    </a>
                </div>
                <div class="grid grid-cols-4 gap-4 mt-4">
                    <div class="bg-white/10 rounded-xl p-4 text-center">
                        <div class="text-2xl font-black"><?= $adStats['total_ads'] ?? 0 ?></div>
                        <div class="text-xs text-rose-100">Pubs Actives</div>
                    </div>
                    <div class="bg-white/10 rounded-xl p-4 text-center">
                        <div class="text-2xl font-black"><?= number_format($adStats['total_views'] ?? 0) ?></div>
                        <div class="text-xs text-rose-100">Impressions</div>
                    </div>
                    <div class="bg-white/10 rounded-xl p-4 text-center">
                        <div class="text-2xl font-black"><?= number_format($adStats['total_clicks'] ?? 0) ?></div>
                        <div class="text-xs text-rose-100">Clics</div>
                    </div>
                    <div class="bg-white/10 rounded-xl p-4 text-center">
                        <?php $ctr = ($adStats['total_views'] > 0) ? round(($adStats['total_clicks'] / $adStats['total_views']) * 100, 1) : 0; ?>
                        <div class="text-2xl font-black"><?= $ctr ?>%</div>
                        <div class="text-xs text-rose-100">CTR</div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Footer -->
            <div class="text-center text-slate-400 text-xs py-4">
                License Server v2.0 &copy; <?= date('Y') ?> — Administration Panel
            </div>

        </div>
    </main>

</body>
</html>
