<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';

// Depuração
error_log("Sessão atual: " . print_r($_SESSION, true));

// Única verificação de redirecionamento
if (isset($_SESSION['user']) && isset($_SESSION['user']['type'])) {
    redirectByUserType($_SESSION['user']);
}

$login_error = '';

// Processamento de login
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = authenticateUser($_POST['username'], $_POST['password']);
    
    if ($user) {
        $_SESSION['user'] = $user;
        redirectByUserType($user);
    } else {
        $login_error = "Usuário ou senha inválidos";
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Login - Sistema de Pacientes</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">
    <div class="w-full max-w-md">
        <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8">
            <h2 class="text-2xl font-bold text-center mb-6">Login do Sistema</h2>
            
            <?php if ($login_error): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                    <?= htmlspecialchars($login_error) ?>
                </div>
            <?php endif; ?>

            <div class="mb-4">
                <label class="block text-gray-700 text-sm font-bold mb-2">Usuário</label>
                <input 
                    type="text" 
                    name="username" 
                    required 
                    class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700"
                >
            </div>
            <div class="mb-6">
                <label class="block text-gray-700 text-sm font-bold mb-2">Senha</label>
                <input 
                    type="password" 
                    name="password" 
                    required 
                    class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700"
                >
            </div>
            <div class="flex items-center justify-center">
                <button 
                    type="submit" 
                    class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                >
                    Entrar
                </button>
            </div>
        </form>
    </div>
</body>
</html>