<?php
require_once __DIR__ . '/includes/layout.php';
require_login();

$stats = get_dashboard_stats();
$total = max(1, (int) $stats['total_devices']);
$pctOnline = round(($stats['online_now'] / $total) * 100);
$pctToday = round(($stats['online_today'] / $total) * 100);
$pctIdle = round(($stats['idle_count'] / $total) * 100);
$pctOffline = round(($stats['offline_count'] / $total) * 100);
$pctBranded = $stats['total_devices'] > 0
    ? round(($stats['branded_count'] / $stats['total_devices']) * 100)
    : 0;
$healthClass = $stats['health_score'] >= 80 ? 'good' : ($stats['health_score'] >= 50 ? 'warn' : 'bad');

render_header(
    'Dashboard',
    'dashboard',
    'Monitoramento em tempo real da infraestrutura',
    [['label' => 'Dashboard', 'url' => null]]
);
?>

<?php if (!$stats['uploads_writable']): ?>
<div class="alert-banner alert-danger">
    <strong>⚠️ Uploads indisponíveis</strong> — A pasta <code>uploads/</code> não tem permissão de escrita. Logo, wallpaper e APKs não funcionarão.
</div>
<?php endif; ?>
<?php if ($stats['dns_active'] === 0): ?>
<div class="alert-banner alert-warning">
    <strong>🌐 Sem DNS ativo</strong> — Nenhum servidor Xtream configurado. Os dispositivos não conseguirão conectar IPTV.
    <a href="dns.php" class="alert-link">Configurar DNS →</a>
</div>
<?php endif; ?>

<section class="dashboard-grid dashboard-grid-6">
    <div class="kpi-card kpi-primary">
        <div class="kpi-head"><span class="kpi-label">Dispositivos</span><span class="kpi-icon">📺</span></div>
        <div class="kpi-value"><?= (int) $stats['total_devices'] ?></div>
        <div class="kpi-foot"><span class="trend up">+<?= (int) $stats['new_week'] ?> / semana</span></div>
    </div>
    <div class="kpi-card kpi-success">
        <div class="kpi-head"><span class="kpi-label">Online agora</span><span class="kpi-icon">🟢</span></div>
        <div class="kpi-value"><?= (int) $stats['online_now'] ?></div>
        <div class="kpi-foot"><span>Últimos 15 min</span></div>
    </div>
    <div class="kpi-card kpi-cyan">
        <div class="kpi-head"><span class="kpi-label">Ativos hoje</span><span class="kpi-icon">📡</span></div>
        <div class="kpi-value"><?= (int) $stats['online_today'] ?></div>
        <div class="kpi-foot"><span>Desde meia-noite</span></div>
    </div>
    <div class="kpi-card kpi-purple">
        <div class="kpi-head"><span class="kpi-label">Apps totais</span><span class="kpi-icon">📱</span></div>
        <div class="kpi-value"><?= (int) $stats['total_apps'] ?></div>
        <div class="kpi-foot"><span>Máx. <?= MAX_APPS ?> / ID</span></div>
    </div>
    <div class="kpi-card kpi-danger">
        <div class="kpi-head"><span class="kpi-label">Bloqueados</span><span class="kpi-icon">⛔</span></div>
        <div class="kpi-value"><?= (int) $stats['blocked_count'] ?></div>
        <div class="kpi-foot"><span><?= (int) $stats['locked_count'] ?> com senha</span></div>
    </div>
    <div class="kpi-card kpi-health kpi-<?= $healthClass ?>">
        <div class="kpi-head"><span class="kpi-label">Saúde geral</span><span class="kpi-icon">💚</span></div>
        <div class="kpi-value"><?= (int) $stats['health_score'] ?><small>%</small></div>
        <div class="kpi-foot"><span>Score do ecossistema</span></div>
    </div>
</section>

<section class="monitor-grid">
    <div class="card monitor-card monitor-blue">
        <h2>🖥️ Infraestrutura</h2>
        <div class="monitor-items">
            <div class="monitor-item">
                <span class="monitor-dot ok"></span>
                <div><strong>Banco MySQL</strong><span>Conectado</span></div>
            </div>
            <div class="monitor-item">
                <span class="monitor-dot <?= $stats['uploads_writable'] ? 'ok' : 'err' ?>"></span>
                <div><strong>Uploads</strong><span><?= $stats['uploads_writable'] ? 'Gravável' : 'Erro de permissão' ?></span></div>
            </div>
            <div class="monitor-item">
                <span class="monitor-dot <?= $stats['dns_active'] > 0 ? 'ok' : 'warn' ?>"></span>
                <div><strong>DNS Xtream</strong><span><?= (int) $stats['dns_active'] ?>/<?= (int) $stats['dns_total'] ?> ativos</span></div>
            </div>
            <div class="monitor-item">
                <span class="monitor-dot ok"></span>
                <div><strong>API REST</strong><span>PHP <?= htmlspecialchars($stats['php_version']) ?></span></div>
            </div>
        </div>
    </div>

    <div class="card monitor-card monitor-green">
        <h2>📊 Presença dos dispositivos</h2>
        <?php if ($stats['total_devices'] === 0): ?>
            <p class="card-desc">Nenhum aparelho registrado ainda.</p>
        <?php else: ?>
            <div class="dist-bars">
                <div class="dist-row">
                    <span class="dist-label"><span class="dot dot-green"></span> Online agora</span>
                    <div class="dist-track"><div class="dist-fill fill-green" style="width:<?= $pctOnline ?>%"></div></div>
                    <span class="dist-num"><?= (int) $stats['online_now'] ?></span>
                </div>
                <div class="dist-row">
                    <span class="dist-label"><span class="dot dot-blue"></span> Ativos hoje</span>
                    <div class="dist-track"><div class="dist-fill fill-blue" style="width:<?= $pctToday ?>%"></div></div>
                    <span class="dist-num"><?= (int) $stats['online_today'] ?></span>
                </div>
                <div class="dist-row">
                    <span class="dist-label"><span class="dot dot-yellow"></span> Esta semana</span>
                    <div class="dist-track"><div class="dist-fill fill-yellow" style="width:<?= $pctIdle ?>%"></div></div>
                    <span class="dist-num"><?= (int) $stats['idle_count'] ?></span>
                </div>
                <div class="dist-row">
                    <span class="dist-label"><span class="dot dot-gray"></span> Inativos</span>
                    <div class="dist-track"><div class="dist-fill fill-gray" style="width:<?= $pctOffline ?>%"></div></div>
                    <span class="dist-num"><?= (int) $stats['offline_count'] ?></span>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <div class="card monitor-card monitor-purple">
        <h2>🎨 Personalização</h2>
        <div class="metric-rows">
            <div class="metric-row"><span>Com logo</span><strong class="text-blue"><?= (int) $stats['with_logo'] ?></strong></div>
            <div class="metric-row"><span>Com wallpaper</span><strong class="text-purple"><?= (int) $stats['with_wallpaper'] ?></strong></div>
            <div class="metric-row"><span>Branding completo</span><strong class="text-green"><?= (int) $stats['branded_count'] ?></strong></div>
        </div>
        <div class="progress-block">
            <div class="progress-label"><span>Cobertura visual</span><span class="text-purple"><?= $pctBranded ?>%</span></div>
            <div class="progress-bar progress-purple"><div class="progress-fill fill-purple" style="width:<?= $pctBranded ?>%"></div></div>
        </div>
    </div>

    <div class="card monitor-card monitor-orange">
        <h2>🔒 Segurança</h2>
        <div class="security-stats">
            <div class="sec-stat sec-green">
                <span class="sec-num"><?= (int) $stats['active_count'] ?></span>
                <span class="sec-label">Operacionais</span>
            </div>
            <div class="sec-stat sec-red">
                <span class="sec-num"><?= (int) $stats['blocked_count'] ?></span>
                <span class="sec-label">Bloqueados</span>
            </div>
            <div class="sec-stat sec-yellow">
                <span class="sec-num"><?= (int) $stats['locked_count'] ?></span>
                <span class="sec-label">Config 🔒</span>
            </div>
        </div>
        <a href="devices.php" class="btn secondary btn-sm" style="width:100%;margin-top:14px;">Ver dispositivos →</a>
    </div>
</section>

<section class="content-split">
    <div class="content-main">
        <div class="card">
            <div class="card-header">
                <div>
                    <h2>🕐 Atividade recente</h2>
                    <p class="card-desc">Últimos aparelhos que comunicaram com o painel</p>
                </div>
                <a href="devices.php" class="btn primary btn-sm">Todos os dispositivos</a>
            </div>
            <?php if (empty($stats['recent_activity'])): ?>
                <p class="card-desc">Nenhuma atividade registrada.</p>
            <?php else: ?>
                <ul class="activity-feed">
                    <?php foreach ($stats['recent_activity'] as $item): ?>
                        <?php $presence = device_presence_status($item['last_seen_at']); ?>
                        <li class="activity-item">
                            <span class="activity-dot <?= htmlspecialchars($presence['class']) ?>"></span>
                            <div class="activity-body">
                                <strong><?= htmlspecialchars($item['label'] ?: 'Dispositivo') ?></strong>
                                <span><?= htmlspecialchars($item['device_model'] ?: 'Modelo desconhecido') ?> · <?= htmlspecialchars(format_device_seen($item['last_seen_at'])) ?></span>
                            </div>
                            <?php if ((int) $item['launcher_blocked'] === 1): ?>
                                <span class="status-pill off">Bloq.</span>
                            <?php else: ?>
                                <span class="presence-pill <?= htmlspecialchars($presence['class']) ?>"><?= htmlspecialchars($presence['label']) ?></span>
                            <?php endif; ?>
                            <a href="device.php?id=<?= urlencode($item['id']) ?>" class="btn secondary btn-sm">Abrir</a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </div>
    </div>

    <aside class="content-side">
        <div class="card quick-card quick-blue">
            <h2>Ações rápidas</h2>
            <div class="quick-actions">
                <a href="devices.php" class="quick-btn">📺 Dispositivos</a>
                <a href="dns.php" class="quick-btn">🌐 DNS Xtream</a>
                <a href="credentials.php" class="quick-btn">🔑 Credenciais</a>
            </div>
        </div>

        <div class="card">
            <h2>Endpoints API</h2>
            <div class="endpoint-list">
                <div class="endpoint-item">
                    <span class="endpoint-method post">POST</span>
                    <code>/api/v1/register.php</code>
                </div>
                <div class="endpoint-item">
                    <span class="endpoint-method get">GET</span>
                    <code>/api/v1/config.php?device_id=</code>
                </div>
            </div>
        </div>

        <div class="card monitor-card monitor-dark">
            <h2>Servidor</h2>
            <div class="metric-rows">
                <div class="metric-row"><span>Horário</span><strong><?= htmlspecialchars($stats['server_time']) ?></strong></div>
                <div class="metric-row"><span>PHP</span><strong><?= htmlspecialchars($stats['php_version']) ?></strong></div>
                <div class="metric-row"><span>URL painel</span><strong style="font-size:0.75rem;"><?= htmlspecialchars(PANEL_BASE_URL) ?></strong></div>
            </div>
        </div>
    </aside>
</section>

<?php render_footer(); ?>
