from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.utils.timezone import now, timedelta
from datetime import datetime

from accounts.models import Customers


def get_customer_statistics(company):
    try:
        today = now().date()
        start_of_week = today - timedelta(days=today.weekday())
        start_of_month = today.replace(day=1)
        start_of_year = today.replace(month=1, day=1)

        customers = Customers.objects.filter(batch__category__created_by__company=company)

        total_customers = customers.count()
        customers_today = customers.filter(created__date=today).count()
        customers_this_week = customers.filter(created__date__gte=start_of_week).count()
        customers_this_month = customers.filter(created__date__gte=start_of_month).count()
        customers_this_year = customers.filter(created__date__gte=start_of_year).count()

        registered = customers.filter(password__isnull=False).exclude(password='').count()
        unregistered = customers.filter(password__in=['', None]).count()

        last_12_months_customers = []

        for i in range(12):
            # Calculate the first day of the current month being processed
            first_day_of_month = today.replace(day=1) - timedelta(days=i * 30)
            last_day_of_month = (first_day_of_month.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(
                days=1)

            month_customers = customers.filter(
                created__date__gte=first_day_of_month,
                created__date__lte=last_day_of_month
            ).count()

            last_12_months_customers.append({
                'month': first_day_of_month.strftime('%Y-%m'),
                'count': month_customers
            })

        return {
            'total_customers': total_customers,
            'customers_today': customers_today,
            'customers_this_week': customers_this_week,
            'customers_this_month': customers_this_month,
            'customers_this_year': customers_this_year,
            'registered': registered,
            'unregistered': unregistered,
            'last_12_months_customers': last_12_months_customers
        }
    except Exception as e:
        return {}
