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

class RSVP(models.Model):
    name = models.CharField(max_length=255, help_text="Name of the guest")
    first_name = models.CharField(max_length=200, help_text="First name of the attendee")
    last_name = models.CharField(max_length=200, null=True, blank=True, help_text="Last name of the attendee")
    email = models.EmailField(unique=True, help_text="Email address of the attendee")
    phone = models.CharField(max_length=20, help_text="Phone number of the attendee")
    ticket_number = models.CharField(max_length=20, unique=True)
    message_sid = models.CharField(max_length=255, blank=True, null=True)
    qr_code = models.ImageField(upload_to='qr_codes/', blank=True, null=True)
    access_card = models.ImageField(upload_to='access/', blank=True, null=True)
    is_sent = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = 'RSVP'
        verbose_name_plural = 'RSVPs'

    def __str__(self):
        return f"{self.first_name} {self.last_name or ''}"

    def save(self, *args, **kwargs):
        if not self.ticket_number:
            import secrets
            import string
            self.ticket_number = ''.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.ticket_number)
            qr.make(fit=True)
            img = qr.make_image(fill='black', back_color='white')
            qr_path = os.path.join(settings.MEDIA_ROOT, 'qr_codes', f'{self.ticket_number}.png')
            os.makedirs(os.path.dirname(qr_path), exist_ok=True)
            img.save(qr_path)
            self.qr_code = f'qr_codes/{self.ticket_number}.png'

            # Generate access card by merging QR with invite template
            invite_path = os.path.join(settings.MEDIA_ROOT, 'card.png')
            qr_code_path = qr_path
            output_path = os.path.join(settings.MEDIA_ROOT, 'access', f'{self.ticket_number}.png')
            merge_qr_with_invite(invite_path, qr_code_path, output_path)
            self.access_card = f'access/{self.ticket_number}.png'
        super().save(*args, **kwargs)

class Accreditation(models.Model):
    rsvp = models.ForeignKey(RSVP, on_delete=models.CASCADE, related_name='accreditations', null=True, blank=True)
    date = models.DateTimeField(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):
        if self.rsvp:
            return f"{self.rsvp.name} - {self.date} {self.time}"
        return f"Accreditation - {self.date} {self.time}"

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

