<?php
session_start();

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function checkSessionTimeout() {
    $timeout = 30 * 60; // 30 minutes in seconds

    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $timeout) {
        // Session has expired
        error_log("Session expired for user: " . ($_SESSION['username'] ?? 'unknown') . " at " . date('Y-m-d H:i:s'));
        session_destroy();
        header('Location: ../login.php?expired=1');
        exit;
    }

    // Update last activity time
    $_SESSION['last_activity'] = time();
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: ../login.php');
        exit;
    }
    checkSessionTimeout();
}

function login($username, $password) {
    $pdo = getDB();
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = $user['role'];
        return true;
    }
    return false;
}

function logout() {
    session_destroy();
    header('Location: home.php');
    exit;
}

function getCurrentUser() {
    if (!isLoggedIn()) return null;
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    return $stmt->fetch();
}
?>