<?php
require_once 'protege.php';
require_once '../config.php';

$totalClientes = (int)$pdo->query("SELECT COUNT(*) FROM clientes")->fetchColumn();
$totalLicencas = (int)$pdo->query("SELECT COUNT(*) FROM licencas")->fetchColumn();
$licencasAtivas = (int)$pdo->query("SELECT COUNT(*) FROM licencas WHERE status='ativa'")->fetchColumn();
$licencasExpiradas = (int)$pdo->query("SELECT COUNT(*) FROM licencas WHERE status='expirada'")->fetchColumn();
$licencasSuspensas = (int)$pdo->query("SELECT COUNT(*) FROM licencas WHERE status='suspensa'")->fetchColumn();
$licencasBloqueadas = (int)$pdo->query("SELECT COUNT(*) FROM licencas WHERE status='bloqueada'")->fetchColumn();
$totalAtivacoes = (int)$pdo->query("SELECT COUNT(*) FROM ativacoes")->fetchColumn();

$pagamentosPendentes = 0;
$pagamentosPagos = 0;
$receitaTotal = 0;

try {
    $pagamentosPendentes = (int)$pdo->query("SELECT COUNT(*) FROM pagamentos WHERE status='pendente'")->fetchColumn();
    $pagamentosPagos = (int)$pdo->query("SELECT COUNT(*) FROM pagamentos WHERE status='pago'")->fetchColumn();
    $receitaTotal = (float)$pdo->query("SELECT COALESCE(SUM(valor),0) FROM pagamentos WHERE status='pago'")->fetchColumn();
} catch (Exception $e) {
    $pagamentosPendentes = 0;
    $pagamentosPagos = 0;
    $receitaTotal = 0;
}

$stmt = $pdo->query("
    SELECT 
        l.*,
        c.nome AS cliente_nome,
        c.email AS cliente_email,
        COUNT(a.id) AS computadores_ativos
    FROM licencas l
    LEFT JOIN clientes c ON c.id = l.cliente_id
    LEFT JOIN ativacoes a ON a.licenca_id = l.id
    GROUP BY l.id
    ORDER BY l.id DESC
    LIMIT 8
");
$ultimasLicencas = $stmt->fetchAll();

$stmt = $pdo->query("
    SELECT 
        a.*,
        l.chave,
        c.nome AS cliente_nome
    FROM ativacoes a
    INNER JOIN licencas l ON l.id = a.licenca_id
    LEFT JOIN clientes c ON c.id = l.cliente_id
    ORDER BY a.ultimo_acesso DESC
    LIMIT 6
");
$ultimosComputadores = $stmt->fetchAll();

function fmtDataDash($data)
{
    if (!$data) return 'Vitalícia';
    return date('d/m/Y', strtotime($data));
}

function diasDash($data)
{
    if (!$data) return 'Vitalícia';

    $hoje = new DateTime(date('Y-m-d'));
    $fim = new DateTime($data);

    if ($fim < $hoje) return 'Vencida';

    return $hoje->diff($fim)->days . ' dias';
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Dashboard - PromoCreative LED Mapper</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
*{box-sizing:border-box}

:root{
    --bg:#050914;
    --panel:#0b1424;
    --card:#0d182b;
    --card2:#101d33;
    --text:#ffffff;
    --muted:#8fa3c7;
    --line:rgba(255,255,255,.08);
    --blue:#00aaff;
    --cyan:#00d4ff;
    --orange:#ff7a00;
    --green:#00ffa0;
    --red:#ff4d5e;
    --yellow:#ffd166;
}

body{
    margin:0;
    min-height:100vh;
    color:var(--text);
    font-family:Arial,Helvetica,sans-serif;
    background:
        radial-gradient(circle at 8% 12%,rgba(0,170,255,.22),transparent 30%),
        radial-gradient(circle at 92% 82%,rgba(255,122,0,.18),transparent 32%),
        linear-gradient(135deg,#050914,#081426 55%,#050914);
    overflow-x:hidden;
}

body::before{
    content:"";
    position:fixed;
    inset:0;
    background:
        linear-gradient(rgba(255,255,255,.025) 1px, transparent 1px),
        linear-gradient(90deg, rgba(255,255,255,.025) 1px, transparent 1px);
    background-size:44px 44px;
    mask-image:linear-gradient(to bottom,rgba(0,0,0,.8),transparent);
    pointer-events:none;
}

.sidebar{
    width:290px;
    height:100vh;
    position:fixed;
    left:0;
    top:0;
    background:rgba(8,15,29,.94);
    border-right:1px solid var(--line);
    padding:28px;
    backdrop-filter:blur(18px);
    z-index:10;
}

.logo{
    margin-bottom:34px;
    animation:fadeUp .6s ease both;
}

.logo strong{
    display:block;
    font-size:22px;
    line-height:1.15;
    letter-spacing:-.4px;
}

.logo span{
    display:block;
    margin-top:9px;
    color:var(--muted);
    font-size:13px;
}

.nav a{
    display:flex;
    align-items:center;
    justify-content:space-between;
    color:#b7c7e8;
    text-decoration:none;
    padding:14px 15px;
    border-radius:15px;
    margin-bottom:8px;
    transition:.25s ease;
    position:relative;
    overflow:hidden;
}

.nav a::before{
    content:"";
    position:absolute;
    inset:0;
    background:linear-gradient(135deg,rgba(255,122,0,.20),rgba(0,170,255,.20));
    opacity:0;
    transition:.25s ease;
}

.nav a span{
    position:relative;
    z-index:2;
}

.nav a:hover,
.nav a.active{
    color:#fff;
    transform:translateX(4px);
}

.nav a:hover::before,
.nav a.active::before{
    opacity:1;
}

.main{
    margin-left:290px;
    padding:34px;
    position:relative;
    z-index:2;
}

.top{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:20px;
    margin-bottom:28px;
    animation:fadeUp .65s ease both;
}

.top h1{
    margin:0;
    font-size:34px;
    letter-spacing:-1px;
}

.top p{
    margin:9px 0 0;
    color:var(--muted);
    line-height:1.5;
}

.quick{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
}

.btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    text-decoration:none;
    color:#fff;
    padding:13px 17px;
    border-radius:15px;
    font-weight:800;
    font-size:14px;
    background:linear-gradient(135deg,var(--orange),var(--blue));
    box-shadow:0 16px 42px rgba(0,170,255,.18);
    transition:.25s ease;
}

.btn:hover{
    transform:translateY(-2px);
    box-shadow:0 22px 56px rgba(0,170,255,.25);
}

.btn.dark{
    background:#13223a;
    box-shadow:none;
}

.hero{
    background:
        linear-gradient(135deg,rgba(255,122,0,.13),rgba(0,170,255,.11)),
        rgba(13,24,43,.86);
    border:1px solid var(--line);
    border-radius:30px;
    padding:28px;
    margin-bottom:24px;
    box-shadow:0 28px 90px rgba(0,0,0,.36);
    overflow:hidden;
    position:relative;
    animation:fadeUp .75s ease both;
}

.hero::after{
    content:"";
    position:absolute;
    width:260px;
    height:260px;
    border-radius:50%;
    right:-90px;
    top:-90px;
    background:rgba(0,170,255,.14);
    filter:blur(35px);
    animation:pulse 4s ease-in-out infinite;
}

.hero-grid{
    display:grid;
    grid-template-columns:1.2fr .8fr;
    gap:24px;
    position:relative;
    z-index:2;
}

.hero h2{
    margin:0;
    font-size:26px;
}

.hero p{
    color:#b8c7e6;
    line-height:1.6;
    margin:12px 0 0;
}

.system-box{
    background:rgba(5,11,21,.56);
    border:1px solid rgba(255,255,255,.08);
    border-radius:22px;
    padding:20px;
}

.system-box small{
    color:var(--muted);
}

.system-box strong{
    display:block;
    font-size:28px;
    margin-top:8px;
}

.cards{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:18px;
    margin-bottom:24px;
}

.card{
    background:rgba(13,24,43,.92);
    border:1px solid var(--line);
    border-radius:24px;
    padding:22px;
    box-shadow:0 24px 70px rgba(0,0,0,.30);
    position:relative;
    overflow:hidden;
    animation:fadeUp .8s ease both;
    transition:.25s ease;
}

.card:hover{
    transform:translateY(-4px);
    border-color:rgba(0,170,255,.25);
}

.card::after{
    content:"";
    position:absolute;
    width:130px;
    height:130px;
    right:-60px;
    top:-60px;
    background:rgba(0,170,255,.10);
    border-radius:50%;
    filter:blur(16px);
}

.card .label{
    color:var(--muted);
    font-size:13px;
    position:relative;
    z-index:2;
}

.card strong{
    display:block;
    font-size:34px;
    margin-top:10px;
    letter-spacing:-1px;
    position:relative;
    z-index:2;
}

.card .mini{
    color:#6f82a8;
    margin-top:8px;
    font-size:12px;
    position:relative;
    z-index:2;
}

.card.orange::after{background:rgba(255,122,0,.12)}
.card.green::after{background:rgba(0,255,160,.11)}
.card.red::after{background:rgba(255,77,94,.11)}
.card.yellow::after{background:rgba(255,209,102,.11)}

.content-grid{
    display:grid;
    grid-template-columns:1.35fr .65fr;
    gap:22px;
}

.panel{
    background:rgba(13,24,43,.92);
    border:1px solid var(--line);
    border-radius:26px;
    padding:24px;
    box-shadow:0 24px 70px rgba(0,0,0,.30);
    overflow:hidden;
    animation:fadeUp .95s ease both;
}

.panel-head{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
    margin-bottom:18px;
}

.panel h3{
    margin:0;
    font-size:22px;
}

.panel p{
    margin:7px 0 0;
    color:var(--muted);
    font-size:14px;
}

.table-wrap{
    overflow-x:auto;
}

table{
    width:100%;
    border-collapse:collapse;
    min-width:850px;
}

th,td{
    padding:15px 12px;
    border-bottom:1px solid rgba(255,255,255,.07);
    text-align:left;
    font-size:14px;
    vertical-align:top;
}

th{
    color:var(--muted);
    font-weight:normal;
}

.key{
    font-family:Consolas,monospace;
    color:var(--cyan);
    font-weight:800;
}

.small{
    color:var(--muted);
    font-size:13px;
}

.badge{
    display:inline-block;
    padding:7px 11px;
    border-radius:999px;
    font-size:12px;
}

.ativa{background:rgba(0,255,160,.12);color:#9fffc8}
.expirada{background:rgba(255,209,102,.13);color:#ffe58a}
.suspensa{background:rgba(255,122,0,.14);color:#ffc38a}
.bloqueada{background:rgba(255,77,94,.13);color:#ffc1c1}

.side-list{
    display:grid;
    gap:12px;
}

.device{
    background:rgba(5,11,21,.46);
    border:1px solid rgba(255,255,255,.07);
    border-radius:18px;
    padding:15px;
    transition:.25s ease;
}

.device:hover{
    transform:translateX(4px);
    border-color:rgba(0,170,255,.22);
}

.device strong{
    display:block;
    margin-bottom:5px;
}

.empty{
    color:var(--muted);
    padding:22px;
    background:rgba(5,11,21,.42);
    border-radius:18px;
}

@keyframes fadeUp{
    from{
        opacity:0;
        transform:translateY(18px);
    }
    to{
        opacity:1;
        transform:translateY(0);
    }
}

@keyframes pulse{
    0%,100%{opacity:.55;transform:scale(1)}
    50%{opacity:1;transform:scale(1.12)}
}

@media(max-width:1200px){
    .cards{grid-template-columns:repeat(2,1fr)}
    .content-grid{grid-template-columns:1fr}
    .hero-grid{grid-template-columns:1fr}
}

@media(max-width:900px){
    .sidebar{
        position:relative;
        width:100%;
        height:auto;
    }

    .main{
        margin-left:0;
        padding:22px;
    }

    .top{
        flex-direction:column;
        align-items:flex-start;
    }

    .cards{
        grid-template-columns:1fr;
    }
}
</style>
</head>

<body>

<div class="sidebar">
    <div class="logo">
        <strong>PromoCreative<br>LED Mapper</strong>
        <span>Painel master de licenças</span>
    </div>

    <div class="nav">
        <a class="active" href="dashboard.php"><span>Dashboard</span><span>●</span></a>
        <a href="clientes.php"><span>Clientes</span><span>›</span></a>
        <a href="licencas.php"><span>Licenças</span><span>›</span></a>
        <a href="gerar_licenca.php"><span>Gerar Licença</span><span>›</span></a>
        <a href="computadores.php"><span>Computadores</span><span>›</span></a>
        <a href="pagamentos.php"><span>Pagamentos</span><span>›</span></a>
        <a href="logout.php"><span>Sair</span><span>×</span></a>
    </div>
</div>

<div class="main">

    <div class="top">
        <div>
            <h1>Dashboard</h1>
            <p>Controle profissional de clientes, licenças, computadores ativados e renovações.</p>
        </div>

        <div class="quick">
            <a class="btn" href="gerar_licenca.php">+ Nova Licença</a>
            <a class="btn dark" href="pagamentos.php">Pagamentos</a>
        </div>
    </div>

    <div class="hero">
        <div class="hero-grid">
            <div>
                <h2>Sistema de licenciamento online</h2>
                <p>
                    O PromoCreative LED Mapper está pronto para controle por computador,
                    vencimento automático, painel do cliente, pagamentos e renovações.
                </p>
            </div>

            <div class="system-box">
                <small>Receita confirmada</small>
                <strong>R$ <?= number_format($receitaTotal, 2, ',', '.'); ?></strong>
                <small><?= $pagamentosPagos; ?> pagamento(s) marcado(s) como pago</small>
            </div>
        </div>
    </div>

    <div class="cards">
        <div class="card">
            <div class="label">Clientes cadastrados</div>
            <strong><?= $totalClientes; ?></strong>
            <div class="mini">Contas disponíveis no painel do cliente</div>
        </div>

        <div class="card green">
            <div class="label">Licenças ativas</div>
            <strong><?= $licencasAtivas; ?></strong>
            <div class="mini">Autorizadas para uso no programa</div>
        </div>

        <div class="card orange">
            <div class="label">Computadores ativados</div>
            <strong><?= $totalAtivacoes; ?></strong>
            <div class="mini">Máquinas vinculadas por Hardware ID</div>
        </div>

        <div class="card yellow">
            <div class="label">Pagamentos pendentes</div>
            <strong><?= $pagamentosPendentes; ?></strong>
            <div class="mini">Aguardando confirmação manual</div>
        </div>

        <div class="card red">
            <div class="label">Licenças expiradas</div>
            <strong><?= $licencasExpiradas; ?></strong>
            <div class="mini">Precisam de renovação</div>
        </div>

        <div class="card orange">
            <div class="label">Suspensas</div>
            <strong><?= $licencasSuspensas; ?></strong>
            <div class="mini">Pausadas temporariamente</div>
        </div>

        <div class="card red">
            <div class="label">Bloqueadas</div>
            <strong><?= $licencasBloqueadas; ?></strong>
            <div class="mini">Bloqueio administrativo</div>
        </div>

        <div class="card">
            <div class="label">Total de licenças</div>
            <strong><?= $totalLicencas; ?></strong>
            <div class="mini">Todas as chaves geradas</div>
        </div>
    </div>

    <div class="content-grid">
        <div class="panel">
            <div class="panel-head">
                <div>
                    <h3>Últimas licenças</h3>
                    <p>Licenças geradas recentemente no sistema.</p>
                </div>

                <a class="btn dark" href="licencas.php">Ver todas</a>
            </div>

            <?php if (empty($ultimasLicencas)): ?>
                <div class="empty">Nenhuma licença cadastrada ainda.</div>
            <?php else: ?>
                <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Licença</th>
                                <th>Cliente</th>
                                <th>Status</th>
                                <th>Vencimento</th>
                                <th>Dias</th>
                                <th>Computadores</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($ultimasLicencas as $l): ?>
                            <tr>
                                <td>
                                    <span class="key"><?= htmlspecialchars($l['chave']); ?></span><br>
                                    <span class="small"><?= htmlspecialchars(ucfirst($l['tipo'])); ?></span>
                                </td>

                                <td>
                                    <?= htmlspecialchars($l['cliente_nome'] ?? 'Sem cliente'); ?><br>
                                    <span class="small"><?= htmlspecialchars($l['cliente_email'] ?? '-'); ?></span>
                                </td>

                                <td>
                                    <span class="badge <?= htmlspecialchars($l['status']); ?>">
                                        <?= htmlspecialchars($l['status']); ?>
                                    </span>
                                </td>

                                <td><?= fmtDataDash($l['data_expiracao']); ?></td>
                                <td><?= diasDash($l['data_expiracao']); ?></td>

                                <td>
                                    <?= (int)$l['computadores_ativos']; ?> /
                                    <?= ((int)$l['limite_maquinas'] === 0) ? 'Ilimitado' : (int)$l['limite_maquinas']; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <div class="panel">
            <div class="panel-head">
                <div>
                    <h3>Últimos acessos</h3>
                    <p>Máquinas que verificaram licença recentemente.</p>
                </div>
            </div>

            <?php if (empty($ultimosComputadores)): ?>
                <div class="empty">Nenhum computador ativado.</div>
            <?php else: ?>
                <div class="side-list">
                    <?php foreach ($ultimosComputadores as $pc): ?>
                        <div class="device">
                            <strong><?= htmlspecialchars($pc['nome_pc'] ?: 'Computador sem nome'); ?></strong>
                            <span class="small">
                                Cliente: <?= htmlspecialchars($pc['cliente_nome'] ?? '-'); ?><br>
                                Usuário: <?= htmlspecialchars($pc['usuario_windows'] ?: '-'); ?><br>
                                Último acesso: <?= date('d/m/Y H:i', strtotime($pc['ultimo_acesso'])); ?><br>
                                <span class="key"><?= htmlspecialchars($pc['chave']); ?></span>
                            </span>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

</div>

</body>
</html>