
<?php
/**
 * Role-Based Access Control (RBAC)
 * OBGYN Research & Collaboration Platform
 */

/**
 * Check if user has role
 */
function hasRole($roleId) {
    return getCurrentUserRole() == $roleId;
}

/**
 * Check if user is super admin
 */
function isSuperAdmin() {
    return hasRole(ROLE_SUPER_ADMIN);
}

/**
 * Check if user is institution admin
 */
function isInstitutionAdmin() {
    return hasRole(ROLE_INSTITUTION_ADMIN);
}

/**
 * Check if user is researcher
 */
function isResearcher() {
    return hasRole(ROLE_RESEARCHER);
}

/**
 * Check if user is guest
 */
function isGuest() {
    return hasRole(ROLE_GUEST);
}

/**
 * Get user permissions
 */
function getUserPermissions($userId) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT p.name, p.description, p.module
            FROM users u
            JOIN role_permissions rp ON u.role_id = rp.role_id
            JOIN permissions p ON rp.permission_id = p.id
            WHERE u.id = ?
        ");
        $stmt->execute([$userId]);
        return $stmt->fetchAll();
    } catch (Exception $e) {
        error_log("Get permissions error: " . $e->getMessage());
        return [];
    }
}

/**
 * Check if user can perform action
 */
function canPerformAction($action) {
    $userId = getCurrentUserId();
    if (!$userId) {
        return false;
    }
    
    return userHasPermission($userId, $action);
}

/**
 * Require permission
 */
function requirePermission($permission) {
    if (!canPerformAction($permission)) {
        setFlashMessage('error', 'You do not have permission to perform this action.');
        redirect(SITE_URL . '/index.php');
    }
}

/**
 * Check if user can manage study
 */
function canManageStudy($studyId, $userId = null) {
    $userId = $userId ?? getCurrentUserId();
    
    if (!$userId) {
        return false;
    }
    
    // Super admin can manage all studies
    if (isSuperAdmin()) {
        return true;
    }
    
    try {
        $db = getDB();
        
        // Check if user is creator or collaborator with appropriate role
        $stmt = $db->prepare("
            SELECT COUNT(*) 
            FROM studies s
            LEFT JOIN study_collaborators sc ON s.id = sc.study_id
            WHERE s.id = ? 
            AND (
                s.creator_id = ? 
                OR (sc.user_id = ? AND sc.role IN ('lead', 'co_investigator') AND sc.status = 'active')
            )
        ");
        $stmt->execute([$studyId, $userId, $userId]);
        return $stmt->fetchColumn() > 0;
    } catch (Exception $e) {
        error_log("Can manage study error: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if user can view study
 */
function canViewStudy($studyId, $userId = null) {
    $userId = $userId ?? getCurrentUserId();
    
    try {
        $db = getDB();
        
        // Check if study is public
        $stmt = $db->prepare("SELECT is_public, creator_id FROM studies WHERE id = ?");
        $stmt->execute([$studyId]);
        $study = $stmt->fetch();
        
        if (!$study) {
            return false;
        }
        
        // Public studies can be viewed by anyone
        if ($study['is_public']) {
            return true;
        }
        
        // Not logged in and study is private
        if (!$userId) {
            return false;
        }
        
        // Super admin can view all
        if (isSuperAdmin()) {
            return true;
        }
        
        // Creator can view
        if ($study['creator_id'] == $userId) {
            return true;
        }
        
        // Check if user is collaborator
        $stmt = $db->prepare("
            SELECT COUNT(*) 
            FROM study_collaborators 
            WHERE study_id = ? AND user_id = ? AND status = 'active'
        ");
        $stmt->execute([$studyId, $userId]);
        return $stmt->fetchColumn() > 0;
        
    } catch (Exception $e) {
        error_log("Can view study error: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if user can manage institution
 */
function canManageInstitution($institutionId, $userId = null) {
    $userId = $userId ?? getCurrentUserId();
    
    if (!$userId) {
        return false;
    }
    
    // Super admin can manage all institutions
    if (isSuperAdmin()) {
        return true;
    }
    
    try {
        $db = getDB();
        
        // Check if user is institution admin
        $stmt = $db->prepare("
            SELECT COUNT(*) 
            FROM institutions 
            WHERE id = ? AND admin_user_id = ?
        ");
        $stmt->execute([$institutionId, $userId]);
        return $stmt->fetchColumn() > 0;
    } catch (Exception $e) {
        error_log("Can manage institution error: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if user can edit profile
 */
function canEditProfile($profileUserId, $userId = null) {
    $userId = $userId ?? getCurrentUserId();
    
    if (!$userId) {
        return false;
    }
    
    // Super admin can edit all profiles
    if (isSuperAdmin()) {
        return true;
    }
    
    // Users can edit their own profile
    return $userId == $profileUserId;
}

/**
 * Check if user can moderate content
 */
function canModerateContent() {
    return isSuperAdmin() || isInstitutionAdmin();
}

/**
 * Check if user can approve studies
 */
function canApproveStudies() {
    return isSuperAdmin() || isInstitutionAdmin();
}

/**
 * Check if user can manage users
 */
function canManageUsers() {
    return isSuperAdmin() || isInstitutionAdmin();
}

/**
 * Check if user can access admin panel
 */
function canAccessAdminPanel() {
    return isSuperAdmin() || isInstitutionAdmin();
}

/**
 * Check if user can send messages
 */
function canSendMessages($recipientId = null) {
    $userId = getCurrentUserId();
    
    if (!$userId) {
        return false;
    }
    
    // Check if user is verified researcher
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT status, email_verified 
            FROM users 
            WHERE id = ?
        ");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        if (!$user || $user['status'] !== 'active' || !$user['email_verified']) {
            return false;
        }
        
        // If recipient specified, check if they are connected or have approved contact sharing
        if ($recipientId) {
            $stmt = $db->prepare("
                SELECT COUNT(*) 
                FROM connections 
                WHERE ((requester_id = ? AND receiver_id = ?) OR (requester_id = ? AND receiver_id = ?))
                AND status = 'accepted'
            ");
            $stmt->execute([$userId, $recipientId, $recipientId, $userId]);
            
            if ($stmt->fetchColumn() > 0) {
                return true;
            }
            
            // Check contact approval
            $stmt = $db->prepare("
                SELECT COUNT(*) 
                FROM contact_approvals 
                WHERE ((requester_id = ? AND receiver_id = ?) OR (requester_id = ? AND receiver_id = ?))
                AND status = 'approved'
            ");
            $stmt->execute([$userId, $recipientId, $recipientId, $userId]);
            
            return $stmt->fetchColumn() > 0;
        }
        
        return true;
        
    } catch (Exception $e) {
        error_log("Can send messages error: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if user can upload files
 */
function canUploadFiles() {
    $userId = getCurrentUserId();
    
    if (!$userId) {
        return false;
    }
    
    // Check if user is verified
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT status, email_verified 
            FROM users 
            WHERE id = ?
        ");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        return $user && $user['status'] === 'active' && $user['email_verified'];
        
    } catch (Exception $e) {
        error_log("Can upload files error: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if user can create study
 */
function canCreateStudy() {
    return isLoggedIn() && (isResearcher() || isInstitutionAdmin() || isSuperAdmin());
}

/**
 * Check if user can publish content
 */
function canPublishContent() {
    return isLoggedIn() && (isResearcher() || isInstitutionAdmin() || isSuperAdmin());
}

/**
 * Check if user can comment
 */
function canComment() {
    $userId = getCurrentUserId();
    
    if (!$userId) {
        return false;
    }
    
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT status, email_verified 
            FROM users 
            WHERE id = ?
        ");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();
        
        return $user && $user['status'] === 'active' && $user['email_verified'];
        
    } catch (Exception $e) {
        error_log("Can comment error: " . $e->getMessage());
        return false;
    }
}

/**
 * Get role name
 */
function getRoleName($roleId) {
    $roles = [
        ROLE_SUPER_ADMIN => 'Super Administrator',
        ROLE_INSTITUTION_ADMIN => 'Institution Administrator',
        ROLE_RESEARCHER => 'Researcher',
        ROLE_GUEST => 'Guest'
    ];
    
    return $roles[$roleId] ?? 'Unknown';
}

/**
 * Get user's institution
 */
function getUserInstitution($userId) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT i.* 
            FROM institutions i
            JOIN researcher_profiles rp ON i.id = rp.institution_id
            WHERE rp.user_id = ?
        ");
        $stmt->execute([$userId]);
        return $stmt->fetch();
    } catch (Exception $e) {
        error_log("Get user institution error: " . $e->getMessage());
        return null;
    }
}

/**
 * Check if users are connected
 */
function areUsersConnected($userId1, $userId2) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT COUNT(*) 
            FROM connections 
            WHERE ((requester_id = ? AND receiver_id = ?) OR (requester_id = ? AND receiver_id = ?))
            AND status = 'accepted'
        ");
        $stmt->execute([$userId1, $userId2, $userId2, $userId1]);
        return $stmt->fetchColumn() > 0;
    } catch (Exception $e) {
        error_log("Are users connected error: " . $e->getMessage());
        return false;
    }
}

/**
 * Check if user is following another user
 */
function isFollowing($followerId, $followingId) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT COUNT(*) 
            FROM followers 
            WHERE follower_id = ? AND following_id = ?
        ");
        $stmt->execute([$followerId, $followingId]);
        return $stmt->fetchColumn() > 0;
    } catch (Exception $e) {
        error_log("Is following error: " . $e->getMessage());
        return false;
    }
}

/**
 * Get connection status between users
 */
function getConnectionStatus($userId1, $userId2) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT status, requester_id 
            FROM connections 
            WHERE (requester_id = ? AND receiver_id = ?) OR (requester_id = ? AND receiver_id = ?)
        ");
        $stmt->execute([$userId1, $userId2, $userId2, $userId1]);
        $connection = $stmt->fetch();
        
        if (!$connection) {
            return 'none';
        }
        
        if ($connection['status'] === 'accepted') {
            return 'connected';
        }
        
        if ($connection['status'] === 'pending') {
            return $connection['requester_id'] == $userId1 ? 'pending_sent' : 'pending_received';
        }
        
        return $connection['status'];
        
    } catch (Exception $e) {
        error_log("Get connection status error: " . $e->getMessage());
        return 'none';
    }
}

/**
 * Require admin access
 */
function requireAdmin() {
    requireLogin();
    if (!canAccessAdminPanel()) {
        setFlashMessage('error', 'You do not have permission to access the admin panel.');
        redirect(SITE_URL . '/index.php');
    }
}

/**
 * Require super admin access
 */
function requireSuperAdmin() {
    requireLogin();
    if (!isSuperAdmin()) {
        setFlashMessage('error', 'You do not have permission to access this area.');
        redirect(SITE_URL . '/index.php');
    }
}
?>
