from django.http import JsonResponse
from django.views.decorators.http import require_GET
from .models import Invoice
import datetime

@require_GET
def filtered_invoices(request):
    """
    Фильтрует счета по начальной/конечной дате и имени клиента,
    возвращает JSON с полем "member" как список счетов со всеми полями.
    """
    start_date = request.GET.get('start_date')
    end_date = request.GET.get('end_date')
    client = request.GET.get('client')
    
    qs = Invoice.objects.all()
    
    if start_date:
        try:
            start_date_obj = datetime.datetime.strptime(start_date, "%Y-%m-%d")
            qs = qs.filter(created_at__gte=start_date_obj)
        except ValueError:
            pass

    if end_date:
        try:
            end_date_obj = datetime.datetime.strptime(end_date, "%Y-%m-%d")
            qs = qs.filter(created_at__lte=end_date_obj)
        except ValueError:
            pass

    if client:
        qs = qs.filter(client_name__icontains=client)
    
    invoices = []
    for invoice in qs:
        invoices.append({
            'api_id': invoice.api_id,  # Номер счета (API ID)
            'invoice_type': invoice.invoice_type,
            'created_at': invoice.created_at.strftime('%Y-%m-%d %H:%M:%S') if invoice.created_at else '',
            'closed_at': invoice.closed_at.strftime('%Y-%m-%d %H:%M:%S') if invoice.closed_at else 'Не закрыт!',
            'ext_id': invoice.ext_id,
            'ext_type': invoice.ext_type,
            'client': {
                'name': invoice.client_name,
                'club_card_num': invoice.client_club_card_number,
            },
            'sum': str(invoice.sum),
            'company_number': invoice.company_number,
            'bonus': str(invoice.bonus) if invoice.bonus is not None else '',
            'start_bonus': str(invoice.start_bonus) if invoice.start_bonus is not None else '',
            'deposit_sum': str(invoice.deposit_sum),
            'notes': invoice.notes,
        })

    data = {
         "member": invoices,
         "totalItems": qs.count(),
    }
    return JsonResponse(data)
