# core/context_processors.py
from django.conf import settings as django_settings


def swiftpos_settings(request):
    """
    Injects per-company settings and plan feature flags into every template context.
    Uses request.company (set by CompanyMiddleware) and request.company.plan.
    """
    company = getattr(request, 'company', None)
    settings = getattr(company, 'settings', None)   # CompanySettings OneToOne
    plan = getattr(company, 'plan', None)

    return {
        # ── Company identity ───────────────────────────────────────
        'company': company,
        'company_slug': company.slug if company else '',
        'company_name': (settings.business_name if settings else '') or (company.name if company else 'SwiftPOS'),

        # ── Currency & display ─────────────────────────────────────
        'currency_symbol': (settings.currency_symbol if settings else '₦'),
        'vat_rate': float(settings.vat_rate) if settings else 0.0,
        'decimal_places': settings.decimal_places if settings else 2,
        'use_comma_separator': settings.use_comma_separator if settings else True,

        # ── POS Interface mode ─────────────────────────────────────
        'pos_interface_mode': (settings.pos_interface_mode if settings else 'classic'),

        # ── Theme colors ───────────────────────────────────────────
        'primary_color': (settings.primary_color if settings else '#667eea'),
        'secondary_color': (settings.secondary_color if settings else '#764ba2'),
        'accent_color': (settings.accent_color if settings else '#f093fb'),

        # ── Module toggles ─────────────────────────────────────────
        'show_inventory': (settings.show_inventory if settings else True),
        'show_receipts': (settings.show_receipts if settings else True),
        'show_analytics': (settings.show_analytics if settings else True),
        'show_reports': (settings.show_reports if settings else True),

        # ── Plan feature flags ─────────────────────────────────────
        'plan_allow_grid_pos':          bool(plan and plan.feature_pos_terminal_v2_grid),
        'plan_allow_barcode':           bool(plan and plan.feature_barcode_pos),
        'plan_allow_multi_branch':      bool(plan and plan.feature_multi_branch),
        'plan_allow_pnl':               bool(plan and plan.feature_profit_loss),
        'plan_allow_audit':             bool(plan and plan.feature_audit_logs),
        'plan_allow_advanced_reports':  bool(plan and plan.feature_advanced_reports),
        'plan_allow_credit_sales':      bool(plan and plan.feature_credit_sales),
        'plan_allow_wholesale':         bool(plan and plan.feature_wholesale_price),
        'plan_allow_promo':             bool(plan and plan.feature_promo),
        'plan_allow_bulk_import':       bool(plan and plan.feature_bulk_import),
        'plan_allow_export':            bool(plan and plan.feature_export),

        # Plan meta
        'plan_name': plan.name if plan else 'Free',

        # ── Global config ─────────────────────────────────────────────
        'whatsapp_number': getattr(django_settings, 'WHATSAPP_NUMBER', ''),
        'max_users': plan.max_staff if plan else 0,

        # ── Analytics badges ───────────────────────────────────────────
        'analytics_unread_insights': _get_unread_insights(company),
        'analytics_unread_notifications': _get_unread_notifications(request, company),
    }


def _get_unread_insights(company):
    if not company:
        return 0
    try:
        from analytics.models import Insight
        return Insight.objects.filter(company=company, is_read=False).count()
    except Exception:
        return 0


def _get_unread_notifications(request, company):
    if not company:
        return 0
    try:
        from analytics.models import Notification
        from django.db.models import Q
        user = getattr(request, 'user', None)
        qs = Notification.objects.filter(company=company, is_read=False)
        if user and user.is_authenticated:
            qs = qs.filter(Q(user=user) | Q(user__isnull=True))
        else:
            qs = qs.filter(user__isnull=True)
        return qs.count()
    except Exception:
        return 0

