from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import random
import string

def generate_membership_id():
    return "PLP" + str(random.randint(100000, 999999))

class Member(models.Model):
    # System fields
    membership_id = models.CharField(max_length=20, unique=True, default=generate_membership_id)
    status = models.CharField(max_length=50, default="under_review") # under_review, membership_issued, rejected
    payment_status = models.CharField(max_length=50, default="unpaid") # unpaid, paid, returned
    pin = models.CharField(max_length=128, blank=True, null=True) # Hashed PIN for tracking auth
    created_at = models.DateTimeField(default=timezone.now)
    expiry_date = models.DateField(null=True, blank=True)
    revoked_date = models.DateField(null=True, blank=True)
    
    # Returns
    returned_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    returned_receipt = models.FileField(upload_to='return_receipts/', blank=True, null=True)

    # Form Fields
    name_nepali = models.CharField(max_length=255, blank=True)
    name_english = models.CharField(max_length=255)
    father_name = models.CharField(max_length=255, blank=True)
    mother_name = models.CharField(max_length=255, blank=True)
    gender = models.CharField(max_length=50, blank=True)
    dob = models.DateField(null=True, blank=True)
    dob_bs = models.CharField(max_length=20, blank=True)
    jaati = models.CharField(max_length=100, blank=True)
    marital = models.CharField(max_length=100, blank=True)
    blood_group = models.CharField(max_length=10, blank=True)
    education = models.CharField(max_length=100, blank=True)
    profession = models.CharField(max_length=100, blank=True)
    organization = models.CharField(max_length=255, blank=True)
    
    # Phones stored as JSON
    phones = models.JSONField(default=list) 
    emails = models.JSONField(default=list, blank=True)
    
    citizenship_no = models.CharField(max_length=100, blank=True)
    citizenship_issued_district = models.CharField(max_length=100, blank=True)
    voter_id = models.CharField(max_length=100, blank=True)
    
    membership_type = models.CharField(max_length=100, blank=True)
    referred_by = models.CharField(max_length=255, blank=True)
    motivation = models.TextField(blank=True)
    
    address = models.JSONField(default=dict)
    
    # Documents & Media
    profile_photo = models.ImageField(upload_to='profiles/', blank=True, null=True)
    profile_photo_approved = models.BooleanField(default=False)
    
    citizenship_document = models.FileField(upload_to='documents/', blank=True, null=True)
    citizenship_approved = models.BooleanField(default=False)
    
    voter_id_document = models.FileField(upload_to='voter_ids/', blank=True, null=True)
    voter_id_approved = models.BooleanField(default=False)
    payment_receipt = models.FileField(upload_to='receipts/', blank=True, null=True)
    
    # Social
    social_media_links = models.JSONField(default=list, blank=True)
    
    # Generated Card
    generated_card = models.ImageField(upload_to='generated_cards/', blank=True, null=True)

    def __str__(self):
        return f"{self.name_english} ({self.membership_id})"

class BankDetail(models.Model):
    bank_name = models.CharField(max_length=255)
    account_name = models.CharField(max_length=255)
    account_number = models.CharField(max_length=100)
    branch = models.CharField(max_length=255)
    qr_code = models.ImageField(upload_to='qrs/', blank=True, null=True)
    is_active = models.BooleanField(default=True)

class CardTemplate(models.Model):
    name = models.CharField(max_length=100, default="Default Template")
    image = models.ImageField(upload_to='templates/')
    admin_signature = models.ImageField(upload_to='signatures/', blank=True, null=True)
    # Coordinates mapping stored as JSON (e.g. {"name": {"x": 100, "y": 200}, "photo": {"x": 50, "y": 50}})
    coordinates = models.JSONField(default=dict)
    is_active = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        if self.is_active:
            CardTemplate.objects.exclude(pk=self.pk).update(is_active=False)
        super().save(*args, **kwargs)

class OTPLog(models.Model):
    phone_number = models.CharField(max_length=20)
    otp_code = models.CharField(max_length=6)
    created_at = models.DateTimeField(auto_now_add=True)
    is_used = models.BooleanField(default=False)

    def __str__(self):
        return f"OTP for {self.phone_number} at {self.created_at}"

class MemberAuditLog(models.Model):
    member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='audit_logs')
    admin_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    action = models.CharField(max_length=255)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.member.membership_id} - {self.action} at {self.timestamp}"
