"""Advertisers Views

This module contains views for managing advertisers, brands, and agencies.
Includes both API views and traditional Django views for CRUD operations.

Views:
    - AgencyViewSet: API views for agency management
    - BrandViewSet: API views for brand management
    - BrandCategoryViewSet: API views for brand category management
    - UserAdvertiserViewSet: API views for user-advertiser relationships
    - Agency/Brand list, create, update, delete views
"""

import logging
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.db.models import Q, Count, Sum, Avg
from django.http import JsonResponse, HttpResponse, Http404
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy, reverse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.utils import timezone
from django import models

from rest_framework import viewsets, status, filters, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend

from .models import Agency, Brand, BrandCategory, UserAdvertiser
from .serializers import (
    AgencySerializer, BrandSerializer, BrandCategorySerializer,
    UserAdvertiserSerializer, AgencyDetailSerializer, BrandDetailSerializer
)
from .filters import AgencyFilter, BrandFilter
from apps.core.permissions import IsOwnerOrReadOnly
from apps.core.utils import check_user_permissions


logger = logging.getLogger(__name__)


# ============================================================================
# API ViewSets (REST Framework)
# ============================================================================

class AgencyViewSet(viewsets.ModelViewSet):
    """API ViewSet for Agency management.
    
    Provides CRUD operations for agencies with filtering, searching,
    and pagination capabilities.
    
    Endpoints:
        GET /api/agencies/ - List all agencies
        POST /api/agencies/ - Create new agency
        GET /api/agencies/{id}/ - Retrieve specific agency
        PUT /api/agencies/{id}/ - Update agency
        DELETE /api/agencies/{id}/ - Delete agency
        GET /api/agencies/{id}/brands/ - Get agency's brands
        GET /api/agencies/{id}/stats/ - Get agency statistics
    """
    
    queryset = Agency.objects.all()
    permission_classes = [IsAuthenticated, IsOwnerOrReadOnly]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = AgencyFilter
    search_fields = ['name', 'description', 'contact_person']
    ordering_fields = ['name', 'created_at', 'updated_at']
    ordering = ['name']
    
    def get_serializer_class(self):
        """Return appropriate serializer based on action."""
        if self.action == 'retrieve':
            return AgencyDetailSerializer
        return AgencySerializer
    
    def get_queryset(self):
        """Filter queryset based on user permissions."""
        queryset = super().get_queryset()
        
        # Filter based on user role and permissions
        if not self.request.user.is_superuser:
            # Users can only see agencies they own or have access to
            queryset = queryset.filter(
                Q(owner=self.request.user) |
                Q(brands__user_relationships__user=self.request.user)
            ).distinct()
        
        return queryset.select_related('owner').prefetch_related('brands')
    
    def perform_create(self, serializer):
        """Set the owner when creating an agency."""
        serializer.save(owner=self.request.user)
        logger.info(f"Agency '{serializer.instance.name}' created by {self.request.user.username}")
    
    @action(detail=True, methods=['get'])
    def brands(self, request, pk=None):
        """Get all brands associated with this agency."""
        agency = self.get_object()
        brands = agency.brands.filter(status='active')
        serializer = BrandSerializer(brands, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['get'])
    def stats(self, request, pk=None):
        """Get statistics for this agency."""
        agency = self.get_object()
        
        stats = {
            'total_brands': agency.total_brands,
            'total_campaigns': agency.total_campaigns,
            'active_campaigns': agency.brands.filter(
                campaigns__status='active'
            ).aggregate(count=Count('campaigns'))['count'] or 0,
            'total_budget': agency.brands.aggregate(
                total=Sum('annual_budget')
            )['total'] or 0
        }
        
        return Response(stats)


class BrandViewSet(viewsets.ModelViewSet):
    """API ViewSet for Brand management.
    
    Provides CRUD operations for brands with filtering, searching,
    and pagination capabilities.
    
    Endpoints:
        GET /api/brands/ - List all brands
        POST /api/brands/ - Create new brand
        GET /api/brands/{id}/ - Retrieve specific brand
        PUT /api/brands/{id}/ - Update brand
        DELETE /api/brands/{id}/ - Delete brand
        GET /api/brands/{id}/campaigns/ - Get brand's campaigns
        GET /api/brands/{id}/stats/ - Get brand statistics
    """
    
    queryset = Brand.objects.all()
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_class = BrandFilter
    search_fields = ['name', 'description', 'industry']
    ordering_fields = ['name', 'created_at', 'updated_at']
    ordering = ['name']
    
    def get_serializer_class(self):
        """Return appropriate serializer based on action."""
        if self.action == 'retrieve':
            return BrandDetailSerializer
        return BrandSerializer
    
    def get_queryset(self):
        """Filter queryset based on user permissions."""
        queryset = super().get_queryset()
        
        # Filter based on user role and permissions
        if not self.request.user.is_superuser:
            # Users can only see brands they have access to
            queryset = queryset.filter(
                Q(agency__owner=self.request.user) |
                Q(user_relationships__user=self.request.user)
            ).distinct()
        
        return queryset.select_related('agency', 'category').prefetch_related('campaigns')
    
    @action(detail=True, methods=['get'])
    def campaigns(self, request, pk=None):
        """Get all campaigns for this brand."""
        brand = self.get_object()
        campaigns = brand.campaigns.filter(status='active')
        
        # Import here to avoid circular imports
        from apps.campaigns.serializers import CampaignSerializer
        serializer = CampaignSerializer(campaigns, many=True)
        return Response(serializer.data)
    
    @action(detail=True, methods=['get'])
    def stats(self, request, pk=None):
        """Get statistics for this brand."""
        brand = self.get_object()
        
        stats = {
            'total_campaigns': brand.total_campaigns,
            'active_campaigns': brand.active_campaigns.count(),
            'total_budget_spent': float(brand.total_budget_spent),
            'annual_budget': float(brand.annual_budget) if brand.annual_budget else 0
        }
        
        return Response(stats)


class BrandCategoryViewSet(viewsets.ModelViewSet):
    """API ViewSet for Brand Category management.
    
    Provides CRUD operations for brand categories with hierarchical support.
    """
    
    queryset = BrandCategory.objects.all()
    serializer_class = BrandCategorySerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['name', 'description']
    ordering_fields = ['name', 'created_at']
    ordering = ['name']
    
    @action(detail=False, methods=['get'])
    def tree(self, request):
        """Get hierarchical tree of categories."""
        root_categories = self.queryset.filter(parent=None)
        serializer = self.get_serializer(root_categories, many=True)
        return Response(serializer.data)


class UserAdvertiserViewSet(viewsets.ModelViewSet):
    """API ViewSet for User-Advertiser relationship management."""
    
    queryset = UserAdvertiser.objects.all()
    serializer_class = UserAdvertiserSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['user', 'brand', 'role', 'is_active']
    ordering_fields = ['created_at', 'updated_at']
    ordering = ['-created_at']
    
    def get_queryset(self):
        """Filter based on user permissions."""
        queryset = super().get_queryset()
        
        if not self.request.user.is_superuser:
            # Users can only see their own relationships or relationships for brands they manage
            queryset = queryset.filter(
                Q(user=self.request.user) |
                Q(brand__agency__owner=self.request.user)
            ).distinct()
        
        return queryset.select_related('user', 'brand', 'brand__agency')


# ============================================================================
# Traditional Django Views
# ============================================================================

@login_required
def agency_list(request):
    """Display list of agencies with search and pagination."""
    search_query = request.GET.get('search', '')
    agencies = Agency.objects.filter(status='active')
    
    # Apply search filter
    if search_query:
        agencies = agencies.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query) |
            Q(contact_person__icontains=search_query)
        )
    
    # Filter based on user permissions
    if not request.user.is_superuser:
        agencies = agencies.filter(
            Q(owner=request.user) |
            Q(brands__user_relationships__user=request.user)
        ).distinct()
    
    # Pagination
    paginator = Paginator(agencies, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search_query': search_query,
        'total_agencies': agencies.count()
    }
    
    return render(request, 'advertisers/agency_list.html', context)


@login_required
def agency_detail(request, agency_id):
    """Display detailed view of an agency."""
    agency = get_object_or_404(Agency, id=agency_id, status='active')
    
    # Check permissions
    if not request.user.is_superuser and agency.owner != request.user:
        # Check if user has access through brand relationships
        if not agency.brands.filter(user_relationships__user=request.user).exists():
            messages.error(request, "You don't have permission to view this agency.")
            return redirect('advertisers:agency_list')
    
    brands = agency.brands.filter(status='active')
    
    context = {
        'agency': agency,
        'brands': brands,
        'total_brands': brands.count(),
        'total_campaigns': agency.total_campaigns
    }
    
    return render(request, 'advertisers/agency_detail.html', context)


@login_required
def brand_list(request):
    """Display list of brands with search and filtering."""
    search_query = request.GET.get('search', '')
    agency_filter = request.GET.get('agency', '')
    category_filter = request.GET.get('category', '')
    
    brands = Brand.objects.filter(status='active')
    
    # Apply filters
    if search_query:
        brands = brands.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query) |
            Q(industry__icontains=search_query)
        )
    
    if agency_filter:
        brands = brands.filter(agency_id=agency_filter)
    
    if category_filter:
        brands = brands.filter(category_id=category_filter)
    
    # Filter based on user permissions
    if not request.user.is_superuser:
        brands = brands.filter(
            Q(agency__owner=request.user) |
            Q(user_relationships__user=request.user)
        ).distinct()
    
    # Get filter options
    agencies = Agency.objects.filter(status='active')
    categories = BrandCategory.objects.all()
    
    if not request.user.is_superuser:
        agencies = agencies.filter(
            Q(owner=request.user) |
            Q(brands__user_relationships__user=request.user)
        ).distinct()
    
    # Pagination
    paginator = Paginator(brands, 12)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search_query': search_query,
        'agencies': agencies,
        'categories': categories,
        'selected_agency': agency_filter,
        'selected_category': category_filter,
        'total_brands': brands.count()
    }
    
    return render(request, 'advertisers/brand_list.html', context)


@login_required
def brand_detail(request, brand_id):
    """Display detailed view of a brand."""
    brand = get_object_or_404(Brand, id=brand_id, status='active')
    
    # Check permissions
    if not request.user.is_superuser:
        if (brand.agency.owner != request.user and 
            not brand.user_relationships.filter(user=request.user).exists()):
            messages.error(request, "You don't have permission to view this brand.")
            return redirect('advertisers:brand_list')
    
    campaigns = brand.campaigns.filter(status='active')[:5]  # Latest 5 campaigns
    
    context = {
        'brand': brand,
        'campaigns': campaigns,
        'total_campaigns': brand.total_campaigns,
        'active_campaigns': brand.active_campaigns.count(),
        'total_budget_spent': brand.total_budget_spent
    }
    
    return render(request, 'advertisers/brand_detail.html', context)


# ============================================================================
# AJAX Views
# ============================================================================

@login_required
@require_http_methods(["GET"])
def get_agency_brands(request, agency_id):
    """AJAX endpoint to get brands for a specific agency."""
    try:
        agency = get_object_or_404(Agency, id=agency_id)
        brands = agency.brands.filter(status='active').values('id', 'name')
        return JsonResponse({'brands': list(brands)})
    except Exception as e:
        logger.error(f"Error fetching brands for agency {agency_id}: {str(e)}")
        return JsonResponse({'error': 'Failed to fetch brands'}, status=500)


@login_required
@require_http_methods(["POST"])
@csrf_exempt
def toggle_brand_status(request, brand_id):
    """AJAX endpoint to toggle brand active status."""
    try:
        brand = get_object_or_404(Brand, id=brand_id)
        
        # Check permissions
        if not request.user.is_superuser and brand.agency.owner != request.user:
            return JsonResponse({'error': 'Permission denied'}, status=403)
        
        brand.status = 'inactive' if brand.status == 'active' else 'active'
        brand.save()
        
        logger.info(f"Brand '{brand.name}' status changed to {brand.status} by {request.user.username}")
        
        return JsonResponse({
            'success': True,
            'new_status': brand.status,
            'message': f"Brand status updated to {brand.status}"
        })
    
    except Exception as e:
        logger.error(f"Error toggling brand status: {str(e)}")
        return JsonResponse({'error': 'Failed to update brand status'}, status=500)


# ============================================================================
# CRUD Views for Agencies
# ============================================================================

@login_required
def agency_create(request):
    """Create a new agency."""
    from .forms import AgencyForm
    
    if request.method == 'POST':
        form = AgencyForm(request.POST, request.FILES, user=request.user)
        if form.is_valid():
            agency = form.save()
            messages.success(request, f"Agency '{agency.name}' created successfully.")
            logger.info(f"Agency '{agency.name}' created by {request.user.username}")
            return redirect('advertisers:agency_detail', agency_id=agency.id)
    else:
        form = AgencyForm(user=request.user)
    
    context = {
        'form': form,
        'title': 'Create New Agency',
        'submit_text': 'Create Agency'
    }
    
    return render(request, 'advertisers/agency_form.html', context)


@login_required
def agency_edit(request, agency_id):
    """Edit an existing agency."""
    from .forms import AgencyForm
    
    agency = get_object_or_404(Agency, id=agency_id)
    
    # Check permissions
    if not request.user.is_superuser and agency.owner != request.user:
        messages.error(request, "You don't have permission to edit this agency.")
        return redirect('advertisers:agency_detail', agency_id=agency.id)
    
    if request.method == 'POST':
        form = AgencyForm(request.POST, request.FILES, instance=agency, user=request.user)
        if form.is_valid():
            agency = form.save()
            messages.success(request, f"Agency '{agency.name}' updated successfully.")
            logger.info(f"Agency '{agency.name}' updated by {request.user.username}")
            return redirect('advertisers:agency_detail', agency_id=agency.id)
    else:
        form = AgencyForm(instance=agency, user=request.user)
    
    context = {
        'form': form,
        'agency': agency,
        'title': f'Edit {agency.name}',
        'submit_text': 'Update Agency'
    }
    
    return render(request, 'advertisers/agency_form.html', context)


@login_required
def agency_delete(request, agency_id):
    """Delete an agency."""
    agency = get_object_or_404(Agency, id=agency_id)
    
    # Check permissions
    if not request.user.is_superuser and agency.owner != request.user:
        messages.error(request, "You don't have permission to delete this agency.")
        return redirect('advertisers:agency_detail', agency_id=agency.id)
    
    if request.method == 'POST':
        agency_name = agency.name
        agency.delete()
        messages.success(request, f"Agency '{agency_name}' deleted successfully.")
        logger.info(f"Agency '{agency_name}' deleted by {request.user.username}")
        return redirect('advertisers:agency_list')
    
    context = {
        'agency': agency,
        'title': f'Delete {agency.name}'
    }
    
    return render(request, 'advertisers/agency_confirm_delete.html', context)


# ============================================================================
# CRUD Views for Brands
# ============================================================================

@login_required
def brand_create(request):
    """Create a new brand."""
    from .forms import BrandForm
    
    # Get agency from query parameter if provided
    agency_id = request.GET.get('agency')
    initial_data = {}
    if agency_id:
        try:
            agency = Agency.objects.get(id=agency_id, status='active')
            # Check if user has permission to create brands for this agency
            if request.user.is_superuser or agency.owner == request.user:
                initial_data['agency'] = agency
        except Agency.DoesNotExist:
            pass
    
    if request.method == 'POST':
        form = BrandForm(request.POST, request.FILES, user=request.user)
        if form.is_valid():
            brand = form.save()
            messages.success(request, f"Brand '{brand.name}' created successfully.")
            logger.info(f"Brand '{brand.name}' created by {request.user.username}")
            return redirect('advertisers:brand_detail', brand_id=brand.id)
    else:
        form = BrandForm(initial=initial_data, user=request.user)
    
    context = {
        'form': form,
        'title': 'Create New Brand',
        'submit_text': 'Create Brand'
    }
    
    return render(request, 'advertisers/brand_form.html', context)


@login_required
def brand_edit(request, brand_id):
    """Edit an existing brand."""
    from .forms import BrandForm
    
    brand = get_object_or_404(Brand, id=brand_id)
    
    # Check permissions
    if not request.user.is_superuser:
        if (brand.agency.owner != request.user and 
            not brand.user_relationships.filter(user=request.user, role__in=['manager', 'admin']).exists()):
            messages.error(request, "You don't have permission to edit this brand.")
            return redirect('advertisers:brand_detail', brand_id=brand.id)
    
    if request.method == 'POST':
        form = BrandForm(request.POST, request.FILES, instance=brand, user=request.user)
        if form.is_valid():
            brand = form.save()
            messages.success(request, f"Brand '{brand.name}' updated successfully.")
            logger.info(f"Brand '{brand.name}' updated by {request.user.username}")
            return redirect('advertisers:brand_detail', brand_id=brand.id)
    else:
        form = BrandForm(instance=brand, user=request.user)
    
    context = {
        'form': form,
        'brand': brand,
        'title': f'Edit {brand.name}',
        'submit_text': 'Update Brand'
    }
    
    return render(request, 'advertisers/brand_form.html', context)


@login_required
def brand_delete(request, brand_id):
    """Delete a brand."""
    brand = get_object_or_404(Brand, id=brand_id)
    
    # Check permissions
    if not request.user.is_superuser:
        if (brand.agency.owner != request.user and 
            not brand.user_relationships.filter(user=request.user, role='admin').exists()):
            messages.error(request, "You don't have permission to delete this brand.")
            return redirect('advertisers:brand_detail', brand_id=brand.id)
    
    if request.method == 'POST':
        brand_name = brand.name
        agency = brand.agency
        brand.delete()
        messages.success(request, f"Brand '{brand_name}' deleted successfully.")
        logger.info(f"Brand '{brand_name}' deleted by {request.user.username}")
        return redirect('advertisers:agency_detail', agency_id=agency.id)
    
    context = {
        'brand': brand,
        'title': f'Delete {brand.name}'
    }
    
    return render(request, 'advertisers/brand_confirm_delete.html', context)


# ============================================================================
# Performance and Analytics Views
# ============================================================================

@login_required
@require_http_methods(["GET"])
def agency_performance_data(request, agency_id):
    """AJAX endpoint to get agency performance data for charts."""
    try:
        agency = get_object_or_404(Agency, id=agency_id)
        
        # Check permissions
        if not request.user.is_superuser and agency.owner != request.user:
            if not agency.brands.filter(user_relationships__user=request.user).exists():
                return JsonResponse({'error': 'Permission denied'}, status=403)
        
        period = request.GET.get('period', '30')  # days
        
        # Sample performance data (replace with actual analytics)
        performance_data = {
            'impressions': [1200, 1350, 1100, 1400, 1250, 1600, 1450],
            'clicks': [45, 52, 38, 61, 48, 73, 56],
            'conversions': [3, 4, 2, 5, 3, 6, 4],
            'dates': ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07'],
            'ctr': 4.2,
            'conversion_rate': 8.1,
            'total_budget': float(agency.brands.aggregate(total=Sum('annual_budget'))['total'] or 0)
        }
        
        return JsonResponse(performance_data)
    
    except Exception as e:
        logger.error(f"Error fetching agency performance data: {str(e)}")
        return JsonResponse({'error': 'Failed to fetch performance data'}, status=500)


@login_required
@require_http_methods(["GET"])
def brand_performance_data(request, brand_id):
    """AJAX endpoint to get brand performance data for charts."""
    try:
        brand = get_object_or_404(Brand, id=brand_id)
        
        # Check permissions
        if not request.user.is_superuser:
            if (brand.agency.owner != request.user and 
                not brand.user_relationships.filter(user=request.user).exists()):
                return JsonResponse({'error': 'Permission denied'}, status=403)
        
        period = request.GET.get('period', '30')  # days
        
        # Sample performance data (replace with actual analytics)
        performance_data = {
            'impressions': [800, 950, 720, 1100, 890, 1200, 1050],
            'clicks': [32, 41, 28, 48, 35, 56, 42],
            'conversions': [2, 3, 1, 4, 2, 5, 3],
            'dates': ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07'],
            'ctr': 3.8,
            'conversion_rate': 7.5,
            'budget_spent': float(brand.total_budget_spent),
            'annual_budget': float(brand.annual_budget) if brand.annual_budget else 0
        }
        
        return JsonResponse(performance_data)
    
    except Exception as e:
        logger.error(f"Error fetching brand performance data: {str(e)}")
        return JsonResponse({'error': 'Failed to fetch performance data'}, status=500)


# ============================================================================
# Utility Views
# ============================================================================

@login_required
def advertiser_list(request):
    """
    Display a combined list of agencies and brands with filtering and search.
    
    This view provides a unified interface for managing both agencies and brands,
    with advanced filtering, search, and pagination capabilities.
    """
    # Get search query
    search_query = request.GET.get('search', '').strip()
    
    # Get filter parameters
    agency_filter = request.GET.get('agency', '')
    category_filter = request.GET.get('category', '')
    status_filter = request.GET.get('status', '')
    
    # Base querysets with permission filtering
    if request.user.is_superuser:
        agencies = Agency.objects.filter(status='active')
        brands = Brand.objects.filter(status='active')
    else:
        # Get agencies where user is owner or has brand relationships
        user_agencies = Agency.objects.filter(
            Q(owner=request.user) |
            Q(brands__user_relationships__user=request.user)
        ).filter(status='active').distinct()
        
        agencies = user_agencies
        brands = Brand.objects.filter(
            agency__in=user_agencies,
            status='active'
        )
    
    # Apply search filters
    if search_query:
        agencies = agencies.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query) |
            Q(contact_person__icontains=search_query)
        )
        brands = brands.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query) |
            Q(industry__icontains=search_query)
        )
    
    # Apply agency filter to brands
    if agency_filter:
        brands = brands.filter(agency_id=agency_filter)
    
    # Apply category filter to brands
    if category_filter:
        brands = brands.filter(category_id=category_filter)
    
    # Apply status filter
    if status_filter:
        if status_filter == 'active':
            agencies = agencies.filter(status='active')
            brands = brands.filter(status='active')
        elif status_filter == 'inactive':
            agencies = agencies.filter(status='inactive')
            brands = brands.filter(status='inactive')
    
    # Get filter options
    all_agencies = Agency.objects.filter(status='active')
    if not request.user.is_superuser:
        all_agencies = all_agencies.filter(
            Q(owner=request.user) |
            Q(brands__user_relationships__user=request.user)
        ).distinct()
    
    categories = BrandCategory.objects.all()
    
    # Calculate statistics
    total_agencies = agencies.count()
    total_brands = brands.count()
    active_campaigns = 0  # Would be calculated from campaign data
    total_budget = brands.aggregate(
        total=Sum('annual_budget')
    )['total'] or 0
    
    # Pagination for brands (main content)
    paginator = Paginator(brands.select_related('agency', 'category'), 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'agencies': all_agencies,
        'brands': page_obj,
        'categories': categories,
        'search_query': search_query,
        'agency_filter': agency_filter,
        'category_filter': category_filter,
        'status_filter': status_filter,
        'total_agencies': total_agencies,
        'total_brands': total_brands,
        'active_campaigns': active_campaigns,
        'total_budget': total_budget,
        'page_obj': page_obj,
    }
    
    return render(request, 'advertisers/list.html', context)


@login_required
def dashboard_stats(request):
    """
    Get dashboard statistics for agencies and brands.
    
    Returns aggregated statistics including:
    - Total agencies and brands
    - Total campaigns and budget
    - Filtered by user permissions
    """
    # Filter based on user permissions
    if request.user.is_superuser:
        agencies = Agency.objects.filter(status='active')
        brands = Brand.objects.filter(status='active')
    else:
        # Get agencies where user is owner or has brand relationships
        user_agencies = Agency.objects.filter(
            Q(owner=request.user) |
            Q(brands__user_relationships__user=request.user)
        ).filter(status='active').distinct()
        
        agencies = user_agencies
        brands = Brand.objects.filter(
            agency__in=user_agencies,
            status='active'
        )
    
    # Calculate statistics
    total_agencies = agencies.count()
    total_brands = brands.count()
    
    # These would be calculated from actual campaign data
    total_campaigns = 0  # Sum of campaigns from all brands
    total_budget = 0     # Sum of budgets from all brands
    
    # Sample data for now
    stats = {
        'total_agencies': total_agencies,
        'total_brands': total_brands,
        'total_campaigns': total_campaigns,
        'total_budget': total_budget,
        'active_campaigns': 0,
        'budget_spent': 0,
    }
    
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return JsonResponse(stats)
    
    return JsonResponse(stats)