<?php
header('Content-Type: text/html; charset=UTF-8');
require_once "include/session.php";
if (isLoggedIn()) {
  header("Location: dashboard");
}
if (isset($_POST['login_submit'])) {
    require_once "include/db.php";
    require_once 'functions.php'; // Make sure this contains log_audit()

    $email = strtolower(trim($_POST['email']));
    $pass = $_POST['password'];

    $stmt = $conn->prepare("SELECT id, password FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    $user_id = null; // Initialize user_id for logging

    if ($stmt->num_rows === 0) {
        $error = "No account found with the email address.";

        // Log failed login - email not found
        log_audit(
            $conn, 'Login Failed - Email Not Found', 'users', null, null, null, null, $email, null, 'LoginAttempt'
        );

    } else {
        $stmt->bind_result($user_id, $hashed_password);
        $stmt->fetch();

        if (password_verify($pass, $hashed_password)) {
            $_SESSION['user_id'] = $user_id;

            // Log login success
            log_audit(
                $conn, 'Login Success', 'users', null, null, null, $user_id, $email, null, 'LoginAttempt'
            );

            header("Location: dashboard");
            exit();

        } else {
            $error = "Incorrect password. Please try again.";

            // Log failed login - wrong password
            log_audit(
                $conn, 'Login Failed - Incorrect Password', 'users', null, null, null, $user_id, $email, null, 'LoginAttempt'
            );
        }
    }

    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login | HealthBüro Healthcare Management</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- [favicon] begin -->
    <link rel="shortcut icon" type="image/x-icon" href="https://sylvianettebox.net/favicon.ico" />
    <link rel="icon" type="image/x-icon" href="https://sylvianettebox.net/favicon.ico" />
    <!-- [favicon] end -->
    <link rel="stylesheet" href="auth.css" type="text/css"  />
    
</head>
<body>
    <div class="auth-container">
        <button class="theme-toggle" id="themeToggle">
            <i class="fas fa-moon"></i>
        </button>
        
        <?php include 'illustrator.php'?>
        
        <div class="auth-forms">
            <div class="logo">
                <h1>HealthBüro</h1>
                <p>Healthcare Management System</p>
            </div>
            
            <!-- Login Form -->
            <form method="POST">
                <div id="login-form" class="auth-form active">
                    <h2 class="form-title">Login to HealthBüro</h2>
                    <?php if (isset($error)): ?>
                    <div class="error-message">
                        <span class="close-btn">&times;</span>
                        <i class="fas fa-times-circle"></i> <?= htmlspecialchars($error) ?>
                    </div>
                    <?php endif; ?>
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-envelope input-icon"></i>
                            <input type="email" class="form-control" placeholder="Enter your email address" name="email" id="login-email">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="input-group">
                            <i class="fas fa-lock input-icon"></i>
                            <input type="password" class="form-control" placeholder="Enter your password" name="password" id="login-password">
                            <i class="fas fa-eye password-toggle" id="toggle-login-password"></i>
                        </div>
                        <div class="text-end mt-2">
                            <a href="forgot-password" style="text-decoration: none; color: #2196f3;" >Forgot Password?</a>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <button class="btn btn-primary" name="login_submit">Sign In</button>
                    </div>
                    
                    <div class="divider">
                        <span>or continue with</span>
                    </div>
                    
                    <div class="social-login">
                        <button class="social-btn">
                            <i class="fab fa-google"></i> Google
                        </button>
                        <button class="social-btn">
                            <i class="fab fa-microsoft"></i> Microsoft
                        </button>
                    </div>
                    
                    <div class="auth-footer">
                        Don't have an account? <a href="sign-up">Register Now</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Theme toggle
            const themeToggle = document.getElementById('themeToggle');
            const body = document.body;
            
            themeToggle.addEventListener('click', function() {
                body.classList.toggle('dark-mode');
                
                if (body.classList.contains('dark-mode')) {
                    themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
                } else {
                    themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
                }
            });
            
        });
        document.getElementById('toggle-login-password').addEventListener('click', function () {
            const passwordInput = document.getElementById('login-password');
            const toggleIcon = this;
        
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleIcon.classList.remove('fa-eye');
                toggleIcon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                toggleIcon.classList.remove('fa-eye-slash');
                toggleIcon.classList.add('fa-eye');
            }
        });
        document.querySelectorAll('.close-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                this.parentElement.style.display = 'none';
            });
        });
    </script>
</body>
</html>