from django.db import models

# Create your models here.
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import re

#from human_resource.models import StaffProfile

class CompanyProfile(models.Model):
    company_name = models.CharField(max_length=100, default="", blank=True)
    company_serial_number = models.CharField(
        max_length=100, default="", blank=True,unique=True, editable=True)
    company_description = models.CharField(
        max_length=500, default="", blank=True)
    company_postal_address = models.CharField(
        max_length=50, default="", blank=True)
    company_country_location = models.CharField(max_length=50, default="", blank=True)
    company_phone = models.CharField(max_length=30, default="", blank=True)
    currency_choices = [("usd", "USD"), ("gbp", "GBP"), ("eur", "EUR"),
                        ("kes", "KES"), ("not_selected", "Not Selected")]
    company_preferred_currency = models.CharField(
        max_length=30, choices=currency_choices, default="kes")
    company_profile_set = models.BooleanField(default=False)
    company_departments_set = models.BooleanField(default=False)
    company_super_hr_created = models.BooleanField(default=False)
    recycle_bin = models.BooleanField(default=False)
    created_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)

    timestamp = models.DateTimeField(default=timezone.now)

    class Meta:
        # ordering= ("first_name", "last_name",)
        verbose_name = "Company Profile"
        verbose_name_plural = "Company Profiles"

    def save(self, *args, **kwargs):
        if not self.pk:
            self.company_serial_number = re.sub(
                r'[^0-9]', '', self.timestamp.strftime('%Y-%m-%d %H:%M:%S'))
        super().save(*args, **kwargs)

class CompanyBranch(models.Model): #it's this company branch that i will be using to link to other models
    company_profile = models.ForeignKey(
        CompanyProfile, null=True, on_delete=models.CASCADE, related_name="company_branches")
    branch_name = models.CharField(
        max_length=100, default="", blank=True)
    branch_description = models.CharField(
        max_length=500, default="", blank=True)
    branch_county_location = models.CharField(max_length=30, default="", blank=True)
    branch_phone = models.CharField(max_length=30, default="", blank=True)
    branch_active = models.BooleanField(default=True)
    main_branch = models.BooleanField(default=False)
    # mpesa payment details
    branch_mpesa_consumer_key = models.CharField(
        max_length=150, null=True, default="", blank=True)
    branch_mpesa_consumer_secret = models.CharField(
        max_length=150, null=True, default="", blank=True)
    branch_mpesa_business_short_code = models.CharField(
        max_length=50, null=True, default="", blank=True)
    branch_mpesa_password = models.CharField(
        max_length=150, null=True, default="", blank=True)
    recycle_bin = models.BooleanField(default=False)
    created_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        # ordering= ("first_name", "last_name",)
        verbose_name = "Company Branch"
        verbose_name_plural = "Company Branches"

class CompanyDepartment(models.Model):
    company_profile = models.ForeignKey(
        CompanyProfile, null=True, on_delete=models.CASCADE,related_name="company_departments")
    department_choices = [("system_and_administration", "System and Administration"), ("procurement", "Procurement"), ("human_resource_management", "Human Resource Management"),
                          ("warehouse_management", "Warehouse Management"), ("marketing", "Marketing"),("sales","Sales"), ("finance_and_accounting", "Finance and Accounting"), ("management", "Management"), ("not_selected", "Not Selected")]
    department_name = models.CharField(max_length=100,choices=department_choices, default="not_selected", unique=True)
    department_description = models.CharField(
        max_length=500, default="", blank=True)
    recycle_bin = models.BooleanField(default=False)
    created_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        # ordering= ("first_name", "last_name",)
        verbose_name = "Company Department"
        verbose_name_plural = "Company Departments"

# model to store whether a system administrator account has been created or not


class SystemAdminCreationStatus(models.Model):#there is to be only one system admin for the whole system
    # when admin account is deleted, the record is deleted
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company_profile = models.OneToOneField(
        CompanyProfile, null=True, on_delete=models.CASCADE)
    systemAdminCreated = models.BooleanField(default=False)
    created_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)


class CompanyEmailSettings(models.Model):
    """Per-company SMTP and notification toggles (managed in System Admin)."""
    company_profile = models.OneToOneField(
        CompanyProfile,
        on_delete=models.CASCADE,
        related_name='email_settings',
    )
    smtp_host = models.CharField(max_length=255, default='smtp.gmail.com', blank=True)
    smtp_port = models.PositiveIntegerField(default=587)
    smtp_use_tls = models.BooleanField(default=True)
    smtp_use_ssl = models.BooleanField(default=False)
    smtp_username = models.CharField(max_length=255, blank=True, default='')
    smtp_password = models.CharField(max_length=255, blank=True, default='')
    default_from_email = models.EmailField(
        max_length=255, default='hr@megawattenergiesltd.com', blank=True)
    signup_from_email = models.EmailField(
        max_length=255, default='hr@megawattenergiesltd.com', blank=True)
    agent_signup_from_email = models.EmailField(
        max_length=255, default='crm_reg@megawattenergiesltd.com', blank=True)
    enable_error_notifications = models.BooleanField(default=False)
    enable_general_notifications = models.BooleanField(default=False)
    enable_signup_notifications = models.BooleanField(default=False)
    enable_attachment_emails = models.BooleanField(default=False)
    enable_marketing_emails = models.BooleanField(default=False)
    marketing_from_email = models.EmailField(
        max_length=255, default='', blank=True)
    error_notification_recipients = models.TextField(
        blank=True,
        default='',
        help_text='Comma-separated email addresses for system error alerts.',
    )
    created_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Company Email Settings'
        verbose_name_plural = 'Company Email Settings'

    def __str__(self):
        return f'Email settings — {self.company_profile.company_name}'


class CompanySecuritySettings(models.Model):
    """Per-company access controls: IP whitelist and login OTP."""
    company_profile = models.OneToOneField(
        CompanyProfile,
        on_delete=models.CASCADE,
        related_name='security_settings',
    )
    enable_ip_whitelist = models.BooleanField(default=False)
    allowed_ips = models.TextField(
        blank=True,
        default='',
        help_text='Comma or newline separated IPv4/IPv6 addresses or CIDR ranges.',
    )
    enable_login_otp = models.BooleanField(default=False)
    otp_length = models.PositiveSmallIntegerField(default=6)
    otp_ttl_minutes = models.PositiveSmallIntegerField(default=10)
    otp_max_attempts = models.PositiveSmallIntegerField(default=5)
    created_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Company Security Settings'
        verbose_name_plural = 'Company Security Settings'

    def __str__(self):
        return f'Security settings — {self.company_profile.company_name}'


class LoginOtpChallenge(models.Model):
    challenge_id = models.CharField(max_length=64, unique=True, db_index=True)
    staff_profile = models.ForeignKey(
        'human_resource.StaffProfile',
        on_delete=models.CASCADE,
        related_name='login_otp_challenges',
    )
    otp_hash = models.CharField(max_length=128)
    attempts = models.PositiveSmallIntegerField(default=0)
    expires_at = models.DateTimeField()
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Login OTP Challenge'
        verbose_name_plural = 'Login OTP Challenges'


class CompanySmsSettings(models.Model):
    """Per-company Africa's Talking SMS credentials (managed in System Admin)."""
    company_profile = models.OneToOneField(
        CompanyProfile,
        on_delete=models.CASCADE,
        related_name='sms_settings',
    )
    at_username = models.CharField(max_length=200, blank=True, default='')
    at_api_key = models.TextField(blank=True, default='')
    at_sender_id = models.CharField(max_length=50, blank=True, default='')
    created_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Company SMS Settings'
        verbose_name_plural = 'Company SMS Settings'

    def __str__(self):
        return f'SMS settings — {self.company_profile.company_name}'


class CompanyIntegrationSettings(models.Model):
    """Per-company external integration endpoints (DB-managed via System Admin).

    Replaces config-file values for the CRM performance webhook so the URL/secret
    can be changed at runtime without redeploying.
    """
    company_profile = models.OneToOneField(
        CompanyProfile,
        on_delete=models.CASCADE,
        related_name='integration_settings',
    )
    crm_performance_webhook_url = models.CharField(max_length=500, blank=True, default='')
    # Inbound stock-quantity broadcast endpoint on the CRM (ERP -> CRM). Shares
    # the same secret / active flag as the performance webhook (same trust boundary).
    crm_stock_webhook_url = models.CharField(max_length=500, blank=True, default='')
    crm_quotation_webhook_url = models.CharField(max_length=500, blank=True, default='')
    crm_webhook_secret = models.CharField(max_length=200, blank=True, default='')
    crm_webhook_active = models.BooleanField(default=False)
    # Public URLs for cPanel subdomains (System Admin — no config file redeploy).
    erp_ui_public_url = models.CharField(max_length=500, blank=True, default='')
    erp_api_public_url = models.CharField(max_length=500, blank=True, default='')
    allowed_hosts = models.TextField(blank=True, default='')
    created_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Company Integration Settings'
        verbose_name_plural = 'Company Integration Settings'

    def __str__(self):
        return f'Integration settings — {self.company_profile.company_name}'

# class VersionUpdate(models.Model):
#     version_number = models.CharField(
#         max_length=10, default="", blank=True)
#     version_url_path = models.CharField(
#         max_length=200, default="", blank=True)
#     created_on = models.DateTimeField(auto_now_add=True)
#     last_updated_on = models.DateTimeField(auto_now=True)





    
