# core/models.py
from django.db import models
from django.utils import timezone

class SystemSettings(models.Model):
    BUSINESS_CURRENCIES = [
        ('NGN', 'Naira (₦)'),
        ('USD', 'Dollar ($)'),
        ('EUR', 'Euro (€)'),
        ('GBP', 'Pound (£)'),
    ]

    POS_INTERFACE_CHOICES = [
        ('classic', 'Classic POS (V1)'),
        ('grid', 'Smart Grid POS (V2)'),
    ]
    
    business_name = models.CharField(max_length=200, default='Modern POS Business')
    business_address = models.TextField(blank=True)
    business_phone = models.CharField(max_length=20, blank=True)
    business_email = models.EmailField(blank=True)
    currency = models.CharField(max_length=3, choices=BUSINESS_CURRENCIES, default='NGN')
    logo = models.ImageField(upload_to='logos/', blank=True, null=True)

    # Activation Barrier
    is_activated = models.BooleanField(default=False)
    activation_code = models.CharField(max_length=50, blank=True)

    # POS Interface Mode
    pos_interface_mode = models.CharField(
        max_length=10,
        choices=POS_INTERFACE_CHOICES,
        default='classic',
        help_text='Which POS interface to use'
    )

    # Currency & Tax
    currency_symbol = models.CharField(
        max_length=5, default='₦',
        help_text='Symbol displayed before prices (e.g. ₦, $, €)'
    )
    decimal_places = models.PositiveSmallIntegerField(
        default=2,
        help_text='Number of decimal places for prices'
    )
    use_comma_separator = models.BooleanField(
        default=True,
        help_text='Use comma as thousands separator (e.g. 1,000.00 vs 1.000,00)'
    )
    vat_rate = models.DecimalField(
        max_digits=5, decimal_places=2, default=0.00,
        help_text='VAT / Tax percentage to apply on orders (0 = disabled)'
    )
    
    # Toggle options
    show_inventory = models.BooleanField(default=True)
    show_receipts = models.BooleanField(default=True)
    show_analytics = models.BooleanField(default=True)
    show_reports = models.BooleanField(default=True)
    enable_sms = models.BooleanField(default=False)
    enable_email = models.BooleanField(default=False)
    enable_camera_scanner = models.BooleanField(default=False, help_text="Enable webcam/phone camera scanning in Barcode POS")
    enable_unlimited_stock = models.BooleanField(default=False, help_text="Treat 0 stock quantity as unlimited (always in stock)")
    
    
    # Theme settings
    primary_color = models.CharField(max_length=7, default='#667eea', help_text='Hex color code')
    secondary_color = models.CharField(max_length=7, default='#764ba2', help_text='Hex color code')
    accent_color = models.CharField(max_length=7, default='#f093fb', help_text='Hex color code')
    
    # Card styling
    card_radius = models.IntegerField(default=20, help_text='Border radius in pixels')
    card_shadow = models.CharField(max_length=50, default='0 10px 30px rgba(0, 0, 0, 0.1)', help_text='CSS shadow value')
    
    # Receipt settings
    receipt_header = models.TextField(blank=True, help_text='Text to appear at top of receipts')
    receipt_footer = models.TextField(blank=True, help_text='Text to appear at bottom of receipts')
    show_receipt_logo = models.BooleanField(default=True)
    
    # Analytics settings
    analytics_refresh_rate = models.IntegerField(default=30, help_text='Refresh rate in seconds')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'System Setting'
        verbose_name_plural = 'System Settings'
    
    def __str__(self):
        return f"{self.business_name} Settings"

class Branch(models.Model):
    """
    A business branch / outlet (for multi-branch setups).
    If subscription does not allow multi-branch, only one branch
    should be created and used as the default.
    """
    name = models.CharField(max_length=150)
    code = models.CharField(max_length=50, unique=True)
    address = models.TextField(blank=True)
    phone = models.CharField(max_length=30, blank=True)
    is_active = models.BooleanField(default=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "Branch"
        verbose_name_plural = "Branches"
        ordering = ["name"]

    def __str__(self):
        return self.name



class FieldCategory(models.Model):
    name = models.CharField(max_length=100, unique=True)
    description = models.TextField(blank=True)
    icon = models.CharField(max_length=50, blank=True, help_text="Font Awesome icon class")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Field Category'
        verbose_name_plural = 'Field Categories'
        ordering = ['name']
    
    def __str__(self):
        return self.name

class CustomField(models.Model):
    FIELD_TYPES = [
        ('text', 'Text'),
        ('number', 'Number'),
        ('email', 'Email'),
        ('phone', 'Phone'),
        ('date', 'Date'),
        ('datetime', 'Date & Time'),
        ('boolean', 'Yes/No'),
        ('dropdown', 'Dropdown'),
        ('textarea', 'Text Area'),
        ('image', 'Image Upload'),
        ('file', 'File Upload'),
        ('currency', 'Currency'),
        ('percentage', 'Percentage'),
    ]
    
    category = models.ForeignKey(FieldCategory, on_delete=models.CASCADE, related_name='fields')
    name = models.CharField(max_length=100)
    field_type = models.CharField(max_length=20, choices=FIELD_TYPES)
    label = models.CharField(max_length=200, help_text="Display label for the field")
    placeholder = models.CharField(max_length=200, blank=True, help_text="Placeholder text")
    help_text = models.TextField(blank=True, help_text="Help text to display")
    required = models.BooleanField(default=False)
    show_on_receipt = models.BooleanField(default=False)
    show_on_reports = models.BooleanField(default=False)
    show_on_pos = models.BooleanField(default=True)
    default_value = models.TextField(blank=True, help_text="Default value for the field")
    validation_rules = models.JSONField(default=dict, blank=True, help_text="Validation rules as JSON")
    order = models.PositiveIntegerField(default=0, help_text="Order in which field appears")
    
    # For dropdown fields
    dropdown_options = models.JSONField(default=list, blank=True, help_text="Dropdown options as JSON array")
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Custom Field'
        verbose_name_plural = 'Custom Fields'
        ordering = ['category', 'order', 'name']
    
    def __str__(self):
        return f"{self.category.name} - {self.name}"
    
    @property
    def is_dropdown(self):
        return self.field_type == 'dropdown'
    
    @property
    def is_required(self):
        return self.required

class FieldValue(models.Model):
    """
    Stores the actual values for custom fields for specific records
    """
    field = models.ForeignKey(CustomField, on_delete=models.CASCADE)
    content_type = models.CharField(max_length=50, help_text="Model name (e.g., 'Product', 'Customer')")
    object_id = models.PositiveIntegerField(help_text="ID of the related object")
    value = models.TextField(help_text="The actual value stored")
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        unique_together = ['field', 'content_type', 'object_id']
        verbose_name = 'Field Value'
        verbose_name_plural = 'Field Values'
    
    def __str__(self):
        return f"{self.field.label}: {self.value}"


class DynamicFormData(models.Model):
    """
    Stores the complete form data for any content type
    """
    content_type = models.CharField(max_length=50, help_text="Model name (e.g., 'Product', 'Customer', 'Sale')")
    object_id = models.PositiveIntegerField(help_text="ID of the related object")
    form_data = models.JSONField(default=dict, help_text="Complete form data as JSON")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        unique_together = ['content_type', 'object_id']
        verbose_name = 'Dynamic Form Data'
        verbose_name_plural = 'Dynamic Form Data'
    
    def __str__(self):
        return f"{self.content_type} - {self.object_id}"

class FormDataEntry(models.Model):
    """
    Individual form data entry for better querying and reporting
    """
    content_type = models.CharField(max_length=50)
    object_id = models.PositiveIntegerField()
    field_name = models.CharField(max_length=100)
    field_value = models.TextField()
    field_type = models.CharField(max_length=20)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        unique_together = ['content_type', 'object_id', 'field_name']
        verbose_name = 'Form Data Entry'
        verbose_name_plural = 'Form Data Entries'
    
    def __str__(self):
        return f"{self.content_type}.{self.field_name} = {self.field_value}"
        
        
class SubscriptionPlan(models.Model):
    name = models.CharField(max_length=50, unique=True)
    code = models.CharField(max_length=50, unique=True)

    max_products = models.PositiveIntegerField(default=0)
    max_categories = models.PositiveIntegerField(default=0)
    max_orders_per_day = models.PositiveIntegerField(default=0)
    max_users = models.PositiveIntegerField(              # 🔹 for user limit
        default=0,
        help_text="0 = unlimited users"
    )

    allow_barcode_scanner = models.BooleanField(
        default=True,
        help_text="Enable barcode scanning in POS"
    )
    allow_credit_sales = models.BooleanField(default=True)
    max_customers = models.PositiveIntegerField(
        default=0,
        help_text="Maximum number of customers allowed. 0 = unlimited."
    )
    allow_dynamic_fields = models.BooleanField(default=True)
    allow_multi_branch = models.BooleanField(
        default=False,
        help_text="Allow multiple store branches/outlets"
    )
    allow_advanced_reports = models.BooleanField(default=False)
    allow_grid_pos = models.BooleanField(
        default=False,
        help_text="Allow Smart Grid POS V2 interface"
    )
    allow_pnl_report = models.BooleanField(
        default=False,
        help_text="Allow access to P&L Report page"
    )
    allow_audit_log = models.BooleanField(
        default=False,
        help_text="Allow access to the full Audit Log"
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

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



class License(models.Model):
    system = models.OneToOneField(SystemSettings, related_name="license", on_delete=models.CASCADE)
    plan = models.ForeignKey(SubscriptionPlan, on_delete=models.PROTECT)
    license_key = models.CharField(max_length=100, unique=True)
    is_active = models.BooleanField(default=True)
    started_at = models.DateField(null=True, blank=True)
    expires_at = models.DateField(null=True, blank=True)

    @property
    def is_expired(self):
        return self.expires_at and self.expires_at < timezone.now().date()


    class Meta:
        verbose_name = "License"
        verbose_name_plural = "Licenses"
    def __str__(self) -> str:
        return f"{self.system.business_name} - {self.plan.name}"


# ─────────────────────────────────────────────────────────────
# PROMO CODE / DISCOUNT
# ─────────────────────────────────────────────────────────────
class PromoCode(models.Model):
    DISCOUNT_TYPES = [
        ('percentage', 'Percentage (%)'),
        ('fixed', 'Fixed Amount'),
    ]

    code = models.CharField(max_length=50, unique=True, help_text="The code a cashier enters at checkout")
    description = models.CharField(max_length=200, blank=True)
    discount_type = models.CharField(max_length=15, choices=DISCOUNT_TYPES, default='percentage')
    discount_value = models.DecimalField(
        max_digits=10, decimal_places=2,
        help_text="10 = 10% off (for percentage) or ₦10 off (for fixed)"
    )
    max_uses = models.PositiveIntegerField(
        default=0, help_text="Maximum number of times this code can be used. 0 = unlimited."
    )
    current_uses = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)
    expires_at = models.DateField(null=True, blank=True, help_text="Leave blank for no expiry")
    minimum_order_amount = models.DecimalField(
        max_digits=10, decimal_places=2, default=0,
        help_text="Minimum order total for this promo to apply. 0 = no minimum."
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Promo Code'
        verbose_name_plural = 'Promo Codes'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.code} ({self.get_discount_type_display()}: {self.discount_value})"

    @property
    def is_exhausted(self):
        return self.max_uses > 0 and self.current_uses >= self.max_uses

    @property
    def is_expired(self):
        if not self.expires_at:
            return False
        return self.expires_at < timezone.now().date()

    @property
    def is_valid(self):
        return self.is_active and not self.is_expired and not self.is_exhausted

    def calculate_discount(self, order_total):
        """Return the discount amount (Decimal) for a given order total."""
        from decimal import Decimal
        total = Decimal(str(order_total))
        if self.discount_type == 'percentage':
            return (self.discount_value / 100) * total
        else:  # fixed
            return min(self.discount_value, total)  # never give more than the total