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

$cliente_id = (int)$_SESSION['cliente_id'];

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

$mensagem = '';
$erro = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $acao = $_POST['acao'] ?? '';

    if ($acao === 'perfil') {
        $nome = trim($_POST['nome'] ?? '');
        $whatsapp = trim($_POST['whatsapp'] ?? '');

        if ($nome === '') {
            $erro = 'Informe seu nome.';
        } else {
            $stmt = $pdo->prepare("UPDATE clientes SET nome = ?, whatsapp = ? WHERE id = ?");
            $stmt->execute([$nome, $whatsapp, $cliente_id]);

            $_SESSION['cliente_nome'] = $nome;
            $mensagem = 'Perfil atualizado com sucesso.';

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

    if ($acao === 'senha') {
        $senha_atual = trim($_POST['senha_atual'] ?? '');
        $nova_senha = trim($_POST['nova_senha'] ?? '');
        $confirmar_senha = trim($_POST['confirmar_senha'] ?? '');

        if (!$senha_atual || !$nova_senha || !$confirmar_senha) {
            $erro = 'Preencha todos os campos.';
        } elseif (!password_verify($senha_atual, $cliente['senha'])) {
            $erro = 'Senha atual incorreta.';
        } elseif ($nova_senha !== $confirmar_senha) {
            $erro = 'As senhas não conferem.';
        } elseif (strlen($nova_senha) < 6) {
            $erro = 'A senha deve possuir pelo menos 6 caracteres.';
        } else {
            $hash = password_hash($nova_senha, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("UPDATE clientes SET senha = ? WHERE id = ?");
            $stmt->execute([$hash, $cliente_id]);

            $mensagem = 'Senha alterada com sucesso.';
        }
    }
}

$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([$cliente_id]);
$licencas = $stmt->fetchAll();

function diasRestantesPainel($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';
}

function avisoPainel($data)
{
    if (empty($data)) {
        return 'Licença vitalícia ativa.';
    }

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

    if ($fim < $hoje) {
        return 'Sua licença expirou. Faça a renovação para continuar usando.';
    }

    $dias = $hoje->diff($fim)->days;

    if ($dias <= 3) {
        return 'Atenção: sua licença expira em ' . $dias . ' dia(s).';
    }

    if ($dias <= 7) {
        return 'Aviso: sua licença expira em ' . $dias . ' dia(s).';
    }

    return 'Licença ativa e funcionando.';
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Painel do 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,.18),transparent 30%),
        radial-gradient(circle at bottom right,rgba(255,122,0,.14),transparent 30%),
        #060b16;
    color:#fff;
    font-family:Arial,Helvetica,sans-serif;
}

.topbar{
    padding:22px 36px;
    background:rgba(8,15,29,.96);
    border-bottom:1px solid rgba(255,255,255,.08);
    display:flex;
    justify-content:space-between;
    align-items:center;
}

.brand{
    display:flex;
    align-items:center;
    gap:14px;
}

.brand img{
    max-width:150px;
    max-height:56px;
    object-fit:contain;
}

.logo-fallback{
    width:48px;
    height:48px;
    border-radius:15px;
    background:linear-gradient(135deg,#ff7a00,#00aaff);
    display:flex;
    align-items:center;
    justify-content:center;
    font-weight:900;
}

.brand-text strong{
    display:block;
    font-size:20px;
}

.brand-text span{
    color:#7f95bd;
    font-size:13px;
}

.menu{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}

.menu a{
    color:#fff;
    text-decoration:none;
    background:#13223a;
    padding:11px 15px;
    border-radius:12px;
    font-size:14px;
}

.menu a:hover{
    background:linear-gradient(135deg,rgba(255,122,0,.4),rgba(0,170,255,.4));
}

.main{
    max-width:1250px;
    margin:auto;
    padding:36px;
}

.hero{
    background:
        linear-gradient(135deg,rgba(255,122,0,.12),rgba(0,170,255,.10)),
        rgba(13,24,43,.92);
    border:1px solid rgba(255,255,255,.08);
    border-radius:28px;
    padding:30px;
    margin-bottom:26px;
    box-shadow:0 24px 70px rgba(0,0,0,.35);
}

.hero h1{
    margin:0;
    font-size:32px;
}

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

.stats{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
    gap:16px;
    margin-top:24px;
}

.stat{
    background:rgba(5,11,21,.55);
    border:1px solid rgba(255,255,255,.07);
    border-radius:20px;
    padding:18px;
}

.stat span{
    color:#7f95bd;
    font-size:13px;
}

.stat strong{
    display:block;
    margin-top:8px;
    font-size:26px;
}

.licenses{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(310px,1fr));
    gap:22px;
}

.card{
    background:rgba(13,24,43,.94);
    border:1px solid rgba(255,255,255,.08);
    border-radius:26px;
    padding:24px;
    box-shadow:0 24px 70px rgba(0,0,0,.32);
}

.card-top{
    display:flex;
    justify-content:space-between;
    gap:12px;
    align-items:flex-start;
    margin-bottom:16px;
}

.card h2{
    margin:0;
    font-size:22px;
}

.key{
    display:block;
    font-family:Consolas,monospace;
    color:#00d4ff;
    font-size:17px;
    font-weight:bold;
    word-break:break-all;
    background:#07101f;
    padding:14px;
    border-radius:15px;
    border:1px dashed rgba(0,170,255,.35);
}

.info{
    margin-top:16px;
    color:#b8c7e6;
    line-height:1.8;
    font-size:14px;
}

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

.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}

.notice{
    margin-top:16px;
    padding:14px;
    border-radius:15px;
    background:rgba(0,170,255,.10);
    border:1px solid rgba(0,170,255,.25);
    color:#bfeeff;
    font-size:14px;
    line-height:1.5;
}

.actions{
    display:flex;
    gap:10px;
    margin-top:18px;
    flex-wrap:wrap;
}

.btn{
    display:inline-block;
    text-decoration:none;
    color:#fff;
    padding:12px 15px;
    border-radius:13px;
    background:linear-gradient(135deg,#ff7a00,#00aaff);
    font-weight:bold;
    font-size:14px;
}

.btn.secondary{
    background:#13223a;
}

.empty{
    color:#8fa3c7;
    padding:30px;
    background:rgba(13,24,43,.92);
    border-radius:24px;
    border:1px solid rgba(255,255,255,.08);
}

.modal{
    position:fixed;
    inset:0;
    background:rgba(0,0,0,.70);
    backdrop-filter:blur(10px);
    display:none;
    align-items:center;
    justify-content:center;
    padding:20px;
    z-index:99999;
}

.modal.show{
    display:flex;
}

.modal-box{
    width:100%;
    max-width:500px;
    background:#0d182b;
    border:1px solid rgba(255,255,255,.10);
    border-radius:26px;
    padding:30px;
    position:relative;
    box-shadow:0 30px 100px rgba(0,0,0,.60);
}

.modal-box h2{
    margin:0;
    font-size:27px;
}

.modal-box p{
    color:#8fa3c7;
    line-height:1.5;
    margin:8px 0 22px;
}

.modal-box label{
    display:block;
    margin:14px 0 8px;
    color:#c8d6f0;
}

.modal-box input{
    width:100%;
    padding:15px;
    border-radius:14px;
    border:1px solid rgba(255,255,255,.12);
    background:#08111f;
    color:#fff;
    outline:none;
}

.modal-box input:focus{
    border-color:#00aaff;
}

.modal-box button[type="submit"]{
    width:100%;
    margin-top:20px;
    padding:15px;
    border:0;
    border-radius:14px;
    background:linear-gradient(135deg,#ff7a00,#00aaff);
    color:#fff;
    font-weight:bold;
    cursor:pointer;
}

.modal-close{
    position:absolute;
    right:15px;
    top:15px;
    width:40px;
    height:40px;
    border:0;
    border-radius:12px;
    background:#13223a;
    color:#fff;
    cursor:pointer;
    font-size:22px;
}

.toast{
    position:fixed;
    top:20px;
    right:20px;
    z-index:999999;
    padding:15px 18px;
    border-radius:15px;
    box-shadow:0 20px 60px rgba(0,0,0,.35);
    max-width:360px;
}

.toast.success{
    background:rgba(0,255,160,.14);
    border:1px solid rgba(0,255,160,.35);
    color:#b7ffd8;
}

.toast.error{
    background:rgba(255,60,60,.14);
    border:1px solid rgba(255,60,60,.35);
    color:#ffc1c1;
}

@media(max-width:800px){
    .topbar{
        padding:18px;
        flex-direction:column;
        align-items:flex-start;
        gap:18px;
    }

    .main{
        padding:20px;
    }

    .hero h1{
        font-size:26px;
    }

    .menu{
        width:100%;
    }

    .menu a{
        flex:1;
        text-align:center;
    }
}
</style>
</head>

<body>

<?php if ($mensagem): ?>
    <div class="toast success"><?= htmlspecialchars($mensagem); ?></div>
<?php endif; ?>

<?php if ($erro): ?>
    <div class="toast error"><?= htmlspecialchars($erro); ?></div>
<?php endif; ?>

<div class="topbar">
    <div class="brand">
        <?php if (file_exists('../assets/logo.png')): ?>
            <img src="../assets/logo.png" alt="PromoCreative LED Mapper">
        <?php else: ?>
            <div class="logo-fallback">PC</div>
        <?php endif; ?>

        <div class="brand-text">
            <strong>PromoCreative LED Mapper</strong>
            <span>Área do Cliente</span>
        </div>
    </div>

    <div class="menu">
        <a href="painel.php">Painel</a>
        <a href="#" onclick="abrirModal('modalPerfil');return false;">Perfil</a>
        <a href="#" onclick="abrirModal('modalSenha');return false;">Senha</a>
        <a href="logout.php">Sair</a>
    </div>
</div>

<div class="main">

    <div class="hero">
        <h1>Olá, <?= htmlspecialchars($cliente['nome']); ?></h1>
        <p>
            Gerencie suas licenças, veja a validade, acompanhe os computadores ativados
            e copie sua chave para usar no programa Windows.
        </p>

        <div class="stats">
            <div class="stat">
                <span>Total de licenças</span>
                <strong><?= count($licencas); ?></strong>
            </div>

            <div class="stat">
                <span>Licenças ativas</span>
                <strong><?= count(array_filter($licencas, fn($l) => $l['status'] === 'ativa')); ?></strong>
            </div>

            <div class="stat">
                <span>Seu e-mail</span>
                <strong style="font-size:16px;word-break:break-all;">
                    <?= htmlspecialchars($cliente['email']); ?>
                </strong>
            </div>
        </div>
    </div>

    <?php if (empty($licencas)): ?>
        <div class="empty">
            Nenhuma licença encontrada para sua conta.
        </div>
    <?php else: ?>
        <div class="licenses">
            <?php foreach ($licencas as $l): ?>
                <div class="card">
                    <div class="card-top">
                        <h2><?= htmlspecialchars(ucfirst($l['tipo'])); ?></h2>

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

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

                    <div class="info">
                        <b>Vencimento:</b>
                        <?= $l['data_expiracao'] ? date('d/m/Y', strtotime($l['data_expiracao'])) : 'Vitalícia'; ?>
                        <br>

                        <b>Dias restantes:</b>
                        <?= diasRestantesPainel($l['data_expiracao']); ?>
                        <br>

                        <b>Computadores:</b>
                        <?= (int)$l['computadores_ativos']; ?> /
                        <?= ((int)$l['limite_maquinas'] === 0) ? 'Ilimitado' : (int)$l['limite_maquinas']; ?>
                        <br>

                        <b>Valor:</b>
                        R$ <?= number_format((float)$l['valor'], 2, ',', '.'); ?>
                    </div>

                    <div class="notice">
                        <?= avisoPainel($l['data_expiracao']); ?>
                    </div>

                    <div class="actions">
                        <a class="btn" href="minha_licenca.php?id=<?= (int)$l['id']; ?>">Ver detalhes</a>
                        <a class="btn secondary" href="pagar.php?id=<?= (int)$l['id']; ?>">Pagar / Renovar</a>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

</div>

<div class="modal" id="modalPerfil">
    <div class="modal-box">
        <button class="modal-close" onclick="fecharModal('modalPerfil')">×</button>

        <h2>Meu Perfil</h2>
        <p>Atualize seus dados de contato.</p>

        <form method="POST">
            <input type="hidden" name="acao" value="perfil">

            <label>Nome</label>
            <input type="text" name="nome" value="<?= htmlspecialchars($cliente['nome']); ?>" required>

            <label>E-mail</label>
            <input type="email" value="<?= htmlspecialchars($cliente['email']); ?>" disabled>

            <label>WhatsApp</label>
            <input type="text" name="whatsapp" value="<?= htmlspecialchars($cliente['whatsapp'] ?? ''); ?>">

            <button type="submit">Salvar Perfil</button>
        </form>
    </div>
</div>

<div class="modal" id="modalSenha">
    <div class="modal-box">
        <button class="modal-close" onclick="fecharModal('modalSenha')">×</button>

        <h2>Alterar Senha</h2>
        <p>Defina uma nova senha para acessar sua área do cliente.</p>

        <form method="POST">
            <input type="hidden" name="acao" value="senha">

            <label>Senha Atual</label>
            <input type="password" name="senha_atual" required>

            <label>Nova Senha</label>
            <input type="password" name="nova_senha" required>

            <label>Confirmar Nova Senha</label>
            <input type="password" name="confirmar_senha" required>

            <button type="submit">Alterar Senha</button>
        </form>
    </div>
</div>

<script>
function abrirModal(id){
    document.getElementById(id).classList.add('show');
}

function fecharModal(id){
    document.getElementById(id).classList.remove('show');
}

window.onclick = function(e){
    document.querySelectorAll('.modal').forEach(function(modal){
        if(e.target === modal){
            modal.classList.remove('show');
        }
    });
};

document.addEventListener('keydown', function(e){
    if(e.key === 'Escape'){
        document.querySelectorAll('.modal').forEach(function(modal){
            modal.classList.remove('show');
        });
    }
});

setTimeout(function(){
    document.querySelectorAll('.toast').forEach(function(toast){
        toast.style.opacity = '0';
        toast.style.transform = 'translateY(-10px)';
        setTimeout(function(){
            toast.remove();
        }, 400);
    });
}, 3500);
</script>

</body>
</html>