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

$token = $_GET['token'] ?? '';
$msg = '';
$erro = '';
$token_valido = false;

// Verifica se o token existe e é válido
if (!empty($token)) {
    $stmt = $pdo->prepare("SELECT id FROM usuarios WHERE token_recuperacao = ? AND token_validade > NOW()");
    $stmt->execute([$token]);
    $user = $stmt->fetch();
    if ($user) {
        $token_valido = true;
    } else {
        $erro = "Este link expirou ou é inválido.";
    }
}

// Processa a Nova Senha
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $token_valido) {
    $nova_senha = $_POST['senha'];
    $confirmar = $_POST['confirmar'];

    if (strlen($nova_senha) < 6) {
        $erro = "A senha deve ter pelo menos 6 caracteres.";
    } elseif ($nova_senha !== $confirmar) {
        $erro = "As senhas não coincidem.";
    } else {
        // Atualiza a senha e limpa o token (para não usar de novo)
        $hash = password_hash($nova_senha, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE usuarios SET senha = ?, token_recuperacao = NULL, token_validade = NULL WHERE id = ?");
        $stmt->execute([$hash, $user['id']]);
        
        $msg = "Senha alterada com sucesso!";
        $token_valido = false; // Esconde o formulário
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nova Senha</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <style>body { font-family: 'Inter', sans-serif; background-color: #000; color: #fff; }</style>
</head>
<body class="h-screen flex items-center justify-center p-4 bg-[#111]">
    <div class="w-full max-w-md bg-black/85 p-10 rounded-xl border border-gray-800">
        
        <?php if($msg): ?>
            <div class="text-center">
                <div class="mb-4 text-green-500 text-5xl">✓</div>
                <h2 class="text-xl font-bold mb-2">Sucesso!</h2>
                <p class="text-gray-400 mb-6"><?= $msg ?></p>
                <a href="area_aluno.php" class="block w-full bg-[#ff0050] text-center py-3 rounded font-bold hover:bg-[#d60043]">Fazer Login</a>
            </div>
        <?php elseif(!$token_valido && !$msg): ?>
            <div class="text-center">
                <h2 class="text-xl font-bold text-red-500 mb-2">Link Inválido</h2>
                <p class="text-gray-400 mb-6"><?= $erro ?></p>
                <a href="recuperar.php" class="text-sm underline hover:text-[#ff0050]">Solicitar novo link</a>
            </div>
        <?php else: ?>
            <h1 class="text-2xl font-bold mb-6">Criar Nova Senha</h1>
            <?php if($erro): ?><div class="bg-red-500/20 text-red-200 p-3 rounded mb-4 text-sm"><?= $erro ?></div><?php endif; ?>
            
            <form method="POST" class="space-y-4">
                <div>
                    <label class="text-xs text-gray-500 uppercase font-bold">Nova Senha</label>
                    <input type="password" name="senha" required class="w-full bg-[#333] border border-transparent focus:border-[#ff0050] text-white rounded p-3 outline-none">
                </div>
                <div>
                    <label class="text-xs text-gray-500 uppercase font-bold">Confirmar Senha</label>
                    <input type="password" name="confirmar" required class="w-full bg-[#333] border border-transparent focus:border-[#ff0050] text-white rounded p-3 outline-none">
                </div>
                <button class="w-full bg-[#ff0050] hover:bg-[#d60043] text-white font-bold py-3 rounded transition">SALVAR SENHA</button>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>