from django import template
from django.utils import timezone

from core.models import SystemSettings, License
from inventory.models import Product, ProductCategory
from sales.models import POSOrder
from accounts.models import CustomUser

register = template.Library()


@register.simple_tag
def plan_usage():
    system = SystemSettings.objects.first()
    if not system:
        return {}

    try:
        license_obj = system.license
    except License.DoesNotExist:
        return {}

    plan = license_obj.plan

    today = timezone.now().date()

    products_count = Product.objects.count()
    categories_count = ProductCategory.objects.count()
    today_orders_count = POSOrder.objects.filter(
        created_at__date=today,
        status="completed",
    ).count()
    users_count = CustomUser.objects.filter(is_active=True).exclude(is_superuser=True).count()

    def pct(current, maximum):
        if not maximum or maximum <= 0:
            return None
        return max(0, min(100, int((current / maximum) * 100)))

    return {
        "plan_name": plan.name,
        "plan_code": plan.code,
        "license_active": license_obj.is_active and not license_obj.is_expired,
        "license_expires_at": license_obj.expires_at,

        "max_products": plan.max_products or None,
        "max_categories": plan.max_categories or None,
        "max_orders_per_day": plan.max_orders_per_day or None,
        "max_users": plan.max_users or None,

        "products_count": products_count,
        "categories_count": categories_count,
        "today_orders_count": today_orders_count,
        "users_count": users_count,

        "products_percent": pct(products_count, plan.max_products),
        "categories_percent": pct(categories_count, plan.max_categories),
        "orders_percent": pct(today_orders_count, plan.max_orders_per_day),
        "users_percent": pct(users_count, plan.max_users),

        "allow_barcode_scanner": plan.allow_barcode_scanner,
        "allow_credit_sales": plan.allow_credit_sales,
        "allow_advanced_reports": plan.allow_advanced_reports,
        "allow_multi_branch": getattr(plan, "allow_multi_branch", False),
    }
