<?php
// ============================================
// AUTH - Check si user est loggé
// ============================================

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config.php';

function requireLogin() {
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
        redirect('login.php');
    }

    // Check session timeout
    if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > SESSION_LIFETIME) {
        session_unset();
        session_destroy();
        redirect('login.php?timeout=1');
    }

    $_SESSION['last_activity'] = time();
}

function getCurrentUser() {
    if (!isset($_SESSION['user_id'])) return null;

    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT id, username, full_name, email, role, last_login FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        return $stmt->fetch();
    } catch (Exception $e) {
        return null;
    }
}

function getUnreadMessagesCount() {
    try {
        $db = getDB();
        $stmt = $db->query("SELECT COUNT(*) FROM messages WHERE is_read = 0");
        return (int)$stmt->fetchColumn();
    } catch (Exception $e) {
        return 0;
    }
}
