<?php
// login.php
require 'config/db.php';


// Si ya está logueado, mandarlo al dashboard de una vez
if (isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit;
}

$error = "";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (!empty($username) && !empty($password)) {
        // Buscamos al usuario por su nombre
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        // Verificar si el usuario existe y la contraseña es correcta
        if ($user && password_verify($password, $user['password'])) {
            
            // --- CONFIGURACIÓN DE SESIÓN CORREGIDA ---
            $_SESSION['user_id']   = $user['id'];       // ID numérico real
            $_SESSION['username']  = $user['username']; // Para el saludo del panel
            
            // Guardamos el rol en ambas llaves para evitar conflictos con el Header/Admin
            $user_role = $user['role'] ?? $user['user_role'] ?? 'user';
            $_SESSION['role']      = $user_role;
            $_SESSION['user_role'] = $user_role;
            
            // Redirección al Dashboard
            header("Location: dashboard.php");
            exit;
        } else {
            $error = "Usuario o contraseña incorrectos.";
        }
    } else {
        $error = "Por favor, completa todos los campos.";
    }
}
?>

<?php include 'includes/header.php'; ?>

<style>
    .login-container {
        max-width: 400px;
        margin: 80px auto;
        padding: 0 20px;
        font-family: 'Inter', sans-serif;
    }
    .login-card {
        background: var(--nav-bg);
        border: 1px solid var(--border);
        padding: 40px;
        border-radius: 20px;
        text-align: center;
        box-shadow: 0 15px 35px rgba(0,0,0,0.2);
    }
    .login-card h2 { 
        margin-bottom: 30px; 
        color: var(--primary); 
        font-family: 'Syncopate', sans-serif;
        font-size: 20px;
        letter-spacing: 1px;
    }
    
    .form-group { margin-bottom: 20px; text-align: left; }
    .form-group label { 
        display: block; 
        color: var(--text-gray); 
        font-size: 11px; 
        margin-bottom: 8px; 
        font-weight: 800;
        letter-spacing: 1px;
    }
    .form-group input { 
        width: 100%; 
        padding: 14px; 
        background: var(--bg-dark); 
        border: 1px solid var(--border); 
        border-radius: 10px; 
        color: white; 
        box-sizing: border-box;
        transition: 0.3s;
    }
    .form-group input:focus { 
        border-color: var(--primary); 
        outline: none; 
        box-shadow: 0 0 10px rgba(0, 255, 136, 0.1);
    }

    .btn-login {
        width: 100%; 
        padding: 16px; 
        background: var(--primary); 
        border: none; 
        border-radius: 10px; 
        font-weight: 900; 
        color: #000;
        cursor: pointer;
        transition: 0.3s; 
        margin-top: 10px;
        text-transform: uppercase;
        letter-spacing: 1px;
    }
    .btn-login:hover { 
        transform: translateY(-3px); 
        box-shadow: 0 8px 20px rgba(0, 255, 136, 0.3); 
        filter: brightness(1.1);
    }

    .error-msg {
        background: rgba(255, 77, 77, 0.1); 
        color: #ff4d4d;
        padding: 12px; 
        border-radius: 10px; 
        margin-bottom: 20px; 
        font-size: 13px;
        border: 1px solid rgba(255, 77, 77, 0.3);
        font-weight: 600;
    }
</style>

<div class="login-container">
    <div class="login-card">
        <h2>ENTER THE VAULT</h2>

        <?php if($error): ?>
            <div class="error-msg"><i class="fa-solid fa-triangle-exclamation"></i> <?php echo $error; ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group">
                <label>USERNAME</label>
                <input type="text" name="username" placeholder="Tu usuario..." required autofocus>
            </div>
            <div class="form-group">
                <label>PASSWORD</label>
                <input type="password" name="password" placeholder="••••••••" required>
            </div>
            <button type="submit" class="btn-login">ACCEDER AHORA</button>
        </form>

        <p style="margin-top: 30px; font-size: 13px; color: var(--text-gray);">
            ¿No tienes cuenta? <a href="register.php" style="color: var(--primary); text-decoration: none; font-weight: 700;">Regístrate aquí</a>
        </p>
    </div>
</div>

<?php include 'includes/footer.php'; ?>