# core/context_processors.py
from .models import SystemSettings
from .utils import get_current_license


def swiftpos_settings(request):
    """
    Injects global SwiftPOS settings into every template context:
    - currency_symbol, vat_rate, decimal_places for price formatting
    - subscription plan flags for feature gating
    - pos_interface_mode for POS V1/V2 switch
    """
    try:
        settings = SystemSettings.objects.get(pk=1)
    except SystemSettings.DoesNotExist:
        settings = None

    # Plan / license
    license_obj = get_current_license()
    plan = getattr(license_obj, 'plan', None)

    return {
        # Currency
        '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,
        'enable_unlimited_stock': settings.enable_unlimited_stock if settings else False,

        # POS interface mode
        'pos_interface_mode': settings.pos_interface_mode if settings else 'classic',

        # Plan-level feature flags (safe defaults = most restrictive)
        'plan_allow_grid_pos': bool(plan and getattr(plan, 'allow_grid_pos', False)),
        'plan_allow_barcode': bool(plan and getattr(plan, 'allow_barcode_scanner', False)),
        'plan_allow_multi_branch': bool(plan and getattr(plan, 'allow_multi_branch', False)),
        'plan_allow_pnl': bool(plan and getattr(plan, 'allow_pnl_report', False)),
        'plan_allow_audit': bool(plan and getattr(plan, 'allow_audit_log', False)),
        'plan_allow_advanced_reports': bool(plan and getattr(plan, 'allow_advanced_reports', False)),
        'plan_name': plan.name if plan else 'Free',
        'plan_code': plan.code if plan else 'free',
    }
