from django.db import models
from django.core.validators import FileExtensionValidator
from decimal import Decimal 
from django.utils import timezone
from datetime import timedelta
from datetime import datetime, timedelta
from pricing_plan.models import Zone

    # Function to calculate expiration date (current date + 30 days)
def get_expiration_date():
    return timezone.now() + timedelta(days=30)


# Define OTTAggregator Model
class OTTAggregator(models.Model):
    PLATFORM_CHOICES = [
        ('watcho', 'Watcho'),
        ('play_box', 'Play Box'),
        ('hotstar', 'Hotstar'),
        ('ottplay', 'OTTplay'),
        ('tata_play_binge', 'Tata Play Binge'),
    ]

    name = models.CharField(max_length=100, unique=True)  # Name of the aggregator
    code = models.CharField(max_length=50, unique=True)  # Unique code for the aggregator
    order_id = models.IntegerField(default=0, null=True, blank=True)
    status = models.CharField(
        max_length=50, 
        choices=[('active', 'Active'), ('inactive', 'Inactive')], 
        default='active'
    )  # Status can be 'active' or 'inactive'

    play_store_url = models.URLField(null=True, blank=True)
    app_store_url = models.URLField(null=True, blank=True)

    play_store_icon = models.FileField(upload_to='icons/playstore/', null=True, blank=True)
    app_store_icon = models.FileField(upload_to='icons/appstore/', null=True, blank=True)


    def __str__(self):
        return self.name  # Returns the name of the aggregator

    class Meta:
        verbose_name = 'OTT Aggregator'
        verbose_name_plural = 'OTT Aggregators'


# Define the OTT Model
class OTT(models.Model):
    name = models.CharField(max_length=255)
    code = models.CharField(max_length=255, unique=True)  # Ensure the 'code' field is unique
    is_active = models.BooleanField(default=True)
    image = models.ImageField(
        upload_to='ott_images/',
        blank=True,
        null=True,
        validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png', 'gif'])]
    )
    order_id = models.IntegerField(default=0)
    ott_plan = models.ForeignKey('OTTPlan', related_name='ott_plans', on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.name


# OTT Plan group 
class OTTPlanGroup(models.Model):
    name = models.CharField(max_length=100)
    group_code = models.CharField(max_length=50, unique=True, null=True, blank=True)  # New field added
    order_id = models.IntegerField(default=0)
    platform_id = models.ForeignKey(OTTAggregator, on_delete=models.CASCADE)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return f"{self.platform_id.name} - {self.name}"

# Define the OTT Plan Model
class OTTPlan(models.Model):
    PLAN_STATUS_CHOICES = [
        ('active', 'Active'),
        ('inactive', 'Inactive'),
    ]
    

    platform_id = models.ForeignKey(OTTAggregator, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=50, unique=True)  # Ensuring the code is unique for each platform
    status = models.CharField(max_length=10, choices=PLAN_STATUS_CHOICES, default='active')
    # New price field to store the price of the plan
    price = models.DecimalField(
        max_digits=10,  # Total number of digits allowed (e.g., for 99999999.99)
        decimal_places=2,  # Number of decimal places (e.g., for .99 cents)
        default=Decimal('0.00')  # Default price is 0.00 (you can adjust this if needed)
    )

     # New premium plan flag field
    premium_plan_flag = models.BooleanField(default=False)  # False = 0, True = 1
     # New premium plan flag field
    highlighted_plan_flag = models.BooleanField(default=False)  # False = 0, True = 1
     # New premium plan flag field
    flexible_plan_flag = models.BooleanField(default=False)  # False = 0, True = 1

    otts = models.ManyToManyField(OTT, related_name='ott_plans_associated')  # Many-to-many with OTT

    # Linking to the OTTPlanGroup
    plan_group = models.ForeignKey(OTTPlanGroup, null=True, blank=True, on_delete=models.SET_NULL)
    validity_months = models.PositiveIntegerField(default=0)

    def __str__(self):
        return f"{self.platform_id.name} - {self.name}"  # Fix the __str__ method

    def get_active_otts(self):
        return self.otts.filter(is_active=True)  # Get active OTTs related to the plan


# Define the Skylink Plan Model
class SkylinkPlan(models.Model):
    PLAN_STATUS_CHOICES = [
        ('active', 'Active'),
        ('inactive', 'Inactive'),
    ]
    JIOHOTSTAR_CHOICES = [
        ('mobile', 'Mobile'),
        ('super', 'Super'),
        ('unavailable', 'Unavailable'),
    ]


    name = models.CharField(max_length=100)
    code = models.CharField(max_length=50, unique=True)  # Ensuring the plan code is unique
    ott_plans = models.ManyToManyField(OTTPlan)  # Many-to-many relationship with OTTPlans
    status = models.CharField(max_length=10, choices=PLAN_STATUS_CHOICES, default='active')
    amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)

    bandwidth_verified_flag = models.BooleanField(default=False)
    bandwidth = models.CharField(max_length=50, blank=True, null=True)

    jiohotstar_flag = models.CharField(
        max_length=15,
        choices=JIOHOTSTAR_CHOICES,
        default='mobile'
    )

    server_type = models.CharField(
        max_length=50,
        choices=Zone.ServiceType.choices,
        null=True,
        blank=True,
        help_text='Specifies the service type associated with this plan.'
    )


    def __str__(self):
        return self.name


# Define the OTTSubscription Model
class OTTSubscription(models.Model):
    client_id = models.CharField(max_length=255)
    platform_id = models.ForeignKey(OTTAggregator, on_delete=models.CASCADE)  # Us
    plan_id = models.CharField(max_length=255)
    subscription_date = models.DateTimeField(auto_now_add=True)  # Track when the subscription is created

    def __str__(self):
        return f"Subscription for {self.client_id} on {self.platform_id} - Plan {self.plan_id}"


# Define the OTTActivationLog Model
class OTTActivationLog(models.Model):
    BILLING_CYCLE_CHOICES = [
        (1, 'Monthly'),
        (3, 'Quarterly'),
        (6, 'Half-Yearly'),
        (12, 'Yearly'),
    ]


    PAYMENT_GATEWAY_CHOICES = [
        ('razorpay', 'Razorpay'),
        ('cashfree', 'Cashfree'),
        ('manual', 'Manual'),
    ]
    client_id = models.CharField(max_length=255)
    platform_id = models.ForeignKey(OTTAggregator, on_delete=models.CASCADE)  # Us
    plan_id = models.CharField(max_length=255)
    activation_date = models.DateTimeField(auto_now_add=True)  # The date when the activation occurred
    status = models.CharField(max_length=50, default='Success')  # Track status like Success/Failure
    message = models.TextField(blank=True, null=True)  # Optional field for any additional message

    input = models.JSONField(null=True, blank=True)  # Store request data
    response_status = models.IntegerField(null=True, blank=True)  # Store response status
    output = models.JSONField(null=True, blank=True)  # Store response body as JSON
    endpoint = models.CharField(null=True, blank=True, max_length=5000)  # Endpoint used in the request

    # Add the subscription_tiers field here
    subscription_tiers = models.CharField(max_length=50, default='free')

      # 🔹 Payment Gateway
    payment_gateway = models.CharField(
        max_length=50,
        choices=PAYMENT_GATEWAY_CHOICES,
        blank=True,
        null=True
    )

     # Payment details for paid subscriptions
    razorpay_payment_id = models.CharField(max_length=255, blank=True, null=True)
    razorpay_signature = models.CharField(max_length=255, blank=True, null=True)
    razorpay_order_id = models.CharField(max_length=255, blank=True, null=True)
    payment_verified = models.BooleanField(default=False)


     # 🔹 Cashfree
    cashfree_order_id = models.CharField(max_length=255, blank=True, null=True)
    cashfree_payment_id = models.CharField(max_length=255, blank=True, null=True)
    cashfree_payment_session_id = models.CharField(max_length=500, blank=True, null=True)
    cashfree_raw_response = models.JSONField(blank=True, null=True)

    # New field to store the payment amount for paid subscriptions
    payment_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    payment_currency = models.CharField(max_length=10, blank=True, null=True)

       # New field to store the expiration date (current date + 30 days)
    expiration_date = models.DateTimeField(default=get_expiration_date)
    phone_number = models.CharField(max_length=15, blank=True, null=True)


    billing_cycle = models.IntegerField(        
        default=1,
        help_text="Billing cycle in months: 1 (Monthly), 3 (Quarterly), 6 (Half-Yearly), 12 (Yearly)"
    )
    invoice_id = models.CharField(max_length=255, blank=True, null=True)
    billing_from_date = models.DateField(null=True, blank=True)
    billing_to_date = models.DateField(null=True, blank=True)
    invoice_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

      # 🔹 Full Raw Data (future-proof)
    payment_raw_data = models.JSONField(blank=True, null=True)

    def __str__(self):
        return f"Activation Log for {self.client_id} on {self.platform_id} - {self.plan_id}"
    

  
class VerificationCode(models.Model):
    email = models.EmailField(unique=True, blank=True, null=True)
    phone_number = models.CharField(max_length=15, blank=True, null=True)
    code = models.CharField(max_length=6)
    timestamp = models.DateTimeField(default=timezone.now)  # 

    def is_expired(self):
        """Check if the verification code has expired"""
        expiry_time = self.timestamp + timedelta(minutes=10)
        return timezone.now() > expiry_time  #     


class JioHotstarCode(models.Model):
    TYPE_CHOICES = [
        ('mobile', 'Mobile'),
        ('super', 'Super'),
    ]
    
    code = models.CharField(max_length=100, unique=True)
    activated_flag = models.BooleanField(default=False)
    activated_date = models.DateTimeField(null=True, blank=True)
    activated_client_id = models.CharField(max_length=100, null=True, blank=True)
    client_phone_number = models.CharField(max_length=15, null=True, blank=True)
    type = models.CharField(max_length=10, choices=TYPE_CHOICES, default='mobile')    
    
    billing_cycle = models.IntegerField(
        default=1,
        help_text="Billing cycle in months: 1 (Monthly), 3 (Quarterly), 6 (Half-Yearly), 12 (Yearly)"
    )
    invoice_id = models.CharField(max_length=255, blank=True, null=True)
    billing_from_date = models.DateField(null=True, blank=True)
    billing_to_date = models.DateField(null=True, blank=True)
    invoice_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

    expired_date = models.DateField(null=True, blank=True)  
    code_provide_count = models.IntegerField(default=0)  

       # Your existing fields...
    code_provide_count = models.IntegerField(default=1)

    def save(self, *args, **kwargs):
        if self.activated_flag and self.activated_date and not self.expired_date:
            self.expired_date = self.activated_date.date() + timedelta(days=90)
        super().save(*args, **kwargs)

        

    def __str__(self):
        return self.code

    

class IptvRequest(models.Model):
    client_id = models.CharField(max_length=100)
    phone_number = models.CharField(max_length=20)
    requested_at = models.DateTimeField(auto_now_add=True)
    email  = models.EmailField(null=True, blank=True)

    # New fields
    activation_code = models.CharField(max_length=100, blank=True, null=True)
    activated_by = models.CharField(max_length=100, blank=True, null=True)
    reason_not_activated = models.TextField(blank=True, null=True)
    activated_at = models.DateTimeField(default=timezone.now, blank=True, null=True)

    def __str__(self):
        return f"{self.client_id} - {self.requested_at}"
    

class SupportVideo(models.Model):
    title = models.CharField(max_length=255)
    subtitle = models.TextField(blank=True)
    video_file = models.FileField(upload_to='support_videos/', blank=True, null=True)
    youtube_link = models.URLField(blank=True, null=True)
    is_active = models.BooleanField(default=True)
    order_id = models.PositiveIntegerField(default=0)  # New field added here

    def __str__(self):
        return self.title
    

class TVChannel(models.Model):
    name = models.CharField(max_length=255)
    code = models.CharField(max_length=100, unique=True)
    image = models.ImageField(upload_to='tv_images/')
    order_id = models.IntegerField(default=0)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.name






class CashfreePayment(models.Model):
    STATUS_CHOICES = [
        ("Pending", "Pending"),
        ("Paid", "Paid"),
        ("Failed", "Failed"),
    ]

    client_id = models.CharField(max_length=255, default="Unknown Client")
    platform_id = models.ForeignKey(OTTAggregator, on_delete=models.CASCADE, null=True, blank=True)
    plan_id = models.CharField(max_length=255, default="Default Plan")

        # ✅ NEW FIELDS
    customer_email = models.EmailField(blank=True, null=True)
    customer_phone = models.CharField(max_length=15, blank=True, null=True)

    
    order_id = models.CharField(max_length=255, unique=True, default="ORDER_0000")
    payment_session_id = models.CharField(max_length=255, blank=True, null=True, default="")
    payment_id = models.CharField(max_length=255, blank=True, null=True, default="")
    payment_status = models.CharField(max_length=50, choices=STATUS_CHOICES, default="Pending")
    amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    currency = models.CharField(max_length=10, default="INR")
    created_at = models.DateTimeField(auto_now_add=True)
    paid_at = models.DateTimeField(blank=True, null=True, default=None)
    extra_data = models.JSONField(blank=True, null=True, default=dict)  # empty dict by default

    def __str__(self):
        return f"Cashfree Payment: {self.client_id} - {self.plan_id} ({self.payment_status})"




class ManualOTTActivation(models.Model):

    platform = models.ForeignKey(
        OTTAggregator,
        on_delete=models.SET_NULL,
        null=True,
        blank=True
    )

    plan = models.ForeignKey(
        OTTPlan,
        on_delete=models.SET_NULL,
        null=True,
        blank=True
    )


    # Second Plan (Optional)
    platform_2 = models.ForeignKey(OTTAggregator, on_delete=models.SET_NULL, null=True, blank=True, related_name="secondary_platform")
    plan_2 = models.ForeignKey(OTTPlan, on_delete=models.SET_NULL, null=True, blank=True, related_name="secondary_plan")

    phone_number = models.CharField(
        max_length=15,
        null=True,
        blank=True
    )

    first_name = models.CharField(
        max_length=100,
        null=True,
        blank=True
    )

    last_name = models.CharField(
        max_length=100,
        null=True,
        blank=True
    )

    sky_id = models.CharField(
        max_length=100,
        null=True,
        blank=True
    )

    status = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        default="Pending"
    )

    message = models.TextField(
        null=True,
        blank=True
    )

    created_at = models.DateTimeField(
        auto_now_add=True,
        null=True,
        blank=True
    )

    def __str__(self):
        phone = self.phone_number if self.phone_number else "No Phone"
        platform = self.platform.name if self.platform else "No Platform"
        return f"{phone} - {platform}"
