from users.models import Branch

def branches(request):
    """
    Context processor to make branches available in all templates
    """
    context = {}
    
    if request.user.is_authenticated:
        if request.user.role == 'admin':
            # Admin users can see all active branches
            user_branches = Branch.objects.filter(is_active=True).order_by('name')
        else:
            # Non-admin users see their accessible branches plus their assigned branch
            accessible_branches = request.user.accessible_branches.filter(is_active=True)
            if request.user.branch and request.user.branch.is_active:
                # Combine accessible branches with user's assigned branch
                branch_ids = list(accessible_branches.values_list('id', flat=True))
                if request.user.branch.id not in branch_ids:
                    user_branches = accessible_branches.union(
                        Branch.objects.filter(id=request.user.branch.id)
                    ).order_by('name')
                else:
                    user_branches = accessible_branches.order_by('name')
            else:
                user_branches = accessible_branches.order_by('name')
        
        # Get selected branch from session
        selected_branch_id = request.session.get('selected_branch_id')
        if selected_branch_id:
            try:
                selected_branch = Branch.objects.get(id=selected_branch_id)
                context['selected_branch'] = selected_branch
                # Ensure current_branch matches selected_branch for consistency
                context['current_branch'] = selected_branch
            except Branch.DoesNotExist:
                # If selected branch doesn't exist, fall back to request.branch
                context['current_branch'] = getattr(request, 'branch', None)
        else:
            # No selected branch, use request.branch
            context['current_branch'] = getattr(request, 'branch', None)
        
        context['user_branches'] = user_branches
    else:
        context['user_branches'] = Branch.objects.none()
        context['current_branch'] = None
    
    return context
