import os
from django.utils import tree
import qrcode
from django.db import models
from django.conf import settings

class Invite(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField(unique=False, null=True, blank=True)
    phone = models.CharField(max_length=20, null=True, blank=True)
    organization = models.CharField(max_length=255, null=True, blank=True)
    representative = models.CharField(max_length=100, null=True, blank=True)
    follow_up_org = models.CharField(max_length=20, null=True, blank=True)
    unique_code = models.CharField(max_length=10, unique=True, null=True, blank=True, editable=False)
    qr_code = models.ImageField(upload_to='qrcodes/', blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    is_sent = models.BooleanField(default=False)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return self.name

    
    def save(self, *args, **kwargs):
        if not self.unique_code:
            import secrets
            import string
            self.unique_code = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(9))
            
        if not self.qr_code:
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=10,
                border=1,
            )
            qr.add_data(self.unique_code)
            qr.make(fit=True)
            img = qr.make_image(fill='black', back_color='white')
            qr_path = os.path.join(settings.MEDIA_ROOT, 'qrcodes', f'{self.unique_code}.png')
            os.makedirs(os.path.dirname(qr_path), exist_ok=True)
            img.save(qr_path)
            self.qr_code = f'qrcodes/{self.unique_code}.png'
        super().save(*args, **kwargs)


class Accreditation(models.Model):
    guest = models.ForeignKey(Invite, on_delete=models.CASCADE, related_name='accreditations')
    date = models.DateField(auto_now_add=True, editable=False, blank=False)
    is_accredited = models.BooleanField(default=False)
    time = models.TimeField(auto_now_add=True, editable=False, blank=False)

    def __str__(self):
        return f"{self.guest.name} - {self.date} {self.time}"

    class Meta:
        unique_together = ('guest', 'date')
        ordering = ['-date', '-time']

