from content.models import SiteBranding
from types import SimpleNamespace
from django.conf import settings
from .models import SiteBranding  #


def _fallback_brand():
    logo_url = getattr(settings, "INSTITUTION_LOGO_URL", "/static/img/logo.png")
    return SimpleNamespace(
        name=getattr(settings, "INSTITUTION_NAME", ""),
        title=getattr(settings, "INSTITUTION_NAME", ""),
        email=getattr(settings, "INSTITUTION_EMAIL", ""),
        phone=getattr(settings, "INSTITUTION_PHONE", ""),
        logo_url=logo_url,
        logo=SimpleNamespace(url=logo_url),
        is_active=False,
    )

def branding(request):
    brand = (
        SiteBranding.objects.filter(is_active=True)
        .order_by("-updated_at", "-id")
        .first()
        or SiteBranding.objects.order_by("-updated_at", "-id").first()
    )
    if brand is None:
        brand = _fallback_brand()

    # Return both keys so templates using either `BRAND` or `brand` work.
    return {
        "BRAND": brand,
        "brand": brand,  # <- fixes `brand.email` lookups
        "INSTITUTION_NAME": getattr(settings, "INSTITUTION_NAME", ""),
        "INSTITUTION_EMAIL": getattr(settings, "INSTITUTION_EMAIL", ""),
        "INSTITUTION_PHONE": getattr(settings, "INSTITUTION_PHONE", ""),
        "INSTITUTION_LOGO_URL": getattr(settings, "INSTITUTION_LOGO_URL", "/static/img/logo.png"),
    }
    
    
def branding_context(request):
    branding = SiteBranding.objects.filter(is_active=True).first()
    return {'branding': branding}