<?php
if (session_status() === PHP_SESSION_NONE) session_start();

// Si ya hay una sesión activa, redirigir al dashboard
if (isset($_SESSION['id_usuario'])) {
    header("Location: /digitalpremium/index.php");
    exit();
}

$page_title = "Login - DigitalPremium";

// Generar token CSRF si no existe
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Mapa de mensajes de error para un código más limpio
$error_messages = [
    'credenciales' => 'Usuario o contraseña incorrectos. Verifica tus datos.',
    'campos_vacios' => 'Por favor, completa todos los campos para continuar.',
    'no_activo' => 'Tu cuenta no se encuentra activa. Contacta al administrador.',
    'csrf' => 'La sesión ha caducado. Por favor, inténtalo de nuevo.',
];
$error_key = $_GET['error'] ?? null;
$error_message = $error_messages[$error_key] ?? null;

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #6366f1;
            --primary-dark: #4f46e5;
            --primary-light: #818cf8;
            --text-primary: #1f2937;
            --text-secondary: #6b7280;
            --bg-light: #f9fafb;
            --bg-white: #ffffff;
            --border-color: #e5e7eb;
            --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
            --shadow-2xl: 0 25px 50px -12px rgb(0 0 0 / 0.25);
        }

        /* --- Estructura y Layout General --- */
        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--bg-light);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 1.5rem;
            overflow-x: hidden;
        }

        .login-wrapper {
            display: flex;
            width: 100%;
            max-width: 1024px;
            min-height: 600px;
            background-color: var(--bg-white);
            border-radius: 24px;
            box-shadow: var(--shadow-2xl);
            overflow: hidden;
            transition: all 0.3s ease;
        }

        /* --- Panel de Presentación (Izquierda) --- */
        .login-showcase {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 40px;
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: var(--bg-white);
            text-align: center;
        }
        
        .showcase-logo {
            width: 100px;
            height: 100px;
            margin-bottom: 24px;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 20px;
            padding: 12px;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .showcase-title {
            font-weight: 700;
            font-size: 2rem;
            margin-bottom: 12px;
        }

        .showcase-description {
            font-size: 1rem;
            opacity: 0.9;
            max-width: 300px;
        }
        
        .showcase-illustration {
            width: 100%;
            max-width: 320px;
            margin-top: 40px;
        }

        /* --- Panel del Formulario (Derecha) --- */
        .login-form-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding: 50px;
            background-color: var(--bg-white);
        }
        
        .form-header {
            margin-bottom: 32px;
            text-align: center;
        }

        .form-title {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: 8px;
        }

        .form-subtitle {
            font-size: 1rem;
            color: var(--text-secondary);
        }
        
        .form-group {
            position: relative;
            margin-bottom: 24px;
        }
        
        .form-label {
            font-size: 0.9rem;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 8px;
            display: block;
        }

        .input-wrapper {
            position: relative;
        }

        .form-control {
            width: 100%;
            height: 52px;
            padding: 0 20px 0 50px;
            border: 1px solid var(--border-color);
            border-radius: 12px;
            font-size: 1rem;
            font-weight: 500;
            color: var(--text-primary);
            background-color: var(--bg-light);
            transition: all 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            background-color: var(--bg-white);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2);
        }

        .input-icon {
            position: absolute;
            left: 18px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-secondary);
            font-size: 1.1rem;
            transition: color 0.3s ease;
            pointer-events: none;
        }
        
        .form-control:focus + .input-icon {
            color: var(--primary-color);
        }

        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: transparent;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            font-size: 1.2rem;
            padding: 5px;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .password-toggle:hover {
            color: var(--primary-color);
            background-color: rgba(99, 102, 241, 0.1);
        }

        /* --- Botón de Login --- */
        .btn-login {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            border: none;
            border-radius: 12px;
            color: white;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 52px;
        }

        .btn-login:hover {
            transform: translateY(-3px);
            box-shadow: var(--shadow-lg);
        }

        .btn-login:active {
            transform: translateY(-1px);
        }

        /* --- Estado de Carga del Botón --- */
        .btn-loading {
            pointer-events: none;
            background: var(--primary-dark);
        }

        .loader {
            width: 20px;
            height: 20px;
            border: 2px solid #FFF;
            border-bottom-color: transparent;
            border-radius: 50%;
            display: inline-block;
            box-sizing: border-box;
            animation: rotation 1s linear infinite;
        }

        @keyframes rotation {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* --- Alertas y Footer --- */
        .alert {
            border-radius: 10px;
            border-left-width: 4px;
            border-left-style: solid;
        }
        
        .footer-text {
            text-align: center;
            color: var(--text-secondary);
            font-size: 0.8rem;
            margin-top: 32px;
        }

        /* --- Diseño Responsivo --- */
        @media (max-width: 992px) {
            .login-wrapper {
                flex-direction: column;
                min-height: auto;
                max-width: 480px;
            }
            .login-showcase {
                display: none; /* Ocultar panel de marca en móviles */
            }
            .login-form-container {
                padding: 40px;
            }
        }
        
        @media (max-width: 576px) {
            body {
                padding: 1rem;
            }
            .login-wrapper {
                border-radius: 16px;
            }
            .login-form-container {
                padding: 30px;
            }
            .form-title {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>

    <div class="login-wrapper">
        <div class="login-showcase">
            <img src="assets/logo/TV DYG - Blanco.png" alt="DigitalPremium Logo" class="showcase-logo">
            <h1 class="showcase-title">Bienvenido de Nuevo</h1>
            <p class="showcase-description">Tu plataforma de gestión todo en uno. Accede para administrar tus operaciones.</p>
            <img src="https://cdni.iconscout.com/illustration/premium/thumb/login-3305943-2757111.png" alt="Login Illustration" class="showcase-illustration">
        </div>

        <div class="login-form-container">
            <div class="form-header">
                <h2 class="form-title">Iniciar Sesión</h2>
                <p class="form-subtitle">Ingresa tus credenciales para acceder</p>
            </div>
            
            <?php if ($error_message): ?>
                <div class="alert alert-danger" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <?php echo htmlspecialchars($error_message); ?>
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['logout_success'])): ?>
                <div class="alert alert-success" role="alert">
                    <i class="fas fa-check-circle me-2"></i>
                    Has cerrado sesión exitosamente.
                </div>
            <?php endif; ?>

            <form action="/digitalpremium/auth/procesar_login.php" method="POST" id="loginForm" novalidate>
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">

                <div class="form-group">
                    <label for="username" class="form-label">Usuario</label>
                    <div class="input-wrapper">
                        <input type="text" class="form-control" id="username" name="username" placeholder="Tu nombre de usuario" required autofocus>
                        <i class="fas fa-user input-icon"></i>
                    </div>
                </div>

                <div class="form-group">
                    <label for="password" class="form-label">Contraseña</label>
                    <div class="input-wrapper">
                        <input type="password" class="form-control" id="password" name="password" placeholder="Tu contraseña" required>
                        <i class="fas fa-lock input-icon"></i>
                        <button type="button" class="password-toggle" id="passwordToggleBtn" aria-label="Mostrar u ocultar contraseña">
                            <i class="fas fa-eye" id="passwordToggleIcon"></i>
                        </button>
                    </div>
                </div>

                <button type="submit" class="btn-login" id="loginBtn">
                    <span id="loginBtnText">Ingresar</span>
                </button>
            </form>
            
            <div class="footer-text">
                &copy; <?php echo date('Y'); ?> DigitalPremium. Todos los derechos reservados.
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const passwordField = document.getElementById('password');
            const toggleBtn = document.getElementById('passwordToggleBtn');
            const toggleIcon = document.getElementById('passwordToggleIcon');

            // Función para mostrar/ocultar contraseña
            toggleBtn.addEventListener('click', function () {
                const isPassword = passwordField.type === 'password';
                passwordField.type = isPassword ? 'text' : 'password';
                toggleIcon.classList.toggle('fa-eye', !isPassword);
                toggleIcon.classList.toggle('fa-eye-slash', isPassword);
            });

            // Lógica para el estado de carga del botón al enviar
            const loginForm = document.getElementById('loginForm');
            const loginBtn = document.getElementById('loginBtn');
            const loginBtnText = document.getElementById('loginBtnText');

            loginForm.addEventListener('submit', function(e) {
                // Validar campos vacíos antes de enviar
                const username = document.getElementById('username').value.trim();
                const password = passwordField.value.trim();
                
                if (!username || !password) {
                    // Previene el envío del formulario si está vacío
                    // Aunque ya tienes validación en backend, esto mejora la UX.
                    e.preventDefault(); 
                    return;
                }

                loginBtn.classList.add('btn-loading');
                loginBtn.disabled = true;
                loginBtnText.textContent = ''; // Ocultar texto
                
                // Crear y mostrar el spinner
                const loader = document.createElement('div');
                loader.className = 'loader';
                loginBtn.appendChild(loader);
            });
        });
    </script>
</body>
</html>