from django.db import models 
from django.contrib.auth.hashers import make_password, check_password
import uuid
from django.utils import timezone   

# 🔹 SUPER ADMIN MODEL
class SuperAdmin(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=255)
    
    def save(self, *args, **kwargs):
        if not self.password.startswith('pbkdf2_'):
            self.password = make_password(self.password)
        super().save(*args, **kwargs)

    def check_password(self, raw_password):
        return check_password(raw_password, self.password)

    def __str__(self):
        return self.name


# 🔹 ORGANIZATION MODEL (Created/Managed by SuperAdmin)
class Organization(models.Model):
    super_admin = models.ForeignKey(SuperAdmin, on_delete=models.CASCADE, related_name='organizations')
    org_id = models.CharField(max_length=20, unique=True, editable=False)
    org_name = models.CharField(max_length=150)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=255)
    
    def save(self, *args, **kwargs):
        if not self.org_id:
            self.org_id = str(uuid.uuid4())[:8].upper()
        if not self.password.startswith('pbkdf2_'):
            self.password = make_password(self.password)
        super().save(*args, **kwargs)

    def check_password(self, raw_password):
        return check_password(raw_password, self.password)

    def __str__(self):
        return f"{self.org_name} ({self.org_id})"


# 🔹 ORGANIZATION ADMIN MODEL
class OrgAdmin(models.Model):
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=128)

    def save(self, *args, **kwargs):
        if not self.password.startswith('pbkdf2_'):
            self.password = make_password(self.password)
        super().save(*args, **kwargs)

    def check_password(self, raw_password):
        return check_password(raw_password, self.password)

    def __str__(self):
        return f"{self.name} ({self.organization.org_name})"


# 🔹 PARTICIPANT MODEL
class Participant(models.Model):
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, blank=True, null=True)
    email = models.EmailField()
    hobbies = models.TextField(blank=True, null=True)
    password = models.CharField(max_length=255, blank=True, null=True)
    invite_token = models.CharField(max_length=255, blank=True, null=True)
    invited = models.BooleanField(default=False)          # ✅ Invitation sent
    invite_accepted = models.BooleanField(default=False)  # ✅ Invitation accepted
    is_active = models.BooleanField(default=False)
    assigned_to = models.ForeignKey('self', on_delete=models.SET_NULL, blank=True, null=True)
    invite_created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)  # ✅ Correctly indented

    # 🔹 PROPERTY: check expiry (48 hrs)
    @property
    def is_invite_expired(self):
        from datetime import timedelta
        from django.utils import timezone
        if not self.invite_created_at:
            return False
        return timezone.now() > self.invite_created_at + timedelta(hours=48)

    def __str__(self):
        return f"{self.name or self.email} - {self.organization.org_name}"



# 🔹 GIFT MODEL
class Gift(models.Model):
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
    participant = models.ForeignKey('Participant', on_delete=models.CASCADE)
    gift_name = models.CharField(max_length=150)
    description = models.TextField(blank=True)
    
    def __str__(self):
        return f"{self.gift_name} ({self.participant.name})"


# 🔹 RULES MODEL
class Rules(models.Model):
    org = models.ForeignKey(Organization, on_delete=models.CASCADE)
    content = models.TextField(default="", blank=True)  # <-- IMPORTANT: ensures non-null

# 🔹 SUBSCRIPTION MODEL
class Subscription(models.Model):
    organization = models.OneToOneField('Organization', on_delete=models.CASCADE, related_name='subscription')
    plan_name = models.CharField(max_length=100)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    payment_date = models.DateTimeField(auto_now_add=True)
    transaction_id = models.CharField(max_length=100, unique=True)
    payment_status = models.CharField(max_length=20, default='Pending')  # Paid / Failed / Pending

    def __str__(self):
        return f"{self.organization.org_name} - {self.plan_name} ({self.payment_status})"
