from django.db import models

class Firma(models.Model):
    ad = models.CharField(max_length=255, verbose_name="Firma Adı")
    vergi_no = models.CharField(max_length=20, unique=True, verbose_name="Vergi No / TC Kimlik No")
    mersis_no = models.CharField(max_length=30, blank=True, null=True, verbose_name="MERSİS No")
    adres = models.TextField(blank=True, null=True, verbose_name="Adres")
    olusturulma_tarihi = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.ad

    class Meta:
        verbose_name = "Firma"
        verbose_name_plural = "Firmalar"

class Fatura(models.Model):
    firma = models.ForeignKey(Firma, on_delete=models.CASCADE, related_name="faturalar", verbose_name="Firma")
    fatura_no = models.CharField(max_length=50, unique=True, verbose_name="Fatura No")
    tarih = models.DateField(verbose_name="Fatura Tarihi")
    ara_toplam = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name="Ara Toplam")
    kdv_toplam = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name="KDV Toplam")
    genel_toplam = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name="Genel Toplam")
    pdf_dosyasi = models.FileField(upload_to="faturalar/%Y/%m/", verbose_name="PDF Dosyası")
    islenmis = models.BooleanField(default=False, verbose_name="İşlendi mi?")
    olusturulma_tarihi = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.fatura_no} - {self.firma.ad}"

    class Meta:
        verbose_name = "Fatura"
        verbose_name_plural = "Faturalar"
        ordering = ['-tarih']

class FaturaKalemi(models.Model):
    fatura = models.ForeignKey(Fatura, on_delete=models.CASCADE, related_name="kalemler", verbose_name="Fatura")
    urun_adi = models.CharField(max_length=255, verbose_name="Ürün Adı")
    adet = models.DecimalField(max_digits=10, decimal_places=2, default=1, verbose_name="Adet")
    birim_fiyat = models.DecimalField(max_digits=12, decimal_places=2, verbose_name="Birim Fiyat")
    kdv_orani = models.DecimalField(max_digits=5, decimal_places=2, default=20, verbose_name="KDV Oranı (%)")
    kdv_tutari = models.DecimalField(max_digits=12, decimal_places=2, verbose_name="KDV Tutarı")
    toplam_tutar = models.DecimalField(max_digits=12, decimal_places=2, verbose_name="Toplam Tutar")

    def __str__(self):
        return f"{self.urun_adi} ({self.fatura.fatura_no})"

    class Meta:
        verbose_name = "Fatura Kalemi"
        verbose_name_plural = "Fatura Kalemleri"
