<?php
session_start();

// Cargar variables de entorno
if (file_exists(__DIR__ . '/.env')) {
    $lines = file(__DIR__ . '/.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        list($key, $value) = explode('=', $line, 2);
        $_ENV[trim($key)] = trim($value);
    }
}

require_once __DIR__ . '/shared/database/connection.php';
require_once __DIR__ . '/shared/auth/jwt.php';

$error = '';
$success = '';

// Si ya está autenticado, redirigir al panel
$userData = JWTAuth::authenticate();
if ($userData) {
    header('Location: /index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $error = 'Por favor, complete todos los campos';
    } else {
        try {
            $db = getDB();
            
            // Buscar usuario
            $stmt = $db->prepare("
                SELECT u.*, r.nombre as rol_nombre, i.codigo as idioma_codigo
                FROM usuarios u
                LEFT JOIN roles r ON u.rol_id = r.id
                LEFT JOIN idiomas i ON u.idioma_id = i.id
                WHERE u.username = ? AND u.activo = 1
            ");
            
            $stmt->execute([$username]);
            $user = $stmt->fetch();
            
            if ($user && password_verify($password, $user['password'])) {
                // Cargar permisos del usuario
                $permisos = JWTAuth::loadUserPermissions($user['id']);
                
                // Generar token JWT
                $token = JWTAuth::generateToken(
                    $user['id'],
                    $user['username'],
                    $user['rol_nombre'] ?? 'Editor',
                    $user['idioma_codigo'] ?? 'es',
                    $permisos
                );
                
                // Guardar token en cookie
                setcookie('auth_token', $token, [
                    'expires' => time() + 3600,
                    'path' => '/',
                    'secure' => false, // Cambiar a true en producción con HTTPS
                    'httponly' => true,
                    'samesite' => 'Lax'
                ]);
                
                // Actualizar último acceso
                $stmt = $db->prepare("UPDATE usuarios SET ultimo_acceso = NOW() WHERE id = ?");
                $stmt->execute([$user['id']]);
                
                // Redireccionar
                $redirect = $_GET['redirect'] ?? '/index.php';
                // Validar que la redirección sea interna para evitar open redirect
                if (!preg_match('/^\/[a-zA-Z0-9_\-\/]+\.php(\?.*)?$/', $redirect)) {
                    $redirect = '/index.php';
                }
                
                header('Location: ' . $redirect);
                exit;
                
            } else {
                $error = 'Usuario o contraseña incorrectos';
            }
            
        } catch (Exception $e) {
            $error = 'Error del sistema. Intente nuevamente.';
            error_log('Error de login: ' . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Sistema de Bots</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .login-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            width: 100%;
            max-width: 420px;
            padding: 40px;
        }
        
        .logo {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .logo h1 {
            color: #667eea;
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .logo p {
            color: #666;
            font-size: 14px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }
        
        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 15px;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn-login {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        
        .btn-login:active {
            transform: translateY(0);
        }
        
        .alert {
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        
        .alert-error {
            background: #fee;
            color: #c33;
            border-left: 4px solid #c33;
        }
        
        .alert-success {
            background: #efe;
            color: #3c3;
            border-left: 4px solid #3c3;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">
            <h1>🤖 Sistema de Bots</h1>
            <p>Discord & Telegram Manager</p>
            <div style="margin-top: 10px;">
                <a href="/admin/users/list.php" style="font-size: 12px; color: #667eea; text-decoration: none; border: 1px solid #667eea; padding: 4px 8px; border-radius: 12px;">
                    <i class="fas fa-users-cog"></i> Gestión de Usuarios
                </a>
            </div>
        </div>
        
        <?php if ($error): ?>
            <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        
        <form method="POST" action="">
            <div class="form-group">
                <label for="username">Usuario</label>
                <input type="text" id="username" name="username" required autofocus>
            </div>
            
            <div class="form-group">
                <label for="password">Contraseña</label>
                <input type="password" id="password" name="password" required>
            </div>
            
            <button type="submit" class="btn-login">Iniciar Sesión</button>
        </form>
    </div>
</body>
</html>
