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

// Se já estiver logado, redireciona para o dashboard
if (isset($_SESSION['usuario_id'])) {
    if (isset($_GET['redirect'])) {
        header('Location: ' . urldecode($_GET['redirect']));
    } else {
        header('Location: index.php');
    }
    exit;
}

// Busca a logo da empresa
require_once 'config/database.php';
$database = new Database();
$db = $database->getConnection();

$logo_path = 'assets/img/placeholder-logo.png';
$empresa_nome = 'Sistema';

try {
    $query = "SELECT logo, nome_empresa FROM config_empresa WHERE id = 1";
    $stmt = $db->prepare($query);
    if ($stmt->execute()) {
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result && !empty($result['logo'])) {
            $logo_path = $result['logo'];
        }
        if ($result && !empty($result['nome_empresa'])) {
            $empresa_nome = $result['nome_empresa'];
        }
    }
} catch (Exception $e) {
    error_log("Erro ao buscar dados da empresa: " . $e->getMessage());
}

$mensagens = [
    'sessao_expirada' => 'Sua sessão expirou. Por favor, faça login novamente.',
    '1' => 'Usuário ou senha inválidos',
    '2' => 'Erro ao fazer login. Tente novamente.'
];

$mensagem = '';
if (isset($_GET['erro']) && isset($mensagens[$_GET['erro']])) {
    $mensagem = $mensagens[$_GET['erro']];
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - <?php echo htmlspecialchars($empresa_nome); ?></title>
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($logo_path); ?>">
    <link rel="shortcut icon" type="image/x-icon" href="<?php echo htmlspecialchars($logo_path); ?>">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    
    <!-- Custom CSS -->
    <link href="assets/css/theme.css?v=<?php echo time(); ?>" rel="stylesheet">
    <link href="assets/css/login.css?v=<?php echo time(); ?>" rel="stylesheet">
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-logo">
                <img src="<?php echo htmlspecialchars($logo_path); ?>" 
                     alt="<?php echo htmlspecialchars($empresa_nome); ?>" 
                     onerror="this.src='assets/img/placeholder-logo.png'">
                <h1 class="empresa-nome">PAINEL DE CONTROLE</h1>
            </div>

            <?php if (!empty($mensagem)): ?>
            <div class="alert" role="alert">
                <i class="bi bi-exclamation-circle"></i>
                <?php echo htmlspecialchars($mensagem); ?>
            </div>
            <?php endif; ?>

            <form action="actions/processar_login.php" method="POST" class="needs-validation" novalidate>
                <?php if (isset($_GET['redirect'])): ?>
                <input type="hidden" name="redirect" value="<?php echo htmlspecialchars($_GET['redirect']); ?>">
                <?php endif; ?>

                <div class="form-floating">
                    <input type="text" class="form-control" id="usuario" name="usuario" placeholder="Usuário" required>
                    <label for="usuario">Usuário</label>
                </div>

                <div class="form-floating">
                    <input type="password" class="form-control" id="senha" name="senha" placeholder="Senha" required>
                    <label for="senha">Senha</label>
                </div>

                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-box-arrow-in-right"></i>
                    Entrar
                </button>
            </form>
        </div>
    </div>

    <footer class="footer">
        <?php echo date('Y'); ?> 
        <span class="footer-separator">|</span> 
        Feito com <span style="color: var(--cor-terciaria);">♥</span> por <a href="https://digin.com.br/" target="_blank">Digin - Sistemas Inteligentes</a> 
        <span class="footer-separator">|</span> 
        Todos os direitos reservados
    </footer>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Toggle password visibility
        function togglePassword() {
            const senha = document.getElementById('senha');
            const toggleIcon = document.getElementById('togglePassword');
            
            if (senha.type === 'password') {
                senha.type = 'text';
                toggleIcon.classList.remove('bi-eye');
                toggleIcon.classList.add('bi-eye-slash');
            } else {
                senha.type = 'password';
                toggleIcon.classList.remove('bi-eye-slash');
                toggleIcon.classList.add('bi-eye');
            }
        }

        // Form validation and loading state
        (function () {
            'use strict'
            const forms = document.querySelectorAll('.needs-validation')
            const btnLogin = document.getElementById('btnLogin')
            
            Array.from(forms).forEach(form => {
                form.addEventListener('submit', event => {
                    if (!form.checkValidity()) {
                        event.preventDefault()
                        event.stopPropagation()
                    } else {
                        btnLogin.classList.add('btn-loading')
                        btnLogin.innerHTML = ''
                    }
                    form.classList.add('was-validated')
                }, false)
            })
        })()
    </script>
</body>
</html>
