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

if (isset($_GET['acao'], $_GET['id'])) {
    $id = (int) $_GET['id'];
    $acao = $_GET['acao'];

    $permitidas = ['ativa', 'suspensa', 'bloqueada', 'expirada'];

    if (in_array($acao, $permitidas)) {
        $stmt = $pdo->prepare("UPDATE licencas SET status = ? WHERE id = ?");
        $stmt->execute([$acao, $id]);
        header('Location: licencas.php');
        exit;
    }
}

$busca = trim($_GET['busca'] ?? '');

if ($busca) {
    $stmt = $pdo->prepare("
        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
        WHERE l.chave LIKE ? OR c.nome LIKE ? OR c.email LIKE ?
        GROUP BY l.id
        ORDER BY l.id DESC
    ");
    $like = "%{$busca}%";
    $stmt->execute([$like, $like, $like]);
} else {
    $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
    ");
}

$licencas = $stmt->fetchAll();

function diasRestantes($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>Licenças - 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;
}
.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;
}
.search{
    display:flex;gap:12px;margin-bottom:22px;
}
.search input{
    flex:1;
    padding:14px;
    border-radius:14px;
    border:1px solid rgba(255,255,255,.12);
    background:#08111f;
    color:#fff;
    outline:none;
}
.search button{
    padding:14px 18px;
    border:0;
    border-radius:14px;
    background:#13223a;
    color:#fff;
    cursor:pointer;
}
.table{width:100%;border-collapse:collapse;min-width:1050px}
.table th,.table td{
    padding:15px 13px;
    border-bottom:1px solid rgba(255,255,255,.07);
    text-align:left;
    font-size:14px;
    vertical-align:top;
}
.table th{color:#7f95bd;font-weight:normal}
.small{color:#7f95bd;font-size:13px}
.key{
    font-family:Consolas,monospace;
    color:#00d4ff;
    font-weight:bold;
}
.badge{
    display:inline-block;
    padding:6px 11px;
    border-radius:999px;
    font-size:12px;
}
.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{background:rgba(255,60,60,.12);color:#ffc1c1}
.actions a{
    display:inline-block;
    margin:3px 4px 3px 0;
    padding:7px 9px;
    border-radius:9px;
    text-decoration:none;
    font-size:12px;
    background:#13223a;
    color:#fff;
}
.empty{
    text-align:center;
    padding:35px;
    color:#8fa3c7;
}
@media(max-width:950px){
    .sidebar{position:relative;width:100%;height:auto}
    .main{margin-left:0;padding:20px}
    .header{flex-direction:column;align-items:flex-start}
    .search{flex-direction:column}
}
</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 href="clientes.php">Clientes</a>
    <a class="active" 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>Licenças</h1>
            <p>Controle as chaves, vencimentos, status e computadores autorizados.</p>
        </div>

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

    <div class="card">
        <form class="search" method="GET">
            <input type="text" name="busca" value="<?= htmlspecialchars($busca); ?>" placeholder="Buscar por chave, cliente ou e-mail">
            <button type="submit">Buscar</button>
        </form>

        <?php if (empty($licencas)): ?>
            <div class="empty">Nenhuma licença encontrada.</div>
        <?php else: ?>
            <table class="table">
                <thead>
                    <tr>
                        <th>Licença</th>
                        <th>Cliente</th>
                        <th>Plano</th>
                        <th>Status</th>
                        <th>Vencimento</th>
                        <th>Dias restantes</th>
                        <th>Computadores</th>
                        <th>Valor</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($licencas as $l): ?>
                    <tr>
                        <td>
                            <span class="key"><?= htmlspecialchars($l['chave']); ?></span><br>
                            <span class="small">Criada em <?= date('d/m/Y', strtotime($l['criado_em'])); ?></span>
                        </td>

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

                        <td><?= htmlspecialchars(ucfirst($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><?= diasRestantes($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>

                        <td class="actions">
                            <a href="licenca_detalhes.php?id=<?= (int)$l['id']; ?>">Ver</a>
                            <a href="licencas.php?acao=ativa&id=<?= (int)$l['id']; ?>">Ativar</a>
                            <a href="licencas.php?acao=suspensa&id=<?= (int)$l['id']; ?>">Suspender</a>
                            <a href="licencas.php?acao=bloqueada&id=<?= (int)$l['id']; ?>">Bloquear</a>
                            <a href="licencas.php?acao=expirada&id=<?= (int)$l['id']; ?>">Expirar</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

</body>
</html>