<?php
	// Chequeo de existencia de token
	if (isset($_GET['tk']) && strlen($_GET['tk'])>10) {
		$indexing=1;
		include 'configs.php';

		$token = htmlentities(urldecode($_GET['tk']));

		$token_query = $pdo->query("SELECT id, correo, token_password FROM accounts WHERE token_password='$token'");
		if ($token_query->rowCount() == 0) {
			echo '<h1>Token inválido</h1>Asegúrese de haber copiado el enlace del correo correctamente';
			exit;
		}
	}else {
		exit;
	}
?>

<!doctype html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nueva Contraseña</title>
    
    <!-- Estilos CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap">
    <link href="https://fonts.googleapis.com/css2?family=Modern+Antiqua&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        :root {
            --jade: #38b2ac;
            --jade-light: #4fd1cc;
            --jade-dark: #2c8a86;
            --bg-dark: #0a0a12;
        }
        
        body, html {
            margin: 0;
            padding: 0;
            font-family: 'Modern Antiqua', serif;
            background-color: black;
            color: #e5e5e5;
            min-height: 100vh;
            position: relative;
        }
        
        /* Estilos de cursor personalizado */
        body {
            cursor: url("assets/media/cursors/image.png"), auto !important;
        }
        
        a, 
        button,
        .btn,
        .language-button,
        .back-button,
        input,
        select {
            cursor: url("assets/media/cursors/image.png"), auto !important;
        }
        
        /* Estilos para el fondo */
        .bg-image {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* Cabecera */
        header {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            padding: 1rem;
            z-index: 10;
        }
        
        .header-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 1rem;
        }
        
        .back-button {
            display: flex;
            align-items: center;
            color: #fff;
            text-decoration: none;
            font-size: 1rem;
            padding: 0.5rem 1rem;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 20px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
        }
        
        .back-button:hover {
            background-color: rgba(0, 0, 0, 0.7);
            color: var(--jade-light);
        }
        
        .back-button i {
            margin-right: 8px;
        }
        
        .language-selector {
            display: flex;
            gap: 8px;
        }
        
        .language-button {
            background-color: rgba(0, 0, 0, 0.5);
            color: #fff;
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            width: 36px;
            height: 36px;
            font-size: 0.8rem;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .language-button:hover, .language-button.active {
            background-color: var(--jade);
            border-color: var(--jade-light);
        }
        
        /* Contenido principal */
        .main-content {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 2rem;
            position: relative;
        }
        
        .form-container {
            width: 100%;
            max-width: 450px;
            margin: 0 auto;
            text-align: center;
            position: relative;
        }
        
        .logo-container {
            margin-bottom: 2rem;
        }
        
        .logo {
            width: 180px;
            margin-bottom: 1rem;
            filter: drop-shadow(0 0 10px rgba(56, 178, 172, 0.7));
        }
        
        .form-title {
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
            color: var(--jade);
            text-shadow: 0 0 10px rgba(56, 178, 172, 0.7);
        }
        
        .form-description {
            color: #ccc;
            font-size: 1.1rem;
            margin-bottom: 2rem;
        }
        
        .form-card {
            background: rgba(10, 10, 18, 0.8);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            border: 1px solid rgba(56, 178, 172, 0.3);
            padding: 2rem;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
            position: relative;
            overflow: hidden;
        }
        
        .form-card::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(56, 178, 172, 0.1) 0%, transparent 70%);
            z-index: -1;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
            text-align: left;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            color: #eee;
            font-size: 1rem;
        }
        
        .form-control {
            width: 100%;
            padding: 0.75rem;
            background-color: rgba(23, 25, 35, 0.5);
            border: 1px solid rgba(75, 85, 99, 0.5);
            border-radius: 6px;
            color: #fff;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: var(--jade);
            box-shadow: 0 0 0 2px rgba(56, 178, 172, 0.3);
            outline: none;
        }
        
        .password-container {
            position: relative;
        }
        
        .password-toggle {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #999;
            font-size: 1rem;
            transition: color 0.3s ease;
        }
        
        .password-toggle:hover {
            color: #fff;
        }
        
        .btn-primary {
            display: block;
            width: 100%;
            padding: 0.75rem;
            border: none;
            border-radius: 6px;
            background: linear-gradient(135deg, var(--jade) 0%, var(--jade-dark) 100%);
            color: #fff;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            margin-top: 1.5rem;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .btn-primary::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: all 0.5s ease;
        }
        
        .btn-primary:hover::before {
            left: 100%;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, var(--jade-light) 0%, var(--jade) 100%);
            box-shadow: 0 0 20px rgba(56, 178, 172, 0.5);
            transform: translateY(-2px);
        }
        
        /* Footer */
        footer {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            text-align: center;
            padding: 1rem;
            color: rgba(255, 255, 255, 0.6);
            font-size: 0.9rem;
        }
        
        /* Notificaciones personalizadas */
        .custom-notification {
            position: fixed;
            top: 20px;
            right: 20px;
            max-width: 350px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            z-index: 9999;
            display: none;
        }
        
        .custom-notification-icon {
            margin-right: 10px;
            font-size: 18px;
        }
        
        .custom-notification-title {
            font-weight: bold;
            margin-bottom: 5px;
            display: block;
        }
        
        .custom-notification-message {
            display: block;
        }
        
        .custom-notification.success {
            background: rgba(40, 167, 69, 0.9);
        }
        
        .custom-notification.error {
            background: rgba(220, 53, 69, 0.9);
        }
        
        .custom-notification.warning {
            background: rgba(255, 193, 7, 0.9);
        }
        
        .custom-notification.info {
            background: rgba(23, 162, 184, 0.9);
        }
        
        .custom-notification.show {
            display: block;
            animation: slideIn 0.5s ease-out;
        }
        
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
    </style>
</head>
<body>
    <!-- Imagen de fondo -->
    <img src="assets/media/bg.jpeg" alt="Fondo Místico" class="bg-image">
    
    <!-- Cabecera con botón de volver y selector de idioma -->
    <header>
        <div class="header-controls">
            <a href="index.php" class="back-button">
                <i class="fas fa-arrow-left"></i>
                <span class="lang-back-to-panel">Volver al Panel</span>
            </a>
            
            <div class="language-selector">
                <button type="button" class="language-button active" data-lang="es">ES</button>
                <button type="button" class="language-button" data-lang="en">EN</button>
                <button type="button" class="language-button" data-lang="br">PT</button>
            </div>
        </div>
    </header>
    
    <!-- Contenido principal -->
    <main class="main-content">
        <div class="form-container">
            <div class="logo-container">
                <img src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/logo-wLBB9y6KreoxJBVQKAJj1BZ1eqO9f4.png" alt="L2JADE Logo" class="logo">
                <h1 class="form-title lang-new-password">Nueva Contraseña</h1>
                <p class="form-description lang-new-password-desc">Ingrese su nueva contraseña para completar el proceso de recuperación.</p>
            </div>
            
            <!-- Formulario de nueva contraseña -->
            <div id="new-password-form" class="form-register">
                <form class="form-card js-validation-signin uns-signup" action="account_save.php" method="post" id="form_signup" onsubmit="return false;">
                    <input type="hidden" name="module_form" value="Modules\Globals\SignUp\SignUp">
                    <input type="hidden" name="module" value="newpass">
                    <input type="hidden" name="token" value="<?php echo $token; ?>">
                    <input id="type_reg" name="type_reg" type="hidden" value="#r-email">
                    
                    <!-- Nueva contraseña -->
                    <div class="form-group">
                        <label for="t-signup-password" class="form-label lang-new-password-input">Nueva Contraseña</label>
                        <div class="password-container">
                            <input type="password" class="form-control" id="t-signup-password" name="password" placeholder="********" required>
                            <button type="button" class="password-toggle" id="eye">
                                <i class="fas fa-eye" id="password-toggle-icon"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Captcha -->
                    <div class="form-group">
                        <input type="hidden" id="captcha" name="captcha">
                    </div>
                    
                    <!-- Botón de guardar -->
                    <button type="submit" class="btn-primary submit-form">
                        <span class="lang-save-button">Guardar Contraseña</span>
                    </button>
                </form>
            </div>
        </div>
    </main>
    
    <!-- Pie de página -->
    <footer>
        <p> 2025 L2JADE. Todos los derechos reservados</p>
    </footer>
    
    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://www.google.com/recaptcha/api.js?render=6LdPq0AUAAAAAJ7Q6jsquGMG0GhgWK78PO_NU4eU"></script>
    <script>
        // Esperar a que reCAPTCHA se cargue
        window.onload = function() {
            // Inicializar reCAPTCHA
            if (typeof grecaptcha !== 'undefined') {
                grecaptcha.ready(function() {
                    grecaptcha.execute('6LdPq0AUAAAAAJ7Q6jsquGMG0GhgWK78PO_NU4eU', {action: 'submit'}).then(function(token) {
                        document.getElementById('captcha').value = token;
                    });
                });
            }
        };

        // Función para obtener un nuevo token de captcha
        function refreshCaptcha() {
            return new Promise((resolve) => {
                if (typeof grecaptcha !== 'undefined') {
                    grecaptcha.execute('6LdPq0AUAAAAAJ7Q6jsquGMG0GhgWK78PO_NU4eU', {action: 'submit'}).then(function(token) {
                        document.getElementById('captcha').value = token;
                        resolve();
                    });
                } else {
                    resolve(); // Resolver la promesa incluso si grecaptcha no está disponible
                }
            });
        }

        $(document).ready(function() {
            // Traducciones
            const translations = {
                en: {
                    "lang-back-to-panel": "Back to Panel",
                    "lang-new-password": "New Password",
                    "lang-new-password-desc": "Enter your new password to complete the recovery process.",
                    "lang-new-password-input": "New Password",
                    "lang-save-button": "Save Password",
                    "lang-all-rights": "All rights reserved"
                },
                es: {
                    "lang-back-to-panel": "Volver al Panel",
                    "lang-new-password": "Nueva Contraseña",
                    "lang-new-password-desc": "Ingrese su nueva contraseña para completar el proceso de recuperación.",
                    "lang-new-password-input": "Nueva Contraseña",
                    "lang-save-button": "Guardar Contraseña",
                    "lang-all-rights": "Todos los derechos reservados"
                },
                br: {
                    "lang-back-to-panel": "Voltar ao Painel",
                    "lang-new-password": "Nova Senha",
                    "lang-new-password-desc": "Digite sua nova senha para concluir o processo de recuperação.",
                    "lang-new-password-input": "Nova Senha",
                    "lang-save-button": "Salvar Senha",
                    "lang-all-rights": "Todos os direitos reservados"
                }
            };
            
            // Idioma actual
            let currentLang = 'es';
            
            // Función para actualizar el idioma
            function updateLanguage(lang) {
                document.documentElement.lang = lang;
                currentLang = lang;
                
                // Actualizar todos los elementos con clases de idioma
                for (const [key, value] of Object.entries(translations[lang])) {
                    document.querySelectorAll('.' + key).forEach(element => {
                        element.textContent = value;
                    });
                }
                
                // Actualizar clases activas en botones de idioma
                document.querySelectorAll('.language-button').forEach(button => {
                    if (button.dataset.lang === lang) {
                        button.classList.add('active');
                    } else {
                        button.classList.remove('active');
                    }
                });
                
                // Guardar preferencia en localStorage
                localStorage.setItem('preferredLanguage', lang);
            }

            // Event listeners para botones de idioma
            document.querySelectorAll('.language-button').forEach(button => {
                button.addEventListener('click', function() {
                    const lang = this.dataset.lang;
                    updateLanguage(lang);
                });
            });

            // Cargar idioma preferido o usar el predeterminado
            const savedLang = localStorage.getItem('preferredLanguage');
            if (savedLang && ['es', 'en', 'br'].includes(savedLang)) {
                updateLanguage(savedLang);
            } else {
                updateLanguage(currentLang);
            }

            // Función para mostrar notificaciones
            function showNotification(message, type, duration = 5000) {
                // Crear elemento de notificación
                const notification = document.createElement('div');
                notification.className = `custom-notification ${type}`;
                
                // Definir iconos según el tipo
                let icon = '';
                switch(type) {
                    case 'success':
                        icon = 'fa-check-circle';
                        break;
                    case 'error':
                        icon = 'fa-times-circle';
                        break;
                    case 'warning':
                        icon = 'fa-exclamation-triangle';
                        break;
                    case 'info':
                        icon = 'fa-info-circle';
                        break;
                }
                
                // Construir el HTML de la notificación
                notification.innerHTML = `
                    <i class="fas ${icon} custom-notification-icon"></i>
                    <span class="custom-notification-title">Notificación</span>
                    <span class="custom-notification-message">${message}</span>
                `;
                
                // Agregar al cuerpo del documento
                document.body.appendChild(notification);
                
                // Mostrar con animación
                setTimeout(() => {
                    notification.classList.add('show');
                }, 100);
                
                // Configurar cierre automático
                setTimeout(() => {
                    notification.style.animation = 'slideOut 0.5s ease-out forwards';
                    setTimeout(() => {
                        notification.remove();
                    }, 500);
                }, duration);
            }

            // Configurar jQuery.notify para que use nuestro sistema personalizado
            if (jQuery && !jQuery.notify) {
                jQuery.notify = function(message, options) {
                    const defaults = {
                        type: 'success',
                        title: '',
                        duration: 5000
                    };
                    
                    const settings = { ...defaults, ...options };
                    
                    if (typeof message === 'object') {
                        if (message.text) {
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(message.text, 'text/html');
                            const title = doc.querySelector('.h4, h4')?.textContent || 'Notificación';
                            const paragraphs = doc.querySelectorAll('p:not(.h4):not(h4)');
                            let messageText = '';
                            paragraphs.forEach(p => {
                                messageText += p.textContent + ' ';
                            });
                            
                            showNotification(messageText, settings.type, settings.duration);
                        }
                    } else {
                        showNotification(message, settings.type, settings.duration);
                    }
                };
            }

            // Manejar el envío del formulario
            $(document).ready(function() {
                $('.submit-form').click(function(e) {
                    e.preventDefault();
                    var formulario = $(this).closest('form');
                    var url = formulario.attr('action');
                    
                    // Obtener nuevo token de captcha antes de enviar
                    refreshCaptcha().then(() => {
                        $.ajax({
                            type: 'POST',
                            url: url,
                            data: formulario.serialize(),
                            dataType: 'json',
                            success: function(response) {
                                if (response) {
                                    if (response.status === 'success') {
                                        $.notify(response, {
                                            type: 'success',
                                            duration: response.time_show || 5000
                                        });
                                        
                                        // Redirigir después de un tiempo si es necesario
                                        if (response.redirect) {
                                            setTimeout(function() {
                                                window.location.href = response.redirect;
                                            }, 2000);
                                        }
                                    } else {
                                        $.notify(response, {
                                            type: 'error',
                                            duration: response.time_show || 5000
                                        });
                                    }
                                }
                            },
                            error: function(xhr, status, error) {
                                $.notify({
                                    text: "<p class='mb-2 h4'>Error</p><p>Ha ocurrido un error al procesar la solicitud.</p>",
                                    status: "error"
                                });
                            }
                        });
                    });
                });
            });
        });
    </script>
    <script src="assets/js/codebase.core.min2954.js"></script>
    <script src="assets/js/codebase.app.min2954.js"></script>
    <script src="assets/js/plugins/bootstrap-notify/bootstrap-notify.min.js"></script>
    <script src="assets/js/mmoweb2954.js"></script>
    <script>
        document.getElementById('eye').addEventListener('click', function() {
            const passwordInput = document.getElementById('t-signup-password');
            const icon = document.getElementById('password-toggle-icon');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    </script>
</body>
</html>