from django import template
from django.conf import settings

register = template.Library()

@register.filter
def has_role(user, role_name):
    """Check if user has a specific role."""
    if not user.is_authenticated or not hasattr(user, 'role'):
        return False
    return user.role and user.role.name == role_name

@register.filter
def has_any_role(user, roles):
    """Check if user has any of the specified roles."""
    if not user.is_authenticated or not hasattr(user, 'role'):
        return False
    role_list = [r.strip() for r in roles.split(',')]
    return user.role and user.role.name in role_list

@register.filter
def can_manage_user(current_user, target_user):
    """Check if current user can manage target user based on role hierarchy."""
    if not current_user.is_authenticated or not target_user:
        return False
        
    # Superuser can manage everyone
    if current_user.is_superuser:
        return True
        
    # Users can manage themselves
    if current_user == target_user:
        return True
        
    # Check role hierarchy
    role_hierarchy = {
        'president': 1,
        'minister': 2,
        'director': 3,
        'head': 4,
        'secretary': 5
    }
    
    current_role = getattr(current_user.role, 'name', None) if hasattr(current_user, 'role') else None
    target_role = getattr(target_user.role, 'name', None) if hasattr(target_user, 'role') else None
    
    if not current_role or not target_role:
        return False
        
    # Check if current user's role is higher in hierarchy
    if role_hierarchy.get(current_role, 99) < role_hierarchy.get(target_role, 99):
        # Check department hierarchy if applicable
        if current_user.department and target_user.department:
            # Users in the same department or parent department can manage
            return (
                current_user.department == target_user.department or
                current_user.department == target_user.department.parent
            )
        return True
        
    return False
