
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from tenants.models import Tenant


class VisitorLog(models.Model):
    ip_address = models.GenericIPAddressField()
    user_agent = models.TextField()
    page_visited = models.CharField(max_length=500)
    referrer = models.CharField(max_length=500, blank=True, null=True)
    session_key = models.CharField(max_length=40, blank=True, null=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    is_bot = models.BooleanField(default=False)
    country = models.CharField(max_length=100, blank=True, null=True)
    city = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        db_table = 'analytics_visitor_log'
        ordering = ['-timestamp']

    def __str__(self):
        return f"{self.ip_address} - {self.page_visited} - {self.timestamp}"


class SignupAttempt(models.Model):
    STATUS_CHOICES = [
        ('success', 'Success'),
        ('failed', 'Failed'),
        ('pending', 'Pending'),
    ]

    business_name = models.CharField(max_length=255)
    email = models.EmailField()
    phone = models.CharField(max_length=15)
    owner_name = models.CharField(max_length=255)
    ip_address = models.GenericIPAddressField()
    user_agent = models.TextField()
    status = models.CharField(max_length=20, choices=STATUS_CHOICES)
    error_message = models.TextField(blank=True, null=True)
    tenant = models.ForeignKey(Tenant, on_delete=models.SET_NULL, null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'analytics_signup_attempt'
        ordering = ['-timestamp']

    def __str__(self):
        return f"{self.business_name} - {self.status} - {self.timestamp}"


class ContactSubmission(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()
    message = models.TextField()
    ip_address = models.GenericIPAddressField()
    user_agent = models.TextField()
    is_processed = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'analytics_contact_submission'
        ordering = ['-timestamp']

    def __str__(self):
        return f"{self.name} - {self.email} - {self.timestamp}"


class PageView(models.Model):
    page_path = models.CharField(max_length=500)
    page_title = models.CharField(max_length=255, blank=True, null=True)
    views_count = models.IntegerField(default=0)
    unique_views = models.IntegerField(default=0)
    last_viewed = models.DateTimeField(auto_now=True)
    date = models.DateField(auto_now_add=True)

    class Meta:
        db_table = 'analytics_page_view'
        unique_together = ('page_path', 'date')
        ordering = ['-last_viewed']

    def __str__(self):
        return f"{self.page_path} - {self.views_count} views"
