<?php
session_start();
// 1. CONEXÃO
$paths = ['config.php', 'tiktok/config.php']; foreach ($paths as $path) { if (file_exists($path)) { require_once $path; break; }}

if (!isset($_SESSION['aluno_id'])) { header("Location: area_aluno.php"); exit; }

$aluno_id = $_SESSION['aluno_id'];
$msg = '';
$erro = '';

// 2. PROCESSAR ATUALIZAÇÃO
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nome = trim($_POST['nome']);
    $whatsapp = trim($_POST['whatsapp']);
    
    // Dados de Endereço (Ajustado para 'endereco')
    $cep = $_POST['cep'];
    $endereco = $_POST['endereco']; // No banco é 'endereco', não 'rua'
    $numero = $_POST['numero'];
    $bairro = $_POST['bairro'];
    $cidade = $_POST['cidade'];
    $estado = $_POST['estado'];
    $complemento = $_POST['complemento'];

    // Senha
    $nova_senha = $_POST['nova_senha'];
    $confirma_senha = $_POST['confirma_senha'];

    if (empty($nome)) {
        $erro = "O nome é obrigatório.";
    } else {
        // Query Base (Usando 'endereco' e 'data_atualizacao')
        $sql = "UPDATE usuarios SET nome=?, whatsapp=?, cep=?, endereco=?, numero=?, bairro=?, cidade=?, estado=?, complemento=?, data_atualizacao=NOW() WHERE id=?";
        $params = [$nome, $whatsapp, $cep, $endereco, $numero, $bairro, $cidade, $estado, $complemento, $aluno_id];

        // Lógica de Senha
        if (!empty($nova_senha)) {
            if (strlen($nova_senha) < 6) {
                $erro = "A senha nova é muito curta (mínimo 6 dígitos).";
            } elseif ($nova_senha !== $confirma_senha) {
                $erro = "As senhas não coincidem.";
            } else {
                $sql = "UPDATE usuarios SET nome=?, whatsapp=?, cep=?, endereco=?, numero=?, bairro=?, cidade=?, estado=?, complemento=?, data_atualizacao=NOW(), senha=? WHERE id=?";
                $params = [$nome, $whatsapp, $cep, $endereco, $numero, $bairro, $cidade, $estado, $complemento, password_hash($nova_senha, PASSWORD_DEFAULT), $aluno_id];
            }
        }

        if (!$erro) {
            $stmt = $pdo->prepare($sql);
            if ($stmt->execute($params)) {
                $msg = "Perfil atualizado com sucesso!";
                $_SESSION['aluno_nome'] = $nome;
            } else {
                $erro = "Erro ao salvar no banco de dados.";
            }
        }
    }
}

// 3. BUSCAR DADOS DO USUÁRIO
$stmt = $pdo->prepare("SELECT * FROM usuarios WHERE id = ?");
$stmt->execute([$aluno_id]);
$dados = $stmt->fetch();

// 4. BUSCAR LOGS (Últimos 10)
// Como você confirmou que criou a tabela logs_acesso, isso vai funcionar
$stmt_logs = $pdo->prepare("SELECT * FROM logs_acesso WHERE usuario_id = ? ORDER BY id DESC LIMIT 10");
$stmt_logs->execute([$aluno_id]);
$logs = $stmt_logs->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meu Perfil Completo</title>
    <link rel="icon" href="https://www.tiktok.com/favicon.ico" type="image/x-icon" />
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script> 
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        body { background-color: #0f0f0f; color: #e5e5e5; font-family: 'Inter', sans-serif; }
        .card { background-color: #1a1a1a; border: 1px solid #333; border-radius: 12px; }
        .input-dark { background-color: #111; border: 1px solid #333; color: #fff; transition: all 0.3s; }
        .input-dark:focus { border-color: #ff0050; outline: none; box-shadow: 0 0 0 2px rgba(255,0,80,0.2); }
        .input-disabled { background-color: #222; color: #666; cursor: not-allowed; }
        
        /* Scrollbar fina */
        ::-webkit-scrollbar { width: 8px; }
        ::-webkit-scrollbar-track { background: #111; }
        ::-webkit-scrollbar-thumb { background: #333; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: #444; }
    </style>
</head>
<body class="min-h-screen pb-20">

    <nav class="sticky top-0 z-50 bg-black/80 backdrop-blur-md border-b border-[#333] px-6 py-4 flex justify-between items-center">
        <div class="text-[#ff0050] font-black text-xl tracking-tighter">THE<span class="text-white">LIKE</span></div>
        <a href="area_aluno.php?dashboard=true" class="text-sm font-bold text-gray-400 hover:text-white flex items-center gap-2 transition">
            <i data-lucide="arrow-left" class="w-4 h-4"></i> <span class="hidden sm:inline">Voltar para Aulas</span>
        </a>
    </nav>

    <div class="max-w-5xl mx-auto px-4 py-8">
        
        <div class="flex flex-col md:flex-row items-center md:items-start gap-6 mb-10">
            <div class="w-24 h-24 rounded-full bg-gradient-to-br from-[#333] to-[#111] border-2 border-[#ff0050] flex items-center justify-center shadow-2xl">
                <span class="text-4xl font-bold text-white"><?= strtoupper(substr($dados['nome'], 0, 1)) ?></span>
            </div>
            <div class="text-center md:text-left">
                <h1 class="text-3xl font-bold text-white mb-2"><?= htmlspecialchars($dados['nome']) ?></h1>
                <p class="text-gray-500 text-sm flex items-center justify-center md:justify-start gap-2">
                    <i data-lucide="mail" class="w-3 h-3"></i> <?= $dados['email'] ?>
                    <span class="bg-green-500/10 text-green-500 text-[10px] px-2 py-0.5 rounded border border-green-500/20 font-bold uppercase">Aluno Ativo</span>
                </p>
                <p class="text-xs text-gray-600 mt-2">Membro desde: <?= date('d/m/Y', strtotime($dados['data_criacao'] ?? date('Y-m-d'))) ?></p>
            </div>
        </div>

        <?php if($msg): ?>
            <div class="bg-green-500/10 border-l-4 border-green-500 text-green-400 p-4 rounded mb-8 flex items-center gap-3 animate-pulse">
                <i data-lucide="check-circle" class="w-5 h-5"></i> <?= $msg ?>
            </div>
        <?php endif; ?>

        <?php if($erro): ?>
            <div class="bg-red-500/10 border-l-4 border-red-500 text-red-400 p-4 rounded mb-8 flex items-center gap-3">
                <i data-lucide="alert-circle" class="w-5 h-5"></i> <?= $erro ?>
            </div>
        <?php endif; ?>

        <form method="POST" class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <div class="lg:col-span-2 space-y-8">
                
                <div class="card p-6 md:p-8">
                    <h2 class="text-lg font-bold text-white mb-6 flex items-center gap-2 border-b border-[#333] pb-4">
                        <i data-lucide="user" class="text-[#ff0050]"></i> Dados Pessoais
                    </h2>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <div>
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Nome Completo</label>
                            <input type="text" name="nome" value="<?= htmlspecialchars($dados['nome']) ?>" class="input-dark w-full rounded p-3 text-sm">
                        </div>
                        <div>
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">WhatsApp</label>
                            <input type="text" name="whatsapp" id="whatsapp" value="<?= htmlspecialchars($dados['whatsapp']) ?>" class="input-dark w-full rounded p-3 text-sm">
                        </div>
                        <div>
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">E-mail (Login)</label>
                            <input type="text" value="<?= $dados['email'] ?>" disabled class="input-disabled w-full rounded p-3 text-sm">
                        </div>
                        <div>
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">CPF</label>
                            <input type="text" value="<?= $dados['cpf'] ?>" disabled class="input-disabled w-full rounded p-3 text-sm">
                        </div>
                    </div>
                </div>

                <div class="card p-6 md:p-8">
                    <h2 class="text-lg font-bold text-white mb-6 flex items-center gap-2 border-b border-[#333] pb-4">
                        <i data-lucide="map-pin" class="text-[#ff0050]"></i> Endereço
                    </h2>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-5">
                        <div class="md:col-span-1">
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">CEP</label>
                            <div class="relative">
                                <input type="text" name="cep" id="cep" value="<?= $dados['cep'] ?? '' ?>" class="input-dark w-full rounded p-3 text-sm" onblur="buscarCep(this.value)">
                                <div id="loading-cep" class="absolute right-3 top-3 hidden"><i data-lucide="loader-2" class="w-4 h-4 animate-spin text-[#ff0050]"></i></div>
                            </div>
                        </div>
                        <div class="md:col-span-2">
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Rua / Logradouro</label>
                            <input type="text" name="endereco" id="endereco" value="<?= $dados['endereco'] ?? '' ?>" class="input-dark w-full rounded p-3 text-sm">
                        </div>
                        <div class="md:col-span-1">
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Número</label>
                            <input type="text" name="numero" value="<?= $dados['numero'] ?? '' ?>" class="input-dark w-full rounded p-3 text-sm">
                        </div>
                        <div class="md:col-span-2">
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Bairro</label>
                            <input type="text" name="bairro" id="bairro" value="<?= $dados['bairro'] ?? '' ?>" class="input-dark w-full rounded p-3 text-sm">
                        </div>
                        <div class="md:col-span-1">
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Cidade</label>
                            <input type="text" name="cidade" id="cidade" value="<?= $dados['cidade'] ?? '' ?>" class="input-dark w-full rounded p-3 text-sm">
                        </div>
                        <div class="md:col-span-1">
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Estado</label>
                            <input type="text" name="estado" id="estado" value="<?= $dados['estado'] ?? '' ?>" class="input-dark w-full rounded p-3 text-sm" maxlength="2">
                        </div>
                        <div class="md:col-span-4">
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Complemento</label>
                            <input type="text" name="complemento" value="<?= $dados['complemento'] ?? '' ?>" class="input-dark w-full rounded p-3 text-sm" placeholder="Apto, Bloco, etc.">
                        </div>
                    </div>
                </div>

            </div>

            <div class="space-y-8">
                
                <div class="card p-6">
                    <h2 class="text-lg font-bold text-white mb-6 flex items-center gap-2 border-b border-[#333] pb-4">
                        <i data-lucide="lock" class="text-[#ff0050]"></i> Segurança
                    </h2>
                    <div class="space-y-4">
                        <div>
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Nova Senha</label>
                            <input type="password" name="nova_senha" placeholder="Deixe em branco para manter" class="input-dark w-full rounded p-3 text-sm">
                        </div>
                        <div>
                            <label class="text-xs font-bold text-gray-500 uppercase mb-1 block">Confirmar Senha</label>
                            <input type="password" name="confirma_senha" placeholder="Repita a nova senha" class="input-dark w-full rounded p-3 text-sm">
                        </div>
                    </div>
                    
                    <button class="w-full bg-[#ff0050] hover:bg-[#d60043] text-white font-bold py-3 mt-6 rounded transition shadow-lg shadow-red-900/20 flex items-center justify-center gap-2">
                        <i data-lucide="save"></i> SALVAR DADOS
                    </button>
                </div>

                <div class="card p-6">
                    <h2 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-[#333] pb-4">
                        <i data-lucide="shield" class="text-blue-500"></i> Últimos Acessos
                    </h2>
                    <div class="overflow-hidden">
                        <?php if(count($logs) > 0): ?>
                            <ul class="space-y-3">
                                <?php foreach($logs as $log): ?>
                                <li class="text-xs text-gray-400 bg-[#111] p-3 rounded border border-[#222]">
                                    <div class="flex justify-between items-center mb-1">
                                        <span class="text-white font-bold"><?= date('d/m/Y H:i', strtotime($log['data_acesso'])) ?></span>
                                        <span class="text-[10px] bg-blue-500/10 text-blue-400 px-1 rounded"><?= $log['ip'] ?></span>
                                    </div>
                                    <div class="truncate opacity-70" title="<?= $log['dispositivo'] ?>">
                                        <?= $log['dispositivo'] ?>
                                    </div>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <p class="text-sm text-gray-600 text-center py-4">Nenhum registro recente.</p>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        </form>
    </div>

    <script>
        lucide.createIcons();

        // Máscaras
        document.addEventListener('DOMContentLoaded', function () {
            IMask(document.getElementById('cep'), {mask: '00000-000'});
            IMask(document.getElementById('whatsapp'), {mask: '(00) 00000-0000'});
        });

        // Busca de CEP Automática (ViaCEP)
        function buscarCep(cep) {
            cep = cep.replace(/\D/g, '');
            if (cep.length === 8) {
                document.getElementById('loading-cep').classList.remove('hidden');
                
                fetch(`https://viacep.com.br/ws/${cep}/json/`)
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('loading-cep').classList.add('hidden');
                        if (!data.erro) {
                            // Aqui o campo no HTML é 'endereco', então buscamos pelo ID 'endereco'
                            document.getElementById('endereco').value = data.logradouro;
                            document.getElementById('bairro').value = data.bairro;
                            document.getElementById('cidade').value = data.localidade;
                            document.getElementById('estado').value = data.uf;
                        } else {
                            alert("CEP não encontrado.");
                        }
                    })
                    .catch(() => {
                        document.getElementById('loading-cep').classList.add('hidden');
                    });
            }
        }
    </script>
</body>
</html>