<?php

error_reporting(E_ALL);

ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';

?>

<!DOCTYPE html>
<html lang="es">

<head>
    <title><?php echo isset($page_title) ? $page_title : "IBO Panel"; ?></title>
    <meta charset="utf-8" />
    <meta name="description" content=" IBO Panel" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#0F172A">
    <link rel="shortcut icon" href="<?php echo $static_url; ?>media/logos/logo.png" />
    
    <!-- Fuentes modernas -->
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&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 {
        --primary: #8B5CF6;
        --primary-dark: #7C3AED;
        --dark: #0F172A;
        --light: #F8FAFC;
        --card-bg: rgba(255, 255, 255, 0.1);
        --text-light: #E2E8F0;
        --glass-effect: blur(16px);
        --input-bg: rgba(255, 255, 255, 0.05);
    }
    
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    body {
        font-family: 'Plus Jakarta Sans', sans-serif;
        background: linear-gradient(135deg, #0F172A 0%, #1E293B 100%);
        color: var(--text-light);
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 2rem;
        transition: background 0.5s ease;
    }
    
    [data-bs-theme="light"] body {
        background: linear-gradient(135deg, #F8FAFC 0%, #E2E8F0 100%);
        color: #0F172A;
    }
    
    .login-container {
        display: grid;
        grid-template-columns: 1fr 1fr;
        max-width: 1200px;
        width: 100%;
        border-radius: 24px;
        overflow: hidden;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    }
    
    .form-section {
        background: var(--card-bg);
        backdrop-filter: var(--glass-effect);
        padding: 4rem;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: relative;
    }
    
    [data-bs-theme="light"] .form-section {
        background: rgba(255, 255, 255, 0.8);
    }
    
    .banner-section {
        background: url('<?php echo $static_url; ?>media/images/auth-bg.png') center/cover;
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding: 3rem;
    }
    
    .banner-section::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(135deg, rgba(15, 23, 42, 0.9) 0%, rgba(30, 41, 59, 0.8) 100%);
    }
    
    [data-bs-theme="light"] .banner-section::before {
        background: linear-gradient(135deg, rgba(248, 250, 252, 0.9) 0%, rgba(226, 232, 240, 0.8) 100%);
    }
    
    .banner-content {
        position: relative;
        z-index: 2;
        text-align: center;
    }
    
    .banner-image {
        max-width: 100%;
        height: auto;
        filter: drop-shadow(0 20px 30px rgba(0, 0, 0, 0.3));
        margin-bottom: 2rem;
        transform: perspective(800px) rotateY(-5deg);
        transition: transform 0.5s ease;
    }
    
    .banner-image:hover {
        transform: perspective(800px) rotateY(5deg);
    }
    
    .banner-title {
        font-size: 2.5rem;
        font-weight: 700;
        margin-bottom: 1rem;
        background: linear-gradient(90deg, #E2E8F0 0%, #94A3B8 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    [data-bs-theme="light"] .banner-title {
        background: linear-gradient(90deg, #0F172A 0%, #475569 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .logo {
        text-align: center;
        margin-bottom: 3rem;
    }
    
    .logo img {
        height: 80px;
        transition: transform 0.3s ease;
    }
    
    .logo img:hover {
        transform: scale(1.1) rotate(-5deg);
    }
    
    .login-form {
        display: flex;
        flex-direction: column;
		z-index: 2;
        gap: 1.5rem;
    }
    
    .form-group {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }
    
    .form-label {
        font-size: 0.875rem;
        font-weight: 600;
        color: var(--text-light);
    }
    
    [data-bs-theme="light"] .form-label {
        color: #334155;
    }
    
    .form-control {
        padding: 1rem 1.25rem;
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 12px;
        background: var(--input-bg);
        color: white;
        font-size: 1rem;
        transition: all 0.3s ease;
    }
    
    [data-bs-theme="light"] .form-control {
        background: rgba(15, 23, 42, 0.05);
        color: #0F172A;
        border: 1px solid rgba(15, 23, 42, 0.1);
    }
    
    .form-control:focus {
        outline: none;
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.2);
        background: rgba(255, 255, 255, 0.1);
    }
    
    [data-bs-theme="light"] .form-control:focus {
        background: rgba(15, 23, 42, 0.1);
    }
    
    .btn {
        padding: 1rem;
        border-radius: 12px;
        font-weight: 600;
        font-size: 1rem;
        cursor: pointer;
        transition: all 0.3s ease;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
    }
    
    .btn-primary {
        background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
        color: white;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
    }
    
    .btn-primary:active {
        transform: translateY(0);
    }
    
    .theme-switcher {
        position: relative;
        z-index: 2;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1rem;
        margin-top: 2rem;
    }
    
    .theme-toggle {
        position: relative;
        width: 50px;
        height: 26px;
        border-radius: 13px;
        background: rgba(255, 255, 255, 0.2);
        cursor: pointer;
    }
    
    [data-bs-theme="light"] .theme-toggle {
        background: rgba(15, 23, 42, 0.2);
    }
    
    .theme-toggle-handle {
        position: absolute;
        top: 3px;
        left: 3px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: white;
        transition: all 0.3s ease;
    }
    
    [data-bs-theme="light"] .theme-toggle-handle {
        background: #0F172A;
    }
    
    [data-bs-theme="dark"] .theme-toggle-handle {
        left: calc(100% - 23px);
    }
    
    /* Efecto de partículas */
    .particles {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        overflow: hidden;
    }
    
    .particle {
        position: absolute;
        background: rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        animation: float 15s infinite linear;
    }
    
    [data-bs-theme="light"] .particle {
        background: rgba(15, 23, 42, 0.2);
    }
    
    @keyframes float {
        0% { transform: translateY(0) rotate(0deg); }
        100% { transform: translateY(-100vh) rotate(360deg); }
    }
    
    /* Mensaje de error */
    .error-message {
        color: #EF4444;
        font-size: 0.875rem;
        text-align: center;
        margin-top: -1rem;
        margin-bottom: 1rem;
    }
    
    /* Responsive */
    @media (max-width: 992px) {
        .login-container {
            grid-template-columns: 1fr;
        }
        
        .banner-section {
            display: none;
        }
        
        .form-section {
            padding: 2.5rem;
        }
    }
    
    @media (max-width: 576px) {
        body {
            padding: 1rem;
        }
        
        .form-section {
            padding: 1.5rem;
        }
    }
	/* Asegura que bg-transparent funcione con tu tema */
.bg-transparent {
    background-color: transparent !important;
}

/* Estilos para el spinner de carga */
.indicator-progress {
    display: none;
}

[data-kt-indicator="on"] .indicator-progress {
    display: inline-flex;
}

[data-kt-indicator="on"] .indicator-label {
    display: none;
}
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.75);
    display: none; /* oculto por defecto */
    align-items: center;
    justify-content: center;
    z-index: 9999;
}
.modal-box {
    background: #f8f9fa; /* blanco/gris claro */
    padding: 30px;
    border-radius: 10px;
    max-width: 400px;
    width: 90%;
    box-shadow: 0 0 20px rgba(0,0,0,0.4);
    text-align: center;
    color: #000; /* 🔹 color de texto negro */
}


.modal-box input {
    background-color: #2a2a3c;
    color: #fff;
    border: 1px solid #444;
}

.modal-box input::placeholder {
    color: #ccc;
}

.modal-box button {
    background-color: #4e73df;
    color: #fff;
    border: none;
}

.modal-box button:hover {
    background-color: #3758b5;
}
.modal-buttons {
    display: flex;
    justify-content: center; /* Centra horizontalmente */
    gap: 10px; /* Espacio entre botones */
    margin-top: 20px; /* Opcional, separación del contenido superior */
}

    </style>
</head>

<body id="kt_body" class="app-blank">
    <script>
    // Sistema de tema mejorado
    var defaultThemeMode = "dark";
    var themeMode;
    
    function applyTheme(mode) {
        document.documentElement.setAttribute('data-bs-theme', mode);
        localStorage.setItem('data-bs-theme', mode);
        
        // Actualizar el interruptor visual
        const toggleHandle = document.querySelector('.theme-toggle-handle');
        if (toggleHandle) {
            if (mode === 'dark') {
                toggleHandle.style.left = 'calc(100% - 23px)';
            } else {
                toggleHandle.style.left = '3px';
            }
        }
        
        // Mostrar/ocultar elementos según el tema
        document.querySelectorAll('.theme-light-show').forEach(el => {
            el.style.display = mode === 'light' ? 'inline' : 'none';
        });
        
        document.querySelectorAll('.theme-dark-show').forEach(el => {
            el.style.display = mode === 'dark' ? 'inline' : 'none';
        });
    }
    
    // Inicializar tema
    if (document.documentElement) {
        if (document.documentElement.hasAttribute("data-bs-theme-mode")) {
            themeMode = document.documentElement.getAttribute("data-bs-theme-mode");
        } else {
            themeMode = localStorage.getItem("data-bs-theme") || defaultThemeMode;
        }
        
        if (themeMode === "system") {
            themeMode = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
        }
        
        applyTheme(themeMode);
    }
    </script>

    <div class="login-container">
        <!-- Sección del formulario -->
        <div class="form-section">
            <div class="particles" id="particles-js"></div>
            
            <div class="logo">
                <img src="<?php echo $static_url; ?>media/logos/logo.png" alt="IBO Panel">
            </div>
            
            <h2 style="text-align: center; margin-bottom: 1.5rem; font-size: 1.75rem;">Acceso al Panel</h2>
            
            <div id="kt_login_error" class="error-message" style="display: none;"></div>
            
            <!-- Dentro de tu sección form-section, reemplaza solo el formulario con este: -->
<div class="login-form">
    <form class="form w-100" novalidate="novalidate" id="kt_sign_in_form" data-kt-redirect-url="dns.php" action="#">
        <div class="form-group">
            <label for="username" class="form-label">Usuario</label>
            <input type="text" id="username" name="username" autocomplete="off" 
                   class="form-control bg-transparent" placeholder="Ingresa tu usuario">
        </div>
        
        <div class="form-group">
            <label for="password" class="form-label">Contraseña</label>
            <input type="password" id="password" name="password" autocomplete="off" 
                   class="form-control bg-transparent" placeholder="Ingresa tu contraseña">
        </div>

     <div style="display: flex; justify-content: center; margin-top: 1.5rem; margin-bottom: 1rem;">
  <button type="submit" id="kt_sign_in_submit" class="btn btn-primary" style="min-width: 180px;">
    <span class="indicator-label">ENTRAR</span>
    <span class="indicator-progress">
      <i class="fas fa-spinner fa-spin"></i> Verificando...
    </span>
  </button>
</div>
        <div class="text-center mt-3">
    <a href="#" id="forgotPasswordBtn" style="font-size: 0.9rem; color: white;">¿Olvidaste tu contraseña?</a>
</div>
    </form>
</div>
            
            <div class="theme-switcher">
                <span class="theme-light-show" style="display: none;">
                    <i class="fas fa-moon"></i> Modo Oscuro
                </span>
                <span class="theme-dark-show">
                    <i class="fas fa-sun"></i> Modo Claro
                </span>
                <div class="theme-toggle" id="kt_theme_toggle">
                    <div class="theme-toggle-handle"></div>
                </div>
            </div>
        </div>

        <!-- Sección del banner -->
        <div class="banner-section">
            <div class="banner-content">
                <img src="<?php echo $static_url; ?>media/images/auth-screens5.png" alt="IBO Player" class="banner-image">
                <h1 class="banner-title">IBO Player v4.3</h1>
                <p>Sistema de gestión avanzado</p>
            </div>
        </div>
    </div>
<div id="passwordRecoveryModal" class="modal-overlay" style="display: none;">
  <div class="modal-box">
    <h3>Recuperar contraseña</h3>
    <p>Ingresa tu código de recuperación:</p>
    <input type="text" id="recoveryCode" class="form-control mb-2" placeholder="Código de recuperación">
    <p>Nueva contraseña:</p>
    <input type="password" id="newPassword" class="form-control mb-3" placeholder="Nueva contraseña">
    <div class="text-right">
        <div class="modal-buttons">
    <button id="cancelRecovery" class="btn btn-secondary btn-sm">Cancelar</button>
    <button id="submitRecovery" class="btn btn-primary btn-sm">Actualizar</button>
</div>
  </div>
</div>

   <!-- Scripts originales -->
    <script src="<?php echo $static_url; ?>plugins/global/plugins.bundle.js"></script>
<script src="<?php echo $static_url; ?>js/scripts.bundle.js"></script>
<script src="<?php echo $static_url; ?>js/users.js"></script>
    <script>
document.getElementById("kt_sign_in_form").addEventListener("submit", function (e) {
    e.preventDefault();

    const form = e.target;
    const username = form.username.value.trim();
    const password = form.password.value.trim();

    const button = document.getElementById("kt_sign_in_submit");
    const spinner = button.querySelector(".indicator-progress");

    // Mostrar spinner
    spinner.style.display = "inline-block";
    button.disabled = true;

    fetch("api/login.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
    })
        .then((res) => res.json())
        .then((data) => {
            if (data.success) {
                window.location.href = data.redirect;
            } else {
                alert(data.message || "Login fallido");
            }
        })
        .catch(() => {
            alert("Error en la conexión.");
        })
        .finally(() => {
            spinner.style.display = "none";
            button.disabled = false;
        });
});
</script>

    <!-- Script personalizado para integración -->
    <script>
   document.addEventListener('DOMContentLoaded', function() {
    // Crear efecto de partículas
    const particlesContainer = document.getElementById('particles-js');
    if(particlesContainer) {
        for(let i = 0; i < 20; i++) {
            const particle = document.createElement('div');
            particle.classList.add('particle');
            
            // Corregido: usando concatenación de strings en lugar de template literals mal formadas
            const size = Math.random() * 4 + 2;
            particle.style.width = size + 'px';
            particle.style.height = size + 'px';
            particle.style.left = Math.random() * 100 + '%';
            particle.style.bottom = '-' + size + 'px';
            particle.style.animationDuration = (Math.random() * 10 + 10) + 's';
            particle.style.animationDelay = (Math.random() * 5) + 's';
            
            particlesContainer.appendChild(particle);
        }
    }
        
        // Toggle del tema
        const themeToggle = document.getElementById('kt_theme_toggle');
        if(themeToggle) {
            themeToggle.addEventListener('click', function() {
                const currentTheme = document.documentElement.getAttribute('data-bs-theme');
                const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
                applyTheme(newTheme);
            });
        }
        
        // Preparar el formulario para la validación original
        const loginForm = document.getElementById('kt_sign_in_form');
        if(loginForm) {
            loginForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const submitButton = document.getElementById('kt_sign_in_submit');
                const indicatorLabel = submitButton.querySelector('.indicator-label');
                const indicatorProgress = submitButton.querySelector('.indicator-progress');
                
                // Mostrar estado de carga
                indicatorLabel.style.display = 'none';
                indicatorProgress.style.display = 'flex';
                submitButton.disabled = true;
                
                // Ocultar mensaje de error previo
                document.getElementById('kt_login_error').style.display = 'none';
                
                // Aquí se ejecutará la validación original de users.js
                // Simplemente preparamos el formulario para ello
                
                // Si hay un error, se puede mostrar así:
                // document.getElementById('kt_login_error').textContent = "Mensaje de error";
                // document.getElementById('kt_login_error').style.display = 'block';
                // indicatorLabel.style.display = 'flex';
                // indicatorProgress.style.display = 'none';
                // submitButton.disabled = false;
            });
        }
    });
    
    // Función para mostrar errores (compatible con la validación original)
    function showLoginError(message) {
        const errorElement = document.getElementById('kt_login_error');
        errorElement.textContent = message;
        errorElement.style.display = 'block';
        
        const submitButton = document.getElementById('kt_sign_in_submit');
        submitButton.querySelector('.indicator-label').style.display = 'flex';
        submitButton.querySelector('.indicator-progress').style.display = 'none';
        submitButton.disabled = false;
    }
    </script>
<script>
document.getElementById("forgotPasswordBtn").addEventListener("click", function(e) {
    e.preventDefault();
    document.getElementById("passwordRecoveryModal").style.display = "flex";
});

document.getElementById("cancelRecovery").addEventListener("click", function() {
    document.getElementById("passwordRecoveryModal").style.display = "none";
});

// Aquí puedes agregar la lógica para enviar la nueva contraseña
document.getElementById("submitRecovery").addEventListener("click", function() {
    const code = document.getElementById("recoveryCode").value.trim();
    const newPassword = document.getElementById("newPassword").value.trim();

    if (!code || !newPassword) {
        alert("Completa todos los campos.");
        return;
    }

    // Enviar a tu backend por fetch/AJAX
    fetch('api/reset_admin_password.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ code: code, new_password: newPassword })
})
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert("Contraseña actualizada con éxito.");
            document.getElementById("passwordRecoveryModal").style.display = "none";
        } else {
            alert(data.message || "Error al actualizar.");
        }
    })
    .catch(err => {
        alert("Error de red.");
        console.error(err);
    });
});
</script>

</body>
</html>