from django.db import models


class PlatformFeatureFlag(models.Model):
    """Admin-controlled on/off switches for user-visible features."""
    BINARY_TREE_DETAILS = 'binary_tree_details_for_users'
    CHAT_ENABLED = 'chat_enabled'
    REGISTRATION_ENABLED = 'registration_enabled'
    LOGIN_ENABLED = 'login_enabled'
    FEATURE_CHOICES = [
        (BINARY_TREE_DETAILS, 'Show binary tree node details to regular users'),
        (CHAT_ENABLED, 'Enable in-system distributor chat globally'),
        (REGISTRATION_ENABLED, 'Allow new user registrations from public web app'),
        (LOGIN_ENABLED, 'Allow user login from public web app'),
    ]

    feature_key = models.CharField(max_length=100, unique=True, choices=FEATURE_CHOICES)
    is_enabled = models.BooleanField(default=False)
    updated_at = models.DateTimeField(auto_now=True)
    updated_by = models.CharField(max_length=255, null=True, blank=True)

    class Meta:
        verbose_name = 'Platform Feature Flag'
        verbose_name_plural = 'Platform Feature Flags'

    def __str__(self):
        return f"{self.feature_key} = {'ON' if self.is_enabled else 'OFF'}"

    @classmethod
    def is_on(cls, key: str) -> bool:
        """Return whether a feature flag is currently enabled."""
        defaults = {
            cls.BINARY_TREE_DETAILS: False,
            cls.CHAT_ENABLED: True,
            cls.REGISTRATION_ENABLED: True,
            cls.LOGIN_ENABLED: True,
        }
        obj = cls.objects.filter(feature_key=key).first()
        return obj.is_enabled if obj else defaults.get(key, False)


class QRConfig(models.Model):
    """
    Stores company payment configuration used during checkout.
    Includes QR, bank transfer, and PhonePe details.
    """
    qr_image = models.ImageField(
        upload_to='qr_codes/',
        null=True,
        blank=True,
        help_text='Company QR code image for payment scanning'
    )
    company_name = models.CharField(
        max_length=255,
        default='TrueWave',
        help_text='Company name associated with the payment configuration'
    )
    is_active = models.BooleanField(
        default=True,
        help_text='Whether this payment configuration is currently active'
    )

    enable_qr_scan = models.BooleanField(default=True)
    enable_bank_transfer = models.BooleanField(default=True)
    enable_phonepe = models.BooleanField(default=False)
    enable_razorpay = models.BooleanField(default=True)

    bank_account_holder_name = models.CharField(max_length=255, null=True, blank=True)
    bank_account_number = models.CharField(max_length=64, null=True, blank=True)
    bank_name = models.CharField(max_length=255, null=True, blank=True)
    bank_ifsc_code = models.CharField(max_length=32, null=True, blank=True)
    bank_branch_name = models.CharField(max_length=255, null=True, blank=True)

    upi_id = models.CharField(max_length=128, null=True, blank=True)
    phonepe_number = models.CharField(max_length=20, null=True, blank=True)
    payment_instructions = models.TextField(null=True, blank=True)

    uploaded_at = models.DateTimeField(
        auto_now_add=True,
        help_text='Timestamp when the QR code was uploaded'
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        help_text='Timestamp when the payment configuration was last updated'
    )
    created_by = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text='Admin user who created this configuration'
    )

    class Meta:
        verbose_name = 'Payment Configuration'
        verbose_name_plural = 'Payment Configurations'
        ordering = ['-uploaded_at']

    def __str__(self):
        return f'Payment Config - {self.company_name} ({"Active" if self.is_active else "Inactive"})'


class Branch(models.Model):
    """Office / branch location for True Wave Marketing."""
    BRANCH_TYPE_CHOICES = [
        ("Head Office", "Head Office"),
        ("Branch", "Branch"),
        ("Franchise", "Franchise"),
    ]

    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    address = models.TextField()
    phone = models.CharField(max_length=30, blank=True, default="")
    email = models.CharField(max_length=255, blank=True, default="")
    branch_type = models.CharField(max_length=30, choices=BRANCH_TYPE_CHOICES, default="Branch")
    working_hours = models.CharField(max_length=100, default="Mon-Sat, 10 AM - 6 PM")
    is_active = models.BooleanField(default=True)
    sort_order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["sort_order", "city"]

    def __str__(self):
        return f"{self.city} ({self.branch_type})"
