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

$id = (int)($_GET['id'] ?? 0);

if ($id <= 0) {
    header('Location: clientes.php');
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM clientes WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$cliente = $stmt->fetch();

if (!$cliente) {
    header('Location: clientes.php');
    exit;
}

$stmt = $pdo->prepare("
    SELECT 
        l.*,
        COUNT(a.id) AS computadores_ativos
    FROM licencas l
    LEFT JOIN ativacoes a ON a.licenca_id = l.id
    WHERE l.cliente_id = ?
    GROUP BY l.id
    ORDER BY l.id DESC
");
$stmt->execute([$id]);
$licencas = $stmt->fetchAll();

$stmt = $pdo->prepare("
    SELECT 
        a.*,
        l.chave
    FROM ativacoes a
    INNER JOIN licencas l ON l.id = a.licenca_id
    WHERE l.cliente_id = ?
    ORDER BY a.ultimo_acesso DESC
");
$stmt->execute([$id]);
$computadores = $stmt->fetchAll();

function diasRestantesCliente($data)
{
    if (empty($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>Cliente - PromoCreative LED Mapper</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
*{box-sizing:border-box}
body{
    margin:0;
    background:
        radial-gradient(circle at top left,rgba(0,170,255,.16),transparent 32%),
        radial-gradient(circle at bottom right,rgba(255,122,0,.13),transparent 28%),
        #060b16;
    color:#fff;
    font-family:Arial,Helvetica,sans-serif;
}
.sidebar{
    width:280px;height:100vh;position:fixed;left:0;top:0;
    background:rgba(8,15,29,.96);
    border-right:1px solid rgba(255,255,255,.08);
    padding:26px;
}
.logo{margin-bottom:34px}
.logo strong{display:block;font-size:21px;line-height:1.2}
.logo span{display:block;margin-top:8px;color:#7f95bd;font-size:13px}
.sidebar a{
    display:block;color:#b7c7e8;text-decoration:none;
    padding:14px 15px;border-radius:13px;margin-bottom:8px;
}
.sidebar a:hover,.sidebar a.active{
    background:linear-gradient(135deg,rgba(255,122,0,.18),rgba(0,170,255,.18));
    color:#fff;
}
.main{margin-left:280px;padding:36px}
.header{
    display:flex;justify-content:space-between;align-items:center;
    margin-bottom:26px;gap:16px;
}
.header h1{margin:0;font-size:30px}
.header p{margin:8px 0 0;color:#8fa3c7}
.btn{
    display:inline-block;
    background:linear-gradient(135deg,#ff7a00,#00aaff);
    color:#fff;text-decoration:none;
    padding:13px 18px;border-radius:14px;font-weight:bold;
}
.grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:22px;
}
.card{
    background:rgba(13,24,43,.92);
    border:1px solid rgba(255,255,255,.08);
    border-radius:24px;
    padding:24px;
    box-shadow:0 24px 70px rgba(0,0,0,.35);
    overflow-x:auto;
}
.card h2{margin:0 0 18px}
.info-line{
    padding:12px 0;
    border-bottom:1px solid rgba(255,255,255,.07);
}
.info-line span{
    display:block;
    color:#7f95bd;
    font-size:13px;
    margin-bottom:5px;
}
.table{width:100%;border-collapse:collapse;min-width:700px}
.table th,.table td{
    padding:14px 12px;
    border-bottom:1px solid rgba(255,255,255,.07);
    text-align:left;
    font-size:14px;
}
.table th{color:#7f95bd;font-weight:normal}
.key{font-family:Consolas,monospace;color:#00d4ff;font-weight:bold}
.small{color:#7f95bd;font-size:13px}
.badge{
    display:inline-block;
    padding:6px 11px;
    border-radius:999px;
    font-size:12px;
}
.ativo,.ativa{background:rgba(0,255,160,.12);color:#9fffc8}
.expirada{background:rgba(255,200,0,.12);color:#ffe58a}
.suspensa{background:rgba(255,122,0,.13);color:#ffc38a}
.bloqueada,.bloqueado{background:rgba(255,60,60,.12);color:#ffc1c1}
.full{grid-column:1/-1}
.empty{color:#8fa3c7;padding:18px 0}
@media(max-width:950px){
    .sidebar{position:relative;width:100%;height:auto}
    .main{margin-left:0;padding:20px}
    .grid{grid-template-columns:1fr}
    .header{flex-direction:column;align-items:flex-start}
}
</style>
</head>

<body>

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

    <a href="dashboard.php">Dashboard</a>
    <a class="active" href="clientes.php">Clientes</a>
    <a href="licencas.php">Licenças</a>
    <a href="gerar_licenca.php">Gerar Licença</a>
    <a href="computadores.php">Computadores</a>
    <a href="logout.php">Sair</a>
</div>

<div class="main">
    <div class="header">
        <div>
            <h1><?= htmlspecialchars($cliente['nome']); ?></h1>
            <p>Detalhes do cliente, licenças e computadores ativados.</p>
        </div>

        <a class="btn" href="gerar_licenca.php">+ Nova licença</a>
    </div>

    <div class="grid">
        <div class="card">
            <h2>Dados do cliente</h2>

            <div class="info-line">
                <span>Nome</span>
                <?= htmlspecialchars($cliente['nome']); ?>
            </div>

            <div class="info-line">
                <span>E-mail</span>
                <?= htmlspecialchars($cliente['email']); ?>
            </div>

            <div class="info-line">
                <span>WhatsApp</span>
                <?= htmlspecialchars($cliente['whatsapp'] ?: '-'); ?>
            </div>

            <div class="info-line">
                <span>Status</span>
                <span class="badge <?= htmlspecialchars($cliente['status']); ?>">
                    <?= htmlspecialchars($cliente['status']); ?>
                </span>
            </div>

            <div class="info-line">
                <span>Cadastrado em</span>
                <?= date('d/m/Y H:i', strtotime($cliente['criado_em'])); ?>
            </div>
        </div>

        <div class="card">
            <h2>Resumo</h2>

            <div class="info-line">
                <span>Total de licenças</span>
                <?= count($licencas); ?>
            </div>

            <div class="info-line">
                <span>Computadores ativados</span>
                <?= count($computadores); ?>
            </div>

            <div class="info-line">
                <span>Último acesso</span>
                <?php
                if (!empty($computadores)) {
                    echo date('d/m/Y H:i', strtotime($computadores[0]['ultimo_acesso']));
                } else {
                    echo '-';
                }
                ?>
            </div>
        </div>

        <div class="card full">
            <h2>Licenças do cliente</h2>

            <?php if (empty($licencas)): ?>
                <div class="empty">Este cliente ainda não possui licenças.</div>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Chave</th>
                            <th>Tipo</th>
                            <th>Status</th>
                            <th>Vencimento</th>
                            <th>Dias restantes</th>
                            <th>Computadores</th>
                            <th>Valor</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($licencas as $l): ?>
                        <tr>
                            <td><span class="key"><?= htmlspecialchars($l['chave']); ?></span></td>
                            <td><?= htmlspecialchars($l['tipo']); ?></td>
                            <td>
                                <span class="badge <?= htmlspecialchars($l['status']); ?>">
                                    <?= htmlspecialchars($l['status']); ?>
                                </span>
                            </td>
                            <td><?= $l['data_expiracao'] ? date('d/m/Y', strtotime($l['data_expiracao'])) : 'Vitalícia'; ?></td>
                            <td><?= diasRestantesCliente($l['data_expiracao']); ?></td>
                            <td>
                                <?= (int)$l['computadores_ativos']; ?> /
                                <?= ((int)$l['limite_maquinas'] === 0) ? 'Ilimitado' : (int)$l['limite_maquinas']; ?>
                            </td>
                            <td>R$ <?= number_format((float)$l['valor'], 2, ',', '.'); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <div class="card full">
            <h2>Computadores do cliente</h2>

            <?php if (empty($computadores)): ?>
                <div class="empty">Nenhum computador ativado.</div>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Computador</th>
                            <th>Usuário Windows</th>
                            <th>Licença</th>
                            <th>Ativado em</th>
                            <th>Último acesso</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($computadores as $pc): ?>
                        <tr>
                            <td><?= htmlspecialchars($pc['nome_pc'] ?: 'Não informado'); ?></td>
                            <td><?= htmlspecialchars($pc['usuario_windows'] ?: '-'); ?></td>
                            <td><span class="key"><?= htmlspecialchars($pc['chave']); ?></span></td>
                            <td><?= date('d/m/Y H:i', strtotime($pc['ativado_em'])); ?></td>
                            <td><?= date('d/m/Y H:i', strtotime($pc['ultimo_acesso'])); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</div>

</body>
</html>