<?php
/**
 * User Login Page for hubben.net
 * 
 * Allows users to log into their account
 */

// Include configuration
require_once 'config.php';

// Include required files
require_once 'includes/auth.php';

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}


// If user is already logged in, redirect to home page or requested return URL
if (isLoggedIn()) {
    $returnUrl = isset($_GET['return']) ? $_GET['return'] : '/';
    // Only allow relative URLs to prevent open redirect
    if (!preg_match('/^\//', $returnUrl)) $returnUrl = '/';
    redirect($returnUrl);
}

// Initialize variables
$usernameOrEmail = '';
$errors = [];
$success = false;

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || !verifyCsrfToken($_POST['csrf_token'])) {
        $errors[] = __('invalid_csrf_token');
    } elseif (!checkRateLimit('login', 10, 900)) {
        // Rate limit - max 10 login attempts per IP per 15 minutes
        $errors[] = 'Too many login attempts from your IP. Please try again in 15 minutes.';
    } else {
        // Get form data
        $usernameOrEmail = sanitizeInput($_POST['username_email'] ?? '');
        $password = $_POST['password'] ?? '';
        $rememberMe = isset($_POST['remember_me']);
        
        // Basic validation
        if (empty($usernameOrEmail)) {
            $errors[] = __('username_email_required');
        }
        
        if (empty($password)) {
            $errors[] = __('password_required');
        }
        
        // If no errors, attempt to log in
        if (empty($errors)) {
            $result = loginUser($usernameOrEmail, $password, $rememberMe);
            
            if ($result['success']) {
                // Set success flag
                $success = true;
                
                // Add welcome message
                addFlashMessage('success', sprintf(__('welcome_back'), $result['user']['username']));
                
                // Redirect to return URL if set, otherwise to home page
                $returnUrl = isset($_GET['return']) ? $_GET['return'] : '/';
                // Only allow relative URLs to prevent open redirect
                if (!preg_match('/^\//', $returnUrl)) $returnUrl = '/';
                redirect($returnUrl);
            } else {
                // Check if account needs verification
                if (isset($result['needs_verification']) && $result['needs_verification']) {
                    $errors[] = __('account_not_verified');
                    // Store email in session for resend verification link
                    $_SESSION['verification_email'] = $result['email'];
                } else {
                    $errors[] = $result['message'];
                }
            }
        }
    }
}

// Set page title
$pageTitle = __('login');

// Include header
require_once 'includes/header.php';
?>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8 col-lg-6">
            <div class="card shadow-sm">
                <div class="card-header">
                    <h1 class="h3 mb-0"><?php echo __('login_to_account'); ?></h1>
                </div>
                <div class="card-body">
                    <?php if (!empty($errors)): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php foreach ($errors as $error): ?>
                                    <li><?php echo $error; ?></li>
                                <?php endforeach; ?>
                            </ul>
                            
                            <?php if (isset($_SESSION['verification_email'])): ?>
                                <div class="mt-2">
                                    <a href="resend-verification.php?email=<?php echo urlencode($_SESSION['verification_email']); ?>" class="btn btn-sm btn-outline-primary">
                                        <?php echo __('resend_verification_email'); ?>
                                    </a>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    
                    <?php echo displayFlashMessages(); ?>
                    
                    <form method="post" action="login.php<?php echo isset($_GET['return']) ? '?return=' . urlencode($_GET['return']) : ''; ?>">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">

                        <div class="mb-3">
                            <label for="username_email" class="form-label"><?php echo __('username_or_email'); ?></label>
                            <input type="text" class="form-control" id="username_email" name="username_email" value="<?php echo $usernameOrEmail; ?>" required autofocus>
                        </div>

                        <div class="mb-3">
                            <label for="password" class="form-label"><?php echo __('password'); ?></label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>

                        <div class="mb-3 form-check">
                            <input type="checkbox" class="form-check-input" id="remember_me" name="remember_me">
                            <label class="form-check-label" for="remember_me"><?php echo __('remember_me'); ?></label>
                        </div>

                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary"><?php echo __('login'); ?></button>
                        </div>
                    </form>
                </div>
                <div class="card-footer">
                    <div class="d-flex justify-content-between">
                        <a href="forgot-password.php"><?php echo __('forgot_password'); ?></a>
                        <a href="register.php"><?php echo __('create_account'); ?></a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Include footer
require_once 'includes/footer.php';
?>