<?php
$stats = $stats ?? [];
$servers = $servers ?? [];
$recentActivity = $recentActivity ?? [];
$aggregatedMetrics = $aggregatedMetrics ?? [];
?>

<div class="page-header">
    <h1 class="page-title">Dashboard</h1>
    <p class="page-subtitle">Server overview and system status</p>
</div>

<div class="stats-grid">
    <div class="stat-card stat-card-primary">
        <div class="stat-icon"><i class="fas fa-hdd"></i></div>
        <div class="stat-info">
            <span class="stat-value" id="statTotalServers"><?= $stats['total_servers'] ?? 0 ?></span>
            <span class="stat-label">Total Servers</span>
        </div>
    </div>
    <div class="stat-card stat-card-success">
        <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
        <div class="stat-info">
            <span class="stat-value" id="statOnlineServers"><?= $stats['online_servers'] ?? 0 ?></span>
            <span class="stat-label">Online</span>
        </div>
    </div>
    <div class="stat-card stat-card-danger">
        <div class="stat-icon"><i class="fas fa-times-circle"></i></div>
        <div class="stat-info">
            <span class="stat-value" id="statOfflineServers"><?= $stats['offline_servers'] ?? 0 ?></span>
            <span class="stat-label">Offline</span>
        </div>
    </div>
    <div class="stat-card stat-card-info">
        <div class="stat-icon"><i class="fas fa-microchip"></i></div>
        <div class="stat-info">
            <span class="stat-value" id="statAvgCpu"><?= $stats['avg_cpu'] ?? 0 ?>%</span>
            <span class="stat-label">Avg CPU</span>
        </div>
    </div>
    <div class="stat-card stat-card-warning">
        <div class="stat-icon"><i class="fas fa-memory"></i></div>
        <div class="stat-info">
            <span class="stat-value" id="statAvgRam"><?= $stats['avg_ram'] ?? 0 ?>%</span>
            <span class="stat-label">Avg RAM</span>
        </div>
    </div>
    <div class="stat-card stat-card-purple">
        <div class="stat-icon"><i class="fas fa-hdd"></i></div>
        <div class="stat-info">
            <span class="stat-value" id="statAvgDisk"><?= $stats['avg_disk'] ?? 0 ?>%</span>
            <span class="stat-label">Avg Disk</span>
        </div>
    </div>
</div>

<div class="card" style="margin-bottom:1.5rem">
    <div class="card-header">
        <h2><i class="fas fa-chart-line"></i> Recursos Agregados (24h)</h2>
    </div>
    <div class="card-body">
        <canvas id="aggregatedChart" height="300"></canvas>
    </div>
</div>

<div class="dashboard-grid">
    <div class="dashboard-card">
        <div class="card-header">
            <h2><i class="fas fa-server"></i> Servers</h2>
            <a href="/servers" class="btn btn-sm">View All</a>
        </div>
        <div class="card-body">
            <?php if (empty($servers)): ?>
                <div class="empty-state">
                    <i class="fas fa-server"></i>
                    <p>No servers configured yet.</p>
                    <?php if (is_admin()): ?>
                    <a href="/servers/create" class="btn btn-primary">Add Server</a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>IP</th>
                                <th>Status</th>
                                <th>CPU</th>
                                <th>RAM</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach (array_slice($servers, 0, 8) as $server): ?>
                                <tr>
                                    <td>
                                        <a href="/servers/<?= $server['id'] ?>">
                                            <?= htmlspecialchars($server['name']) ?>
                                        </a>
                                    </td>
                                    <td><code><?= htmlspecialchars($server['ip_address']) ?>:<?= $server['ssh_port'] ?></code></td>
                                    <td>
                                        <span class="status-badge status-<?= $server['current_status'] ?? 'unknown' ?>">
                                            <?= ucfirst($server['current_status'] ?? 'unknown') ?>
                                        </span>
                                    </td>
                                    <td><?= $server['cpu_usage'] ?? '-' ?>%</td>
                                    <td><?= $server['ram_usage'] ?? '-' ?>%</td>
                                    <td>
                                        <a href="/servers/<?= $server['id'] ?>" class="btn btn-xs" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="/terminal/<?= $server['id'] ?>" class="btn btn-xs" title="Terminal">
                                            <i class="fas fa-terminal"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="dashboard-card">
        <div class="card-header">
            <h2><i class="fas fa-history"></i> Recent Activity</h2>
        </div>
        <div class="card-body">
            <?php if (empty($recentActivity)): ?>
                <div class="empty-state">
                    <i class="fas fa-history"></i>
                    <p>No recent activity.</p>
                </div>
            <?php else: ?>
                <div class="activity-list">
                    <?php foreach ($recentActivity as $activity): ?>
                        <div class="activity-item">
                            <div class="activity-icon activity-<?= str_contains($activity['action'] ?? '', 'failed') ? 'danger' : (str_contains($activity['action'] ?? '', 'created') ? 'success' : 'info') ?>">
                                <i class="fas fa-<?= match(true) {
                                    str_contains($activity['action'] ?? '', 'login') => 'sign-in-alt',
                                    str_contains($activity['action'] ?? '', 'server') => 'server',
                                    str_contains($activity['action'] ?? '', 'command') => 'terminal',
                                    str_contains($activity['action'] ?? '', 'user') => 'user',
                                    default => 'circle',
                                } ?>"></i>
                            </div>
                            <div class="activity-details">
                                <span class="activity-action"><?= htmlspecialchars(str_replace('_', ' ', $activity['action'] ?? '')) ?></span>
                                <span class="activity-meta">
                                    <?= htmlspecialchars($activity['actor_name'] ?? $activity['username'] ?? 'System') ?>
                                    &middot; <?= date('H:i', strtotime($activity['created_at'] ?? '')) ?>
                                </span>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"></script>
<script>
const aggregatedData = <?= json_encode($aggregatedMetrics) ?>;

let aggregatedChart = null;

function initAggregatedChart(data) {
    const container = document.getElementById('aggregatedChart').parentNode;
    const oldCanvas = document.getElementById('aggregatedChart');
    const newCanvas = document.createElement('canvas');
    newCanvas.id = 'aggregatedChart';
    newCanvas.height = 300;
    container.replaceChild(newCanvas, oldCanvas);
    const ctx = newCanvas.getContext('2d');
    const labels = data.map(m => {
        const d = new Date(m.time_bucket);
        return d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0');
    });

    aggregatedChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'CPU',
                    data: data.map(m => parseFloat(m.avg_cpu)),
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    fill: true,
                    tension: 0.3,
                    pointRadius: 1,
                },
                {
                    label: 'RAM',
                    data: data.map(m => parseFloat(m.avg_ram)),
                    borderColor: '#22c55e',
                    backgroundColor: 'rgba(34, 197, 94, 0.1)',
                    fill: true,
                    tension: 0.3,
                    pointRadius: 1,
                },
                {
                    label: 'Disk',
                    data: data.map(m => parseFloat(m.avg_disk)),
                    borderColor: '#8b5cf6',
                    backgroundColor: 'rgba(139, 92, 246, 0.1)',
                    fill: true,
                    tension: 0.3,
                    pointRadius: 1,
                },
            ],
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index',
            },
            plugins: {
                legend: {
                    labels: {
                        color: '#9ca3af',
                        font: { family: "'Inter', sans-serif" },
                        boxWidth: 12,
                        padding: 16,
                    },
                },
                tooltip: {
                    backgroundColor: '#1a1d2b',
                    borderColor: '#2a2d3d',
                    borderWidth: 1,
                    titleColor: '#e1e4ed',
                    bodyColor: '#9ca3af',
                    padding: 10,
                    cornerRadius: 8,
                    callbacks: {
                        label: function(ctx) {
                            return ctx.dataset.label + ': ' + ctx.parsed.y.toFixed(1) + '%';
                        },
                    },
                },
            },
            scales: {
                x: {
                    ticks: {
                        color: '#6b7280',
                        maxTicksLimit: 12,
                        font: { size: 11 },
                    },
                    grid: {
                        color: 'rgba(255,255,255,0.04)',
                    },
                },
                y: {
                    min: 0,
                    max: 100,
                    ticks: {
                        color: '#6b7280',
                        font: { size: 11 },
                        callback: function(v) { return v + '%'; },
                    },
                    grid: {
                        color: 'rgba(255,255,255,0.04)',
                    },
                },
            },
        },
    });
}

function refreshAggregatedChart() {
    fetch('/dashboard/chart-data')
        .then(r => r.json())
        .then(response => {
            if (response.success && response.data) {
                const data = response.data;
                const labels = data.map(m => {
                    const d = new Date(m.time_bucket);
                    return d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0');
                });
                if (aggregatedChart) {
                    aggregatedChart.data.labels = labels;
                    aggregatedChart.data.datasets[0].data = data.map(m => parseFloat(m.avg_cpu));
                    aggregatedChart.data.datasets[1].data = data.map(m => parseFloat(m.avg_ram));
                    aggregatedChart.data.datasets[2].data = data.map(m => parseFloat(m.avg_disk));
                    aggregatedChart.update('none');
                } else if (data.length > 0) {
                    initAggregatedChart(data);
                }
            }
        });
}

if (aggregatedData.length > 0) {
    initAggregatedChart(aggregatedData);
}

setInterval(refreshAggregatedChart, 30000);
</script>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
