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

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

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

if (isset($_GET['remover_pc'])) {
    $pc_id = (int)$_GET['remover_pc'];

    $stmt = $pdo->prepare("DELETE FROM ativacoes WHERE id = ?");
    $stmt->execute([$pc_id]);

    header('Location: licenca_detalhes.php?id=' . $id);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $status = $_POST['status'] ?? 'ativa';
    $tipo = $_POST['tipo'] ?? 'mensal';
    $data_expiracao = $_POST['data_expiracao'] ?? null;
    $limite_maquinas = (int)($_POST['limite_maquinas'] ?? 1);
    $valor = str_replace(',', '.', trim($_POST['valor'] ?? '0'));

    if ($tipo === 'vitalicia') {
        $data_expiracao = null;
    }

    $stmt = $pdo->prepare("
        UPDATE licencas
        SET status = ?, tipo = ?, data_expiracao = ?, limite_maquinas = ?, valor = ?
        WHERE id = ?
    ");
    $stmt->execute([
        $status,
        $tipo,
        $data_expiracao ?: null,
        $limite_maquinas,
        $valor,
        $id
    ]);

    header('Location: licenca_detalhes.php?id=' . $id . '&salvo=1');
    exit;
}

$stmt = $pdo->prepare("
    SELECT 
        l.*,
        c.nome AS cliente_nome,
        c.email AS cliente_email,
        c.whatsapp AS cliente_whatsapp
    FROM licencas l
    LEFT JOIN clientes c ON c.id = l.cliente_id
    WHERE l.id = ?
    LIMIT 1
");
$stmt->execute([$id]);
$licenca = $stmt->fetch();

if (!$licenca) {
    header('Location: licencas.php');
    exit;
}

$stmt = $pdo->prepare("
    SELECT *
    FROM ativacoes
    WHERE licenca_id = ?
    ORDER BY ultimo_acesso DESC
");
$stmt->execute([$id]);
$computadores = $stmt->fetchAll();

function diasRestantesLicenca($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>Detalhes da Licença - 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:#13223a;
    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}
.key{
    display:block;
    font-family:Consolas,monospace;
    color:#00d4ff;
    font-size:22px;
    font-weight:bold;
    word-break:break-all;
}
.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;
}
label{
    display:block;
    margin:15px 0 8px;
    color:#c4d2ee;
    font-size:14px;
}
input,select{
    width:100%;
    padding:14px;
    border-radius:14px;
    border:1px solid rgba(255,255,255,.12);
    background:#08111f;
    color:#fff;
    outline:none;
}
input:focus,select:focus{border-color:#00aaff}
.row{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:14px;
}
button{
    width:100%;
    margin-top:24px;
    padding:16px;
    border:0;
    border-radius:16px;
    background:linear-gradient(135deg,#ff7a00,#00aaff);
    color:#fff;
    font-weight:bold;
    cursor:pointer;
}
.alert{
    padding:15px;
    border-radius:14px;
    margin-bottom:18px;
    background:rgba(0,255,160,.12);
    border:1px solid rgba(0,255,160,.3);
    color:#b7ffd8;
}
.table{width:100%;border-collapse:collapse;min-width:850px}
.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}
.small{color:#7f95bd;font-size:13px}
.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}
.remove{
    display:inline-block;
    padding:8px 11px;
    border-radius:10px;
    background:rgba(255,60,60,.12);
    color:#ffb3b3;
    text-decoration:none;
}
.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}
    .row{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 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>Detalhes da licença</h1>
            <p>Edite plano, vencimento, valor e computadores autorizados.</p>
        </div>

        <a class="btn" href="licencas.php">← Voltar</a>
    </div>

    <div class="grid">
        <div class="card">
            <h2>Licença</h2>

            <?php if (isset($_GET['salvo'])): ?>
                <div class="alert">Alterações salvas com sucesso.</div>
            <?php endif; ?>

            <span class="key"><?= htmlspecialchars($licenca['chave']); ?></span>

            <div class="info-line">
                <span>Cliente</span>
                <?= htmlspecialchars($licenca['cliente_nome'] ?? 'Sem cliente'); ?>
            </div>

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

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

            <div class="info-line">
                <span>Dias restantes</span>
                <?= diasRestantesLicenca($licenca['data_expiracao']); ?>
            </div>

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

        <div class="card">
            <h2>Editar licença</h2>

            <form method="POST">
                <label>Status</label>
                <select name="status">
                    <option value="ativa" <?= $licenca['status'] === 'ativa' ? 'selected' : ''; ?>>Ativa</option>
                    <option value="suspensa" <?= $licenca['status'] === 'suspensa' ? 'selected' : ''; ?>>Suspensa</option>
                    <option value="bloqueada" <?= $licenca['status'] === 'bloqueada' ? 'selected' : ''; ?>>Bloqueada</option>
                    <option value="expirada" <?= $licenca['status'] === 'expirada' ? 'selected' : ''; ?>>Expirada</option>
                </select>

                <div class="row">
                    <div>
                        <label>Tipo</label>
                        <select name="tipo">
                            <option value="teste" <?= $licenca['tipo'] === 'teste' ? 'selected' : ''; ?>>Teste</option>
                            <option value="mensal" <?= $licenca['tipo'] === 'mensal' ? 'selected' : ''; ?>>Mensal</option>
                            <option value="anual" <?= $licenca['tipo'] === 'anual' ? 'selected' : ''; ?>>Anual</option>
                            <option value="vitalicia" <?= $licenca['tipo'] === 'vitalicia' ? 'selected' : ''; ?>>Vitalícia</option>
                        </select>
                    </div>

                    <div>
                        <label>Valor</label>
                        <input type="text" name="valor" value="<?= htmlspecialchars($licenca['valor']); ?>">
                    </div>
                </div>

                <label>Data de expiração</label>
                <input type="date" name="data_expiracao" value="<?= htmlspecialchars($licenca['data_expiracao']); ?>">

                <label>Limite de computadores</label>
                <select name="limite_maquinas">
                    <?php foreach ([1,2,3,5,10,0] as $limite): ?>
                        <option value="<?= $limite; ?>" <?= (int)$licenca['limite_maquinas'] === $limite ? 'selected' : ''; ?>>
                            <?= $limite === 0 ? 'Ilimitado' : $limite . ' computador(es)'; ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <button type="submit">Salvar alterações</button>
            </form>
        </div>

        <div class="card full">
            <h2>Computadores ativados nesta licença</h2>

            <?php if (empty($computadores)): ?>
                <div class="empty">Nenhum computador ativado ainda.</div>
            <?php else: ?>
                <table class="table">
                    <thead>
                        <tr>
                            <th>Computador</th>
                            <th>Usuário Windows</th>
                            <th>Hardware ID</th>
                            <th>Ativado em</th>
                            <th>Último acesso</th>
                            <th>Ação</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="small"><?= htmlspecialchars($pc['hardware_id']); ?></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>
                            <td>
                                <a class="remove"
                                   href="licenca_detalhes.php?id=<?= (int)$id; ?>&remover_pc=<?= (int)$pc['id']; ?>"
                                   onclick="return confirm('Remover este computador desta licença?');">
                                    Remover
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
</div>

</body>
</html>