@login_required
def pos(request):
    from .models import CashierSession
    # Check for active session
    active_session = CashierSession.objects.filter(user=request.user, status='active').first()
    if not active_session:
        # Check if user is a cashier (assigned to a counter)
        if hasattr(request.user, 'counter_assignment'):
             messages.warning(request, _("Please open a session to start selling."))
             return redirect('start_session')

    settings = SystemSetting.objects.first()
    products = Product.objects.filter(is_active=True)
    
    if not settings or not settings.allow_zero_stock_sales:
        products = products.filter(stock_quantity__gt=0)

    customers = Customer.objects.all()
    categories = Category.objects.all()
    payment_methods = PaymentMethod.objects.filter(is_active=True)
    
    # Ensure at least Cash exists
    if not payment_methods.exists():
        PaymentMethod.objects.create(name_en="Cash", name_ar="نقدي", is_active=True)
        payment_methods = PaymentMethod.objects.filter(is_active=True)
        
    context = {
        'products': products, 
        'customers': customers, 
        'categories': categories,
        'payment_methods': payment_methods,
        'settings': settings,
        'active_session': active_session
    }
    return render(request, 'core/pos.html', context)
