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

// Redirect if already logged in
if (isLoggedIn()) {
    redirectToDashboard();
}

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'];
    $password = $_POST['password'];
    
    if (login($email, $password)) {
        redirectToDashboard();
    } else {
        $_SESSION['error_message'] = "Invalid email or password.";
    }
}

function redirectToDashboard() {
    switch ($_SESSION['user_type']) {
        case 'student':
            header('Location: student/');
            break;
        case 'counselor':
            header('Location: counselor/');
            break;
        case 'admin':
            header('Location: admin/');
            break;
        default:
            header('Location: ../');
    }
    exit();
}

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

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="card shadow-sm">
                <div class="card-body p-5">
                    <div class="text-center mb-4">
                        <img src="../assets/images/logo.png" alt="JV Overseas" style="height: 60px;">
                        <h3 class="mt-3">Login to Your Account</h3>
                    </div>
                    
                    <?php displayMessages(); ?>
                    
                    <form method="post">
                        <div class="form-group">
                            <label for="email">Email Address</label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="password">Password</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        
                        <div class="form-group form-check">
                            <input type="checkbox" class="form-check-input" id="remember" name="remember">
                            <label class="form-check-label" for="remember">Remember me</label>
                        </div>
                        
                        <button type="submit" class="btn btn-primary btn-block">Login</button>
                        
                        <div class="text-center mt-3">
                            <a href="forgot-password.php">Forgot your password?</a>
                        </div>
                    </form>
                </div>
                
                <div class="card-footer text-center bg-transparent">
                    Don't have an account? <a href="register.php">Register here</a>
                </div>
            </div>
        </div>
    </div>
</div>

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