# Create your views here.
from django.shortcuts import render
from django.utils.timezone import now
from .models import Wallet, PromoBanner, QuickAction, ExploreItem, Voucher, ThinBanner
from django.contrib.auth.decorators import login_required
from django.db.models import Sum, Q
from decimal import Decimal, ROUND_HALF_UP
from datetime import date
from payments.models import ExternalWallet, ViralPeWallet, ViralPeWalletUsage
from notifications.models import Notification

def round2(val):
    return Decimal(val or 0).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)

# @login_required
def dashboard_new(request):
    user = request.user

    unread_count = Notification.objects.filter(user=request.user, is_read=False).count()

    promo_banners = PromoBanner.objects.filter(active=True, start_date__lte=now(), end_date__gte=now())
    quick_actions = QuickAction.objects.filter(active=True).order_by('order')[:4]
    explore_items = ExploreItem.objects.filter(active=True).order_by('order')[:8]
    vouchers = Voucher.objects.filter(active=True)
    thin_banners = ThinBanner.objects.filter(active=True)

    # Add absolute URLs
    for item in explore_items:
        item.url = request.build_absolute_uri(item.path)


    # ==========================================
  # External Wallet Balance
    external_wallet_obj = ExternalWallet.objects.filter(user=user).first()
    external_wallet = round2(external_wallet_obj.balance) if external_wallet_obj else Decimal('0.00')

    # ViralPe Wallet Balance
    viralpe_wallet_obj = ViralPeWallet.objects.filter(user=user).first()
    viralpe_wallet = round2(viralpe_wallet_obj.balance) if viralpe_wallet_obj else Decimal('0.00')

    # Combined Wallet Balance (External + ViralPe)
    total_wallet_balance = round2(external_wallet + viralpe_wallet)

    # Common QuerySet for commissions
    commission_qs = ViralPeWalletUsage.objects.filter(
        user=user,
        transaction_type="credit",
        purpose__startswith="Commission:"
    )

    # Today’s Cashback
    today = date.today()
    todays_cashback = round2(
        commission_qs.filter(used_on__date=today).aggregate(total=Sum('amount_used'))['total']
    )

    # Lifetime Cashback
    lifetime_cashback = round2(
        commission_qs.aggregate(total=Sum('amount_used'))['total']
    )

    # Cashback – Only "User share"
    cashback = round2(
        commission_qs.filter(purpose="Commission: User share").aggregate(total=Sum('amount_used'))['total']
    )

    # Referral Earnings
    referral_earnings = round2(
        commission_qs.filter(
            Q(purpose="Commission: Referral share") | Q(purpose="Commission: Vendor Referral share")
        ).aggregate(total=Sum('amount_used'))['total']
    )

    context = {

        'unread_notifications': unread_count,

        'promo_banners': promo_banners,
        'quick_actions': quick_actions,
        'explore_items': explore_items,
        'vouchers': vouchers,
        'thin_banners': thin_banners,

        'external_wallet': external_wallet if external_wallet else 0,
        'viralpe_wallet': viralpe_wallet  if viralpe_wallet else 0,
        'total_wallet_balance': total_wallet_balance,
        'todays_cashback': todays_cashback  if todays_cashback else 0,
        'lifetime_cashback': lifetime_cashback if lifetime_cashback else 0,
        'cashback': cashback if cashback else 0,
        'referral_earnings': referral_earnings if referral_earnings else 0,
    }

    return render(request, "users/homel.html", context)
