from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Sum, Count, Avg, Q
from .models import Firma, Fatura, FaturaKalemi
from .forms import FirmaForm, FaturaForm

def home(request):
    """Fatura Yönetimi Gösterge Paneli."""
    toplam_firma = Firma.objects.count()
    toplam_fatura = Fatura.objects.count()
    toplam_harcama = Fatura.objects.aggregate(Sum('genel_toplam'))['genel_toplam__sum'] or 0
    son_faturalar = Fatura.objects.select_related('firma').all().order_by('-olusturulma_tarihi')[:10]

    context = {
        "toplam_firma": toplam_firma,
        "toplam_fatura": toplam_fatura,
        "toplam_harcama": toplam_harcama,
        "son_faturalar": son_faturalar,
        "active_menu": "dashboard"
    }
    return render(request, "core/index.html", context)

def fatura_arsivi(request):
    """Firmalara göre gruplanmış fatura arşivi."""
    firmalar = Firma.objects.annotate(
        fatura_sayisi=Count('faturalar'),
        toplam_tutar=Sum('faturalar__genel_toplam')
    ).order_by('ad')
    
    context = {
        "firmalar": firmalar,
        "active_menu": "archive"
    }
    return render(request, "core/fatura_arsivi.html", context)

def firma_detay(request, pk):
    """Belirli bir firmanın fatura listesi."""
    firma = get_object_or_404(Firma, pk=pk)
    faturalar = firma.faturalar.all().order_by('-tarih')
    
    context = {
        "firma": firma,
        "faturalar": faturalar,
        "active_menu": "archive"
    }
    return render(request, "core/firma_detay.html", context)

def fatura_detay(request, pk):
    """Fatura detay önizleme ve kalemleri."""
    fatura = get_object_or_404(Fatura.objects.select_related('firma'), pk=pk)
    kalemler = fatura.kalemler.all()
    
    context = {
        "fatura": fatura,
        "kalemler": kalemler,
        "active_menu": "archive"
    }
    return render(request, "core/fatura_detay.html", context)

def raporlar(request):
    """İstatistik ve Raporlar."""
    # Aylık harcama trendi
    aylik_harcama = Fatura.objects.values('tarih__month').annotate(
        toplam=Sum('genel_toplam'),
        adet=Count('id')
    ).order_by('tarih__month')
    
    # KDV dağılımı
    kdv_ozet = Fatura.objects.aggregate(
        toplam_kdv=Sum('kdv_toplam'),
        ortalama_kdv=Avg('kdv_toplam')
    )
    
    context = {
        "aylik_harcama": aylik_harcama,
        "kdv_ozet": kdv_ozet,
        "active_menu": "reports"
    }
    return render(request, "core/raporlar.html", context)

def firma_ekle(request):
    if request.method == 'POST':
        form = FirmaForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('fatura_arsivi')
    else:
        form = FirmaForm()
    return render(request, 'core/firma_form.html', {'form': form, 'title': 'Yeni Firma Ekle'})

def fatura_ekle(request):
    firma_id = request.GET.get('firma')
    initial = {}
    if firma_id:
        initial['firma'] = firma_id
        
    if request.method == 'POST':
        form = FaturaForm(request.POST, request.FILES)
        if form.is_valid():
            fatura = form.save()
            return redirect('firma_detay', pk=fatura.firma.pk)
    else:
        form = FaturaForm(initial=initial)
    return render(request, 'core/fatura_form.html', {'form': form, 'title': 'Yeni Fatura Yükle'})

def search(request):
    query = request.GET.get('q', '')
    faturalar = []
    firmalar = []
    if query:
        faturalar = Fatura.objects.filter(
            Q(fatura_no__icontains=query) | 
            Q(firma__ad__icontains=query)
        ).select_related('firma')
        firmalar = Firma.objects.filter(
            Q(ad__icontains=query) | 
            Q(vergi_no__icontains=query)
        )
    
    context = {
        'query': query,
        'faturalar': faturalar,
        'firmalar': firmalar,
    }
    return render(request, 'core/search_results.html', context)

def firma_sil(request, pk):
    firma = get_object_or_404(Firma, pk=pk)
    if request.method == 'POST':
        firma.delete()
        return redirect('fatura_arsivi')
    return render(request, 'core/confirm_delete.html', {'object': firma, 'type': 'Firma'})

def fatura_sil(request, pk):
    fatura = get_object_or_404(Fatura, pk=pk)
    firma_pk = fatura.firma.pk
    if request.method == 'POST':
        fatura.delete()
        return redirect('firma_detay', pk=firma_pk)
    return render(request, 'core/confirm_delete.html', {'object': fatura, 'type': 'Fatura'})