from django.db import models
from django.utils import timezone


class EventCategory(models.Model):
    name = models.CharField(max_length=100, unique=True)
    code = models.CharField(max_length=50, unique=True)
    description = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Event Category'
        verbose_name_plural = 'Event Categories'
        ordering = ['name']

    def __str__(self):
        return self.name


class Event(models.Model):
    EVENT_TYPE_CHOICES = [
        ('ALL', 'All Packages (no restriction)'),
        ('CONFERENCE', 'Conference'),
        ('TRAINING', 'Training'),
        ('AGM', 'AGM'),
        ('EXPO', 'Expo'),
        ('GALA', 'Gala Dinner'),
        ('WORKSHOP', 'Workshop'),
    ]

    name = models.CharField(max_length=255)
    category = models.ForeignKey(EventCategory, on_delete=models.SET_NULL, null=True, blank=True, related_name='events')
    event_type = models.CharField(
        max_length=50, choices=EVENT_TYPE_CHOICES, default='ALL',
        help_text='Used for package validation. Members are admitted if their package name contains this keyword (or event_type is ALL).'
    )
    description = models.TextField(blank=True)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
    location = models.CharField(max_length=255, blank=True)
    is_paid = models.BooleanField(default=False)
    amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    is_active = models.BooleanField(default=True)
    is_archived = models.BooleanField(default=False)
    archived_at = models.DateTimeField(null=True, blank=True)
    is_registerable = models.BooleanField(default=False, help_text='Whether public registration is open for this event')
    max_capacity = models.PositiveIntegerField(null=True, blank=True, help_text='Max registrations (null = unlimited)')
    self_checkin_enabled = models.BooleanField(default=False, help_text='Allow members to self-check-in via the public /checkin page')
    self_checkin_lat = models.DecimalField(
        max_digits=9, decimal_places=6, null=True, blank=True,
        help_text='Venue latitude for geofencing (leave blank to use default: Avani Victoria Falls Resort -17.856000)'
    )
    self_checkin_lng = models.DecimalField(
        max_digits=9, decimal_places=6, null=True, blank=True,
        help_text='Venue longitude for geofencing (leave blank to use default: 25.858000)'
    )
    self_checkin_radius_m = models.PositiveIntegerField(
        default=500,
        help_text='Geofence radius in metres. Members outside this radius are blocked.'
    )
    parent_event = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='sub_events', help_text='Parent event for sub-events/sessions')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-start_date']

    def __str__(self):
        return self.name

    def archive(self):
        self.is_archived = True
        self.is_active = False
        self.archived_at = timezone.now()
        self.save(update_fields=['is_archived', 'is_active', 'archived_at'])

    def unarchive(self):
        self.is_archived = False
        self.is_active = True
        self.archived_at = None
        self.save(update_fields=['is_archived', 'is_active', 'archived_at'])

    @property
    def registration_count(self):
        return self.registrations.count()

    @property
    def is_at_capacity(self):
        if self.max_capacity is None:
            return False
        return self.registration_count >= self.max_capacity
