<?php
require_once __DIR__.'/includes/config.php';
require_login();
$db = db();
$portals = get_portals();
$totalDns = count($portals);
$totalUsers = (int)$db->querySingle('SELECT COUNT(*) FROM users');
$activeMessages = (int)$db->querySingle("SELECT COUNT(*) FROM screen_messages WHERE is_active=1");
$historyToday = (int)$db->querySingle("SELECT COUNT(*) FROM screen_message_hits WHERE date(shown_at)=date('now','localtime')");
$logo = $db->querySingle('SELECT * FROM screen_logo WHERE id=1', true) ?: [];
$logoAtiva = ((int)($logo['is_active'] ?? 0) === 1);
$lastMessages = $db->query('SELECT id,title,message,is_active,created_at FROM screen_messages ORDER BY id DESC LIMIT 5');
include __DIR__.'/includes/header.php';
?>
<?php if(($_SESSION['role'] ?? 'admin') !== 'admin'): ?>
<?php
$myPanelNotices=[];
$st=$db->prepare('SELECT * FROM panel_notices WHERE is_active=1 AND target_type=:t AND target_id=:id ORDER BY id DESC LIMIT 3');
$st->bindValue(':t', current_owner_type(), SQLITE3_TEXT);
$st->bindValue(':id', current_owner_id(), SQLITE3_INTEGER);
$res=$st->execute();
while($n=$res->fetchArray(SQLITE3_ASSOC)) $myPanelNotices[]=$n;
?>
<div class="card">
    <h3>📨 Avisos do Admin</h3>
    <?php if(!$myPanelNotices): ?><p class="muted">Nenhum aviso no momento.</p><?php endif; ?>
    <?php foreach($myPanelNotices as $n): ?>
        <div style="padding:12px;border:1px solid rgba(255,138,0,.22);border-radius:12px;margin:10px 0;background:#0b111a">
            <b><?=h($n['title'] ?: 'Aviso do Admin')?></b>
            <div class="muted"><?=h($n['created_at'])?></div>
            <div style="white-space:pre-wrap;margin-top:8px"><?=h($n['message'])?></div>
        </div>
    <?php endforeach; ?>
    <p><a class="btn dark" href="meus_avisos.php">Ver todos</a></p>
</div>
<?php endif; ?>

<div class="grid stats-grid">
    <div class="stat-card"><div class="stat-icon">🌐</div><div class="stat-label">DNS configurados</div><div class="stat-value"><?=$totalDns?></div><div class="stat-note">servidores cadastrados</div></div>
    <div class="stat-card"><div class="stat-icon">👤</div><div class="stat-label">Usuários painel</div><div class="stat-value"><?=$totalUsers?></div><div class="stat-note">acesso administrativo</div></div>
    <div class="stat-card"><div class="stat-icon">📢</div><div class="stat-label">Avisos ativos</div><div class="stat-value"><?=$activeMessages?></div><div class="stat-note">mensagens liberadas</div></div>
    <div class="stat-card"><div class="stat-icon">🖼️</div><div class="stat-label">Logo na tela</div><div class="stat-value"><?=$logoAtiva?'ON':'OFF'?></div><div class="stat-note">marca d'água do app</div></div>
</div>

<div class="grid dash-grid" style="margin-top:18px">
    <div class="card">
        <h2>Últimos avisos</h2>
        <p class="muted">Resumo das mensagens cadastradas no painel.</p>
        <table>
            <tr><th>ID</th><th>Título</th><th>Status</th><th>Data</th></tr>
            <?php while($m=$lastMessages->fetchArray(SQLITE3_ASSOC)): ?>
            <tr>
                <td>#<?=h($m['id'])?></td>
                <td><?=h($m['title'] ?: mb_substr($m['message'],0,45))?></td>
                <td><span class="pill"><?=((int)$m['is_active']===1?'Ativo':'Pausado')?></span></td>
                <td><?=h($m['created_at'])?></td>
            </tr>
            <?php endwhile; ?>
        </table>
    </div>
    <div class="card">
        <h2>Ações rápidas</h2>
        <div class="quick-actions">
            <a href="dns.php">🌐 Gerenciar DNS</a>
            <a href="avisos.php#novo">➕ Novo aviso</a>
            <a href="avisos.php#historico">📜 Histórico</a>
            <a href="logo_tela.php">🖼️ Logo na tela</a>
            <a href="avisos.php#limpeza">🗑️ Limpeza auto</a>
            <a href="user.php">👤 Usuário</a>
        </div>
        <div style="margin-top:18px" class="muted">Entregas registradas hoje: <b class="ok"><?=$historyToday?></b></div>
    </div>
</div>
<?php include __DIR__.'/includes/footer.php'; ?>
