"""
Monthly Chit Fund screens for both panels.

Admin: full control (chits, months/terms, members, winners, payments).
Staff: chits of their assigned places only; can view and record payments.

Pages
  chit_list        /<panel>/monthlychitfund/
  chit_detail      /<panel>/monthlychitfund/<id>/
  chit_reports     /<panel>/chit_reports/
JSON / actions are listed in NexusApp/urls.py (names start with chit_).
"""
import logging
from datetime import datetime
from decimal import Decimal, InvalidOperation

from django.db import transaction
from django.db.models import Q, Sum
from django.http import Http404, JsonResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from django.views.decorators.http import require_POST

from NexusApp.models import ChitGroup, ChitMember, ChitPayment, ChitTerm, Place
from NexusApp.utils.chit_service import (
    ZERO, add_months, auction_split, chit_queryset_for, chit_state, member_status, month_start,
    paid_map, sync_terms, term_summary,
)
from NexusApp.utils.excel import xlsx_response

logger = logging.getLogger(__name__)
MAX_MONEY = Decimal('999999999999')


# ------------------------------------------------------------------ helpers
def _panel(request):
    return 'staff' if request.path.startswith('/staff/') else 'admin'


def _is_admin(request):
    return _panel(request) == 'admin'


def _err(message, status=400, errors=None):
    return JsonResponse({'status': 'error', 'message': message, 'errors': errors or {}}, status=status)


def _ok(message, **extra):
    return JsonResponse({'status': 'success', 'message': message, **extra})


def _money(raw, allow_zero=False):
    try:
        v = Decimal(str(raw).strip())
    except (InvalidOperation, AttributeError):
        return None
    if not v.is_finite() or v < 0 or (v == 0 and not allow_zero) or v > MAX_MONEY:
        return None
    if v != v.quantize(Decimal('0.01')):
        return None
    return v


def _int(raw, lo=1, hi=1000):
    try:
        v = int(str(raw).strip())
    except (TypeError, ValueError):
        return None
    return v if lo <= v <= hi else None


def _date(raw):
    try:
        return datetime.strptime((raw or '').strip(), '%Y-%m-%d').date()
    except ValueError:
        return None


def _month(raw):
    """'2026-11' or '2026-11-05' -> date(2026, 11, 1)."""
    raw = (raw or '').strip()
    for fmt in ('%Y-%m', '%Y-%m-%d'):
        try:
            return datetime.strptime(raw, fmt).date().replace(day=1)
        except ValueError:
            pass
    return None


def _get_chit(request, chit_id):
    chit = chit_queryset_for(request).filter(pk=chit_id).first()
    if chit is None:
        raise Http404('Chit not found')
    return chit


def _places_for(request):
    if _is_admin(request):
        return Place.objects.order_by('name')
    from NexusApp.utils.staff_scope import staff_places
    return staff_places(request).order_by('name')


def _urls(request):
    ns = _panel(request)
    names = ['chit_list', 'chit_list_data', 'chit_list_export', 'chit_detail_data', 'chit_pay',
             'chit_reports', 'chit_reports_data', 'chit_reports_export']
    if ns == 'admin':
        names += ['chit_new', 'chit_save', 'chit_delete', 'chit_member_save', 'chit_member_delete',
                  'chit_term_save', 'chit_payment_delete', 'chit_auction_preview']
    return {n: reverse(f'{ns}:{n}') for n in names}


def _ctx(request, **extra):
    return {
        'base_template': f'{_panel(request)}panel/base.html',
        'is_admin': _is_admin(request),
        'panel': _panel(request),
        'chit_urls': _urls(request),
        **extra,
    }


STATE_LABEL = {'upcoming': 'Upcoming', 'active': 'Active', 'completed': 'Completed', 'closed': 'Closed'}


def _chit_row(chit, month, today, members_by_chit, terms_by_chit, paid):
    state, current = chit_state(chit, today)
    members = members_by_chit.get(chit.id, [])
    term = next((t for t in terms_by_chit.get(chit.id, []) if t.month == month), None)
    s = term_summary(term, members, paid, today) if term else None
    claimed = sum(1 for t in terms_by_chit.get(chit.id, []) if t.winner_id)
    return {
        'id': chit.id,
        'name': chit.name,
        'chit_value': float(chit.chit_value),
        'total_members': chit.total_members,
        'member_count': len(members),
        'total_months': chit.total_months,
        'monthly_amount': float(chit.monthly_amount),
        'due_day': chit.due_day,
        'place': chit.place.name if chit.place else '-',
        'state': STATE_LABEL[state],
        'current_month': current or 0,
        'progress_pct': int(round((current or 0) * 100 / chit.total_months)) if chit.total_months else 0,
        'claimed_count': claimed,
        'this_month': s,
        'start_month': chit.start_month.strftime('%b %Y'),
        'detail_url': '',
    }


def _load(chits):
    ids = [c.id for c in chits]
    members_by_chit, terms_by_chit = {}, {}
    for m in ChitMember.objects.filter(chit_id__in=ids):
        members_by_chit.setdefault(m.chit_id, []).append(m)
    for t in ChitTerm.objects.filter(chit_id__in=ids).select_related('winner'):
        terms_by_chit.setdefault(t.chit_id, []).append(t)
    paid = paid_map([t.id for ts in terms_by_chit.values() for t in ts])
    return members_by_chit, terms_by_chit, paid


# ------------------------------------------------------------------ list page
def chit_list(request):
    return render(request, 'chit/chit_list.html', _ctx(
        request, this_month=timezone.localdate().strftime('%Y-%m')))


def _list_rows(request):
    today = timezone.localdate()
    month = _month(request.GET.get('month')) or month_start(today)
    status = request.GET.get('status', '').strip()
    search = request.GET.get('search', '').strip().lower()

    chits = list(chit_queryset_for(request))
    members_by_chit, terms_by_chit, paid = _load(chits)
    rows = []
    for chit in chits:
        row = _chit_row(chit, month, today, members_by_chit, terms_by_chit, paid)
        row['detail_url'] = reverse(f'{_panel(request)}:chit_view', args=[chit.id])
        rows.append(row)
    cards = {
        'active': sum(1 for r in rows if r['state'] == 'Active'),
        'due': sum(r['this_month']['due_total'] for r in rows if r['this_month']),
        'collected': sum(r['this_month']['collected'] for r in rows if r['this_month']),
    }
    cards['pending'] = max(cards['due'] - cards['collected'], 0)
    if status:
        rows = [r for r in rows if r['state'] == status]
    if search:
        rows = [r for r in rows if search in r['name'].lower() or search in r['place'].lower()]
    return month, rows, cards


def chit_list_data(request):
    month, rows, cards = _list_rows(request)
    return JsonResponse({'month': month.strftime('%B %Y'), 'cards': cards, 'data': rows})


def chit_list_export(request):
    month, rows, cards = _list_rows(request)
    out = []
    for i, r in enumerate(rows, 1):
        tm = r['this_month'] or {}
        out.append([i, r['name'], r['place'], r['chit_value'], r['member_count'], r['total_months'],
                    r['monthly_amount'], f"{r['current_month']} of {r['total_months']}",
                    tm.get('due_total', 0), tm.get('collected', 0), tm.get('pending', 0),
                    tm.get('winner', ''), r['state']])
    return xlsx_response(
        f"monthly_chits_{month.strftime('%Y_%m')}", 'Monthly Chit Fund',
        ['S.No', 'Chit', 'Place', 'Chit Value', 'Members', 'Months', 'Monthly Amount', 'Progress',
         'Due This Month', 'Collected', 'Pending', 'Winner', 'Status'],
        out, subtitle=month.strftime('%B %Y'),
        totals=['', 'Total', '', '', '', '', '', '', cards['due'], cards['collected'], cards['pending'], '', ''])


# ------------------------------------------------------------------ create / edit / delete chit
def chit_form(request, chit_id=None):
    """Full page: chit details + one row per member + one row per month (due / winner amount)."""
    chit = ChitGroup.objects.filter(pk=chit_id).first() if chit_id else None
    if chit_id and chit is None:
        raise Http404('Chit not found')
    initial = None
    if chit:
        paid_members = set(ChitPayment.objects.filter(term__chit=chit).values_list('member_id', flat=True))
        won = set(ChitTerm.objects.filter(chit=chit, winner__isnull=False).values_list('winner_id', flat=True))
        terms_paid = set(ChitPayment.objects.filter(term__chit=chit).values_list('term_id', flat=True))
        initial = {
            **_chit_json(chit),
            'members': [{'id': m.id, 'ticket_no': m.ticket_no, 'name': m.name, 'phone': m.phone,
                         'address': m.address, 'aadhaar_number': m.aadhaar_number,
                         'locked': m.id in paid_members or m.id in won}
                        for m in chit.members.all()],
            'terms': [{'term_no': t.term_no, 'due_amount': float(t.due_amount),
                       'prize_amount': float(t.prize_amount), 'has_payments': t.id in terms_paid}
                      for t in chit.terms.all()],
        }
    return render(request, 'chit/chit_form.html', _ctx(
        request, chit=chit, initial=initial, places=_places_for(request)))


def _parse_rows(raw):
    import json
    try:
        rows = json.loads(raw or '[]')
    except ValueError:
        return None
    return rows if isinstance(rows, list) else None


@require_POST
def chit_save(request):
    p = request.POST
    chit = None
    if p.get('id', '').strip():
        chit = ChitGroup.objects.filter(pk=_int(p.get('id'), 1, 10 ** 9) or 0).first()
        if chit is None:
            return _err('Chit not found.', 404)

    errors = {}
    name = ' '.join(p.get('name', '').split())
    if not name:
        errors['name'] = 'Chit name is required.'
    elif len(name) > 150:
        errors['name'] = 'Chit name is too long.'
    chit_value = _money(p.get('chit_value'))
    if chit_value is None:
        errors['chit_value'] = 'Enter the chit value.'
    members = _int(p.get('total_members'), 1, 500)
    if members is None:
        errors['total_members'] = 'Members must be between 1 and 500.'
    months = _int(p.get('total_months'), 1, 240)
    if months is None:
        errors['total_months'] = 'Months must be between 1 and 240.'
    monthly = _money(p.get('monthly_amount'))
    if monthly is None:
        errors['monthly_amount'] = 'Enter the monthly amount.'
    start = _month(p.get('start_month'))
    if start is None:
        errors['start_month'] = 'Select the start month.'
    due_day = _int(p.get('due_day'), 1, 31)
    if due_day is None:
        errors['due_day'] = 'Due day must be 1 to 31.'
    commission = _money(p.get('commission_percent', '0') or '0', allow_zero=True)
    if commission is None or commission > 100:
        errors['commission_percent'] = 'Commission must be 0 to 100 %.'
    place = None
    if p.get('place', '').strip():
        place = Place.objects.filter(pk=_int(p.get('place'), 1, 10 ** 9) or 0).first()
        if place is None:
            errors['place'] = 'Select a valid place.'
    status = p.get('status', 'active')
    if status not in dict(ChitGroup.STATUS_CHOICES):
        status = 'active'

    # ---- member rows (optional: blank rows are skipped, members can be added later)
    member_rows = _parse_rows(p.get('members_json'))
    if member_rows is None:
        errors['members'] = 'Member details could not be read.'
        member_rows = []
    clean_members = []
    for i, r in enumerate(member_rows, start=1):
        if not isinstance(r, dict):
            continue
        nm = ' '.join(str(r.get('name', '')).split())[:150]
        ph = str(r.get('phone', '')).strip()
        ad = str(r.get('address', '')).strip()[:255]
        aa = str(r.get('aadhaar_number', '')).strip()
        rid = _int(r.get('id'), 1, 10 ** 9) if r.get('id') else None
        if not (nm or ph or ad or aa) and not rid:
            continue
        if not nm:
            errors.setdefault('members', f'Member {i}: name is required.')
        elif not (ph.isdigit() and len(ph) == 10):
            errors.setdefault('members', f'Member {i} ({nm}): enter a 10-digit phone number.')
        elif aa and not (aa.isdigit() and len(aa) == 12):
            errors.setdefault('members', f'Member {i} ({nm}): Aadhaar must be 12 digits.')
        clean_members.append({'id': rid, 'ticket_no': i, 'name': nm, 'phone': ph, 'address': ad,
                              'aadhaar_number': aa})
    if members is not None and len(clean_members) > members:
        errors['members'] = f'You entered {len(clean_members)} members but the chit has {members}.'

    # ---- month rows: due per member + winner amount for each month
    term_rows = _parse_rows(p.get('terms_json'))
    if term_rows is None:
        errors['terms'] = 'Month amounts could not be read.'
        term_rows = []
    clean_terms = {}
    for r in term_rows:
        if not isinstance(r, dict):
            continue
        n = _int(r.get('term_no'), 1, 240)
        if n is None or (months and n > months):
            continue
        due = _money(r.get('due_amount'), allow_zero=True)
        prize = _money(r.get('prize_amount'), allow_zero=True)
        if due is None:
            errors.setdefault('terms', f'Month {n}: enter a valid due amount.')
        elif prize is None:
            errors.setdefault('terms', f'Month {n}: enter a valid winner amount.')
        else:
            clean_terms[n] = (due, prize)

    if errors:
        return _err(next(iter(errors.values())), errors=errors)

    with transaction.atomic():
        created = chit is None
        chit = chit or ChitGroup()
        chit.name, chit.chit_value, chit.total_members = name, chit_value, members
        chit.total_months, chit.monthly_amount, chit.start_month = months, monthly, start
        chit.due_day, chit.commission_percent = due_day, commission
        chit.place, chit.status, chit.notes = place, status, p.get('notes', '').strip()[:2000]
        chit.save()
        blocked = sync_terms(chit)

        # members: update existing, add new, remove ones left out (if they have no history)
        if p.get('members_json') is not None:
            keep = set()
            existing = {m.id: m for m in chit.members.all()}
            for row in clean_members:
                if row['id'] and row['id'] in existing:
                    keep.add(row['id'])
            for mid, m in existing.items():
                if mid not in keep:
                    if m.payments.exists() or m.won_terms.exists():
                        transaction.set_rollback(True)
                        return _err(f'{m.name} has payments or has won a month, so they cannot be removed.')
                    m.delete()
            # park existing tickets out of the way, then number everyone in row order
            for m in chit.members.all():
                m.ticket_no += 10000
                m.save(update_fields=['ticket_no'])
            for row in clean_members:
                m = existing.get(row['id']) if row['id'] in keep else ChitMember(chit=chit)
                m.ticket_no, m.name, m.phone = row['ticket_no'], row['name'], row['phone']
                m.address, m.aadhaar_number = row['address'], row['aadhaar_number']
                if m.pk is None:
                    m.joined_date = timezone.localdate()
                m.save()

        # month amounts
        for t in chit.terms.all():
            if t.term_no not in clean_terms:
                continue
            due, prize = clean_terms[t.term_no]
            if due < t.due_amount:
                over = (t.payments.values('member_id').annotate(s=Sum('amount')).filter(s__gt=due))
                if over.exists():
                    transaction.set_rollback(True)
                    return _err(f'Month {t.term_no}: some members already paid more than \u20b9{due:,.2f}.')
            if (t.due_amount, t.prize_amount) != (due, prize):
                t.due_amount, t.prize_amount = due, prize
                t.save(update_fields=['due_amount', 'prize_amount'])

    msg = 'Chit created.' if created else 'Chit updated.'
    if blocked:
        msg += f' Months {", ".join(map(str, blocked))} were kept because they have payments or a winner.'
    return _ok(msg, id=chit.id, detail_url=reverse('admin:chit_view', args=[chit.id]))


@require_POST
def chit_delete(request):
    chit = ChitGroup.objects.filter(pk=_int(request.POST.get('id'), 1, 10 ** 9) or 0).first()
    if chit is None:
        return _err('Chit not found.', 404)
    if ChitPayment.objects.filter(term__chit=chit).exists():
        return _err('This chit has payments. Close it instead of deleting (Edit -> Status: Closed).')
    chit.delete()
    return _ok('Chit deleted.')


# ------------------------------------------------------------------ detail page
def chit_detail(request, chit_id):
    chit = _get_chit(request, chit_id)
    return render(request, 'chit/chit_detail.html', _ctx(
        request, chit=chit, today=timezone.localdate(),
        edit_url=reverse('admin:chit_edit', args=[chit.id]) if _is_admin(request) else ''))


def _chit_json(chit):
    return {
        'id': chit.id, 'name': chit.name, 'chit_value': float(chit.chit_value),
        'total_members': chit.total_members, 'total_months': chit.total_months,
        'monthly_amount': float(chit.monthly_amount),
        'start_month': chit.start_month.strftime('%Y-%m'),
        'start_label': chit.start_month.strftime('%b %Y'), 'due_day': chit.due_day,
        'commission_percent': float(chit.commission_percent),
        'place_id': chit.place_id or '', 'place': chit.place.name if chit.place else '-',
        'status': chit.status, 'notes': chit.notes,
    }


def chit_detail_data(request):
    chit = _get_chit(request, _int(request.GET.get('id'), 1, 10 ** 9) or 0)
    today = timezone.localdate()
    members = list(chit.members.all())
    terms = list(chit.terms.select_related('winner'))
    paid = paid_map([t.id for t in terms])
    state, current = chit_state(chit, today)

    term_rows = [term_summary(t, members, paid, today) for t in terms]
    sel = _int(request.GET.get('term'), 1, 10 ** 6)
    if sel is None:
        sel = min(max(current or 1, 1), chit.total_months)
    term = next((t for t in terms if t.term_no == sel), terms[0] if terms else None)

    won = {t.winner_id: t for t in terms if t.winner_id}
    member_rows = []
    for m in members:
        w = won.get(m.id)
        total_paid = sum((paid.get((t.id, m.id), ZERO) for t in terms), ZERO)
        total_due = sum((t.due_amount for t in terms if t.due_date <= today), ZERO)
        p = paid.get((term.id, m.id), ZERO) if term else ZERO
        member_rows.append({
            'id': m.id, 'ticket_no': m.ticket_no, 'name': m.name, 'phone': m.phone,
            'address': m.address, 'aadhaar_number': m.aadhaar_number, 'nominee': m.nominee,
            'joined_date': m.joined_date.isoformat() if m.joined_date else '', 'notes': m.notes,
            'claimed': bool(w),
            'claimed_term': w.term_no if w else None,
            'claimed_month': w.month.strftime('%b %Y') if w else '',
            'claimed_amount': float(w.prize_amount) if w else 0,
            'prize_received': bool(w and w.claimed),
            'term_paid': float(p),
            'term_due': float(term.due_amount) if term else 0,
            'term_status': member_status(p, term.due_amount, term.due_date, today) if term else '-',
            'term_balance': float(max((term.due_amount if term else ZERO) - p, ZERO)),
            'total_paid': float(total_paid),
            'total_pending': float(max(total_due - total_paid, ZERO)),
        })

    payments = []
    if term:
        for pay in term.payments.select_related('member', 'collected_by').order_by('-paid_date', '-id'):
            payments.append({
                'id': pay.id, 'member': f'#{pay.member.ticket_no} {pay.member.name}',
                'amount': float(pay.amount), 'date': pay.paid_date.strftime('%d %b %Y'),
                'method': pay.get_method_display(),
                'collected_by': pay.collected_by.name if pay.collected_by else 'Admin',
            })

    return JsonResponse({
        'chit': _chit_json(chit),
        'state': STATE_LABEL[state], 'current_month': current or 0,
        'claimed_count': len(won), 'member_count': len(members),
        'totals': {
            'collected': float(sum((Decimal(str(t['collected'])) for t in term_rows), ZERO)),
            'due_so_far': float(sum((Decimal(str(t['due_total'])) for t in term_rows if t['is_past'] or t['is_current']), ZERO)),
            'prize_paid': float(sum((t.prize_amount for t in terms if t.claimed), ZERO)),
        },
        'terms': term_rows,
        'selected_term': term_summary(term, members, paid, today) if term else None,
        'members': member_rows,
        'payments': payments,
    })


# ------------------------------------------------------------------ members
@require_POST
def chit_member_save(request):
    p = request.POST
    chit = ChitGroup.objects.filter(pk=_int(p.get('chit_id'), 1, 10 ** 9) or 0).first()
    if chit is None:
        return _err('Chit not found.', 404)
    member = None
    if p.get('id', '').strip():
        member = chit.members.filter(pk=_int(p.get('id'), 1, 10 ** 9) or 0).first()
        if member is None:
            return _err('Member not found.', 404)

    errors = {}
    name = ' '.join(p.get('name', '').split())
    if not name:
        errors['name'] = 'Member name is required.'
    phone = p.get('phone', '').strip()
    if not phone.isdigit() or len(phone) != 10:
        errors['phone'] = 'Enter a 10-digit phone number.'
    aadhaar = p.get('aadhaar_number', '').strip()
    if aadhaar and (not aadhaar.isdigit() or len(aadhaar) != 12):
        errors['aadhaar_number'] = 'Aadhaar must be 12 digits.'
    ticket = _int(p.get('ticket_no'), 1, 500) if p.get('ticket_no', '').strip() else None
    if p.get('ticket_no', '').strip() and ticket is None:
        errors['ticket_no'] = 'Ticket number must be 1 to 500.'
    if member is None and chit.members.count() >= chit.total_members:
        errors['name'] = f'This chit is full ({chit.total_members} members). Increase members in Edit Chit.'
    if ticket is None:
        used = set(chit.members.values_list('ticket_no', flat=True))
        ticket = next(n for n in range(1, 10 ** 4) if n not in used)
    elif chit.members.filter(ticket_no=ticket).exclude(pk=getattr(member, 'pk', None)).exists():
        errors['ticket_no'] = f'Ticket {ticket} is already taken.'
    joined = _date(p.get('joined_date')) if p.get('joined_date', '').strip() else None
    if errors:
        return _err(next(iter(errors.values())), errors=errors)

    member = member or ChitMember(chit=chit)
    member.ticket_no, member.name, member.phone = ticket, name, phone
    member.address = p.get('address', '').strip()[:255]
    member.aadhaar_number, member.nominee = aadhaar, ' '.join(p.get('nominee', '').split())[:150]
    member.joined_date, member.notes = joined, p.get('notes', '').strip()[:255]
    member.save()
    return _ok('Member saved.', id=member.id)


@require_POST
def chit_member_delete(request):
    m = ChitMember.objects.filter(pk=_int(request.POST.get('id'), 1, 10 ** 9) or 0).first()
    if m is None:
        return _err('Member not found.', 404)
    if m.payments.exists() or m.won_terms.exists():
        return _err('This member has payments or has won a month, so they cannot be removed.')
    m.delete()
    return _ok('Member removed.')


# ------------------------------------------------------------------ terms (months)
def chit_auction_preview(request):
    chit = ChitGroup.objects.filter(pk=_int(request.GET.get('chit_id'), 1, 10 ** 9) or 0).first()
    discount = _money(request.GET.get('discount', '0') or '0', allow_zero=True)
    if chit is None or discount is None or discount > chit.chit_value:
        return _err('Enter a valid discount.')
    prize, commission, dividend, due = auction_split(chit, discount)
    return JsonResponse({'prize_amount': float(prize), 'commission_amount': float(commission),
                         'dividend_per_member': float(dividend), 'due_amount': float(due)})


@require_POST
def chit_term_save(request):
    p = request.POST
    term = ChitTerm.objects.select_related('chit').filter(pk=_int(p.get('term_id'), 1, 10 ** 9) or 0).first()
    if term is None:
        return _err('Month not found.', 404)
    chit = term.chit
    errors = {}
    due = _money(p.get('due_amount'), allow_zero=True)
    if due is None:
        errors['due_amount'] = 'Enter the amount each member pays this month.'
    prize = _money(p.get('prize_amount'), allow_zero=True)
    if prize is None:
        errors['prize_amount'] = 'Enter the amount the winner can claim.'
    discount = _money(p.get('bid_discount', '0') or '0', allow_zero=True)
    commission = _money(p.get('commission_amount', '0') or '0', allow_zero=True)
    dividend = _money(p.get('dividend_per_member', '0') or '0', allow_zero=True)
    if None in (discount, commission, dividend):
        errors['bid_discount'] = 'Discount, commission and dividend must be valid amounts.'
    due_date = _date(p.get('due_date')) or term.due_date

    winner = None
    if p.get('winner_id', '').strip():
        winner = chit.members.filter(pk=_int(p.get('winner_id'), 1, 10 ** 9) or 0).first()
        if winner is None:
            errors['winner_id'] = 'Select a member of this chit.'
        elif winner.won_terms.exclude(pk=term.pk).exists():
            other = winner.won_terms.exclude(pk=term.pk).first()
            errors['winner_id'] = f'{winner.name} already won month {other.term_no}. Each member can win only once.'
    claimed = p.get('claimed') in ('1', 'true', 'on', 'yes')
    claimed_date = _date(p.get('claimed_date')) if claimed else None
    if claimed and winner is None:
        errors['claimed'] = 'Select the winner before marking the prize as claimed.'
    if claimed and claimed_date is None:
        claimed_date = timezone.localdate()
    if due is not None and due < term.due_amount:
        over = (ChitPayment.objects.filter(term=term).values('member_id')
                .annotate(s=Sum('amount')).filter(s__gt=due))
        if over.exists():
            errors['due_amount'] = 'Some members already paid more than this amount for the month.'
    if errors:
        return _err(next(iter(errors.values())), errors=errors)

    term.due_amount, term.prize_amount, term.due_date = due, prize, due_date
    term.bid_discount, term.commission_amount, term.dividend_per_member = discount, commission, dividend
    term.winner, term.claimed, term.claimed_date = winner, claimed, claimed_date
    term.notes = p.get('notes', '').strip()[:255]
    term.save()

    # "apply to later months": copy the due / prize to every later month that has no payments
    if p.get('apply_forward') in ('1', 'true', 'on'):
        for t in chit.terms.filter(term_no__gt=term.term_no):
            if not t.payments.exists():
                t.due_amount, t.prize_amount = due, prize
                t.save(update_fields=['due_amount', 'prize_amount'])
    return _ok(f'Month {term.term_no} saved.')


# ------------------------------------------------------------------ payments
@require_POST
def chit_pay(request):
    p = request.POST
    term = ChitTerm.objects.select_related('chit').filter(pk=_int(p.get('term_id'), 1, 10 ** 9) or 0).first()
    if term is None or not chit_queryset_for(request).filter(pk=term.chit_id).exists():
        return _err('Month not found.', 404)
    member = term.chit.members.filter(pk=_int(p.get('member_id'), 1, 10 ** 9) or 0).first()
    if member is None:
        return _err('Member not found.', 404)
    amount = _money(p.get('amount'))
    if amount is None:
        return _err('Enter a valid amount.', errors={'amount': 'Enter a valid amount.'})
    paid_date = _date(p.get('paid_date')) or timezone.localdate()
    if paid_date > timezone.localdate():
        return _err('Payment date cannot be in the future.', errors={'paid_date': 'Future date.'})
    method = p.get('method', 'cash').lower()
    if method not in dict(ChitPayment.METHOD_CHOICES):
        return _err('Select a payment method.')

    with transaction.atomic():
        ChitTerm.objects.select_for_update().get(pk=term.pk)
        paid = term.payments.filter(member=member).aggregate(s=Sum('amount'))['s'] or ZERO
        balance = term.due_amount - paid
        if balance <= 0:
            return _err(f'{member.name} has already paid month {term.term_no}.')
        if amount > balance:
            return _err(f'Amount is more than the balance for this month (₹{balance:,.2f}).',
                        errors={'amount': 'Too much.'})
        ChitPayment.objects.create(
            term=term, member=member, amount=amount, paid_date=paid_date, method=method,
            collected_by=getattr(request, 'staff', None) if _panel(request) == 'staff' else None,
            notes=p.get('notes', '').strip()[:255])
    left = balance - amount
    return _ok('Payment saved.' + (f' Balance for this month ₹{left:,.2f}.' if left > 0 else
                                    ' Month fully paid.'))


@require_POST
def chit_payment_delete(request):
    pay = ChitPayment.objects.filter(pk=_int(request.POST.get('id'), 1, 10 ** 9) or 0).first()
    if pay is None:
        return _err('Payment not found.', 404)
    pay.delete()
    return _ok('Payment removed.')


# ------------------------------------------------------------------ reports
def chit_reports(request):
    today = timezone.localdate()
    return render(request, 'chit/chit_reports.html', _ctx(
        request, chits=chit_queryset_for(request).order_by('name'),
        default_from=add_months(month_start(today), -5).strftime('%Y-%m'),
        default_to=month_start(today).strftime('%Y-%m')))


def _report_rows(request):
    today = timezone.localdate()
    start = _month(request.GET.get('from_month')) or add_months(month_start(today), -5)
    end = _month(request.GET.get('to_month')) or month_start(today)
    if start > end:
        start, end = end, start
    chits = chit_queryset_for(request)
    chit_id = _int(request.GET.get('chit'), 1, 10 ** 9)
    if chit_id:
        chits = chits.filter(pk=chit_id)
    chits = list(chits)
    members_by_chit, terms_by_chit, paid = _load(chits)
    rows = []
    for chit in chits:
        members = members_by_chit.get(chit.id, [])
        for t in terms_by_chit.get(chit.id, []):
            if not (start <= t.month <= end):
                continue
            s = term_summary(t, members, paid, today)
            rows.append({'chit': chit.name, 'chit_id': chit.id, 'place': chit.place.name if chit.place else '-',
                         **s, 'member_count': len(members)})
    rows.sort(key=lambda r: (r['month_iso'], r['chit']))

    by_month = {}
    for r in rows:
        m = by_month.setdefault(r['month_iso'], {'month': r['month'], 'month_iso': r['month_iso'], 'chits': 0,
                                                 'due_total': 0, 'collected': 0, 'pending': 0,
                                                 'prize': 0, 'claimed': 0, 'winners': 0})
        m['chits'] += 1
        m['due_total'] += r['due_total']
        m['collected'] += r['collected']
        m['pending'] += r['pending']
        m['prize'] += r['prize_amount'] if r['winner'] else 0
        m['winners'] += 1 if r['winner'] else 0
        m['claimed'] += 1 if r['claimed'] else 0
    totals = {k: sum(r[k] for r in rows) for k in ('due_total', 'collected', 'pending')}
    totals['prize_claimed'] = sum(r['prize_amount'] for r in rows if r['claimed'])
    return start, end, rows, sorted(by_month.values(), key=lambda m: m['month_iso']), totals


def chit_reports_data(request):
    start, end, rows, months, totals = _report_rows(request)
    return JsonResponse({'from': start.strftime('%b %Y'), 'to': end.strftime('%b %Y'),
                         'rows': rows, 'months': months, 'totals': totals})


def chit_reports_export(request):
    start, end, rows, months, totals = _report_rows(request)
    out = [[i, r['chit'], r['place'], r['month'], r['term_no'], r['due_amount'], r['member_count'],
            r['due_total'], r['collected'], r['pending'], r['paid_members'], r['unpaid_members'],
            r['winner'] or '-', r['prize_amount'], 'Yes' if r['claimed'] else 'No']
           for i, r in enumerate(rows, 1)]
    return xlsx_response(
        f"chit_report_{start.strftime('%Y_%m')}_{end.strftime('%Y_%m')}", 'Chit Fund Report',
        ['S.No', 'Chit', 'Place', 'Month', 'Month No', 'Due / Member', 'Members', 'Due Total',
         'Collected', 'Pending', 'Paid Members', 'Unpaid Members', 'Winner', 'Prize Amount', 'Prize Claimed'],
        out, subtitle=f"{start.strftime('%b %Y')} to {end.strftime('%b %Y')}",
        totals=['', 'Total', '', '', '', '', '', totals['due_total'], totals['collected'], totals['pending'],
                '', '', '', '', ''])
