# storefront/context_processors.py
from catalog.models import SiteSetting, Category

def site_defaults(request):
    # cart count
    cart = request.session.get("cart", {})
    cart_count = sum(cart.values()) if isinstance(cart, dict) else 0

    # site settings (with safe defaults)
    site = {
        "name": "MapleMart",
        "store_title": "MapleMart Grocery",
        "address": [],
        "hours_text": "",
        "newsletter_note": "We never share your email. Demo only.",
    }
    try:
        ss = SiteSetting.objects.first()
        if ss:
            site["name"] = ss.site_name or site["name"]
            site["store_title"] = ss.store_title or site["store_title"]
            addr = []
            if ss.address_line1: addr.append(ss.address_line1)
            if ss.address_line2: addr.append(ss.address_line2)
            city_line = " ".join(x for x in [ss.city, ss.region, ss.postal_code, ss.country] if x)
            if city_line: addr.append(city_line)
            site["address"] = addr
            site["hours_text"] = ss.hours_text or ""
            site["newsletter_note"] = ss.newsletter_note or site["newsletter_note"]
    except Exception:
        pass

    # 6 دسته برای ستون Shop در فوتر
    footer_categories = Category.objects.order_by("name")[:6]

    return {"SITE_NAME": site["name"], "SITE": site, "cart_count": cart_count, "FOOTER_CATEGORIES": footer_categories}
