<?php
// Authentication functions

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

function requireLogin() {
    if (!isLoggedIn()) {
        redirect('/login.php');
    }
}

function requireRole($roles) {
    requireLogin();
    if (!is_array($roles)) $roles = [$roles];
    if (!in_array($_SESSION['user_role'], $roles)) {
        flash('error', 'Accès non autorisé.');
        redirect('/dashboard.php');
    }
}

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

function login($username, $password) {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM users WHERE username = ? AND status = 'actif'");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['full_name'];
        $_SESSION['user_role'] = $user['role'];
        $_SESSION['user_username'] = $user['username'];
        
        $stmt = $db->prepare("UPDATE users SET last_login = datetime('now') WHERE id = ?");
        $stmt->execute([$user['id']]);
        
        logAction($user['id'], 'login', 'Connexion réussie');
        return true;
    }
    return false;
}

function logout() {
    if (isLoggedIn()) {
        logAction($_SESSION['user_id'], 'logout', 'Déconnexion');
    }
    session_destroy();
    header("Location: " . APP_URL . "/login.php");
    exit;
}

function hasPermission($permission) {
    if ($_SESSION['user_role'] === 'admin') return true;
    
    $permissions = [
        'responsable' => ['voyageurs','programmes','groupes','hotels','vols','documents','rapports'],
        'comptable' => ['paiements','depenses','rapports','voyageurs'],
        'agent' => ['voyageurs','programmes','groupes','paiements'],
    ];
    
    $role = $_SESSION['user_role'] ?? '';
    return in_array($permission, $permissions[$role] ?? []);
}
