from decimal import Decimal
from django.contrib.auth.models import AbstractUser
from django.db import models
from adminapp.models import AdTemplate

class User(AbstractUser):
    ADMIN = 'Admin'
    USER = 'User'
   
    ROLE_CHOICES = [
        (ADMIN, 'Admin'),
        (USER, 'User'),
    ]

    role = models.CharField(max_length=255, choices=ROLE_CHOICES, default=USER)
    phone = models.CharField(max_length=15, unique=True, null=True,blank=True)
    full_name = models.CharField(max_length=255, null=True,blank=True)

class AdCustomization(models.Model):
    STATUS_CHOICES = [
        ("draft", "Draft"),
        ("submitted", "Submitted"),
    ]
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    template = models.ForeignKey("adminapp.AdTemplate", on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    description = models.TextField()
    color = models.CharField(max_length=7)  # Hex color code
    style = models.CharField(max_length=50)
    image = models.ImageField(upload_to="ads/", null=True, blank=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="draft")
    created_at = models.DateTimeField(auto_now_add=True)

    def _str_(self):
        return f"{self.title} ({self.get_status_display()})"

class Order(models.Model):
    STATUS_CHOICES = [
        ("pending", "Pending"),
        ("processing", "Processing"),
        ("completed", "Completed"),
        ("cancelled", "Cancelled"),
    ]
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ad = models.ForeignKey("AdCustomization", on_delete=models.CASCADE)  # Allow multiple orders per ad
    # Template Details
    template_id = models.IntegerField(blank=True, null=True)  # Store template ID
    template_name = models.CharField(max_length=255, blank=True)  
    template_image = models.ImageField(upload_to='order_templates/', blank=True, null=True)
    template_ad_type = models.CharField(max_length=100, blank=True)
    # Pricing & Charges
    base_price = models.DecimalField(max_digits=10, decimal_places=2)
    making_charges = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    gst_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
    additional_charge = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)  
    total_price = models.DecimalField(max_digits=10, decimal_places=2, editable=False)
    
    # Additional Order Details
    location_link = models.URLField(blank=True, null=True)  
    social_media_platform = models.CharField(max_length=255, blank=True, null=True)  
    ad_completion_date = models.DateField(blank=True, null=True)  
    # Auto-filled billing details
    full_name = models.CharField(max_length=255, blank=True)
    email = models.EmailField(blank=True)
    phone = models.CharField(max_length=15, blank=True)
  
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="pending")

    created_at = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        """Auto-fill billing details from User model & calculate total price"""
        
        # Auto-fill user details if missing
        if not self.full_name:
            self.full_name = self.user.get_full_name() or self.user.username
        if not self.email:
            self.email = self.user.email
        if not self.phone:
            self.phone = getattr(self.user, "phone", "")

        # Fetch template details from AdCustomization
        if self.ad:
            self.template_id = self.ad.template.id  # Store template ID
            self.template_name = self.ad.template.name
            self.template_image = self.ad.template.image
            self.template_ad_type = self.ad.template.ad_type.name if self.ad.template.ad_type else ""

        # Ensure total_price includes all charges
        self.total_price = (
            Decimal(self.base_price) +
            Decimal(self.making_charges) +
            Decimal(self.gst_amount) +
            Decimal(self.additional_charge)
        )

        super().save(*args, **kwargs)

    def __str__(self):
        return f"Order {self.id} - {self.status}"

    def get_order_summary(self):
        """Returns formatted order summary"""
        return {
            "Order ID": self.id,
            "User": self.user.username,
            "Template ID": self.template_id,
            "Template Name": self.template_name,
            "Base Price": self.base_price,
            "Making Charges": self.making_charges,
            "GST Amount": self.gst_amount,
            "Additional Charge": self.additional_charge,
            "Total Price": self.total_price,
            
            "Status": self.status,
            "Location": self.location_link,
            "Social Media Platform": self.social_media_platform,
            "Ad Completion Date": self.ad_completion_date,
            "Ordered On": self.created_at.strftime("%Y-%m-%d %H:%M:%S"),
        }

class Payment(models.Model):
    PAYMENT_STATUS_CHOICES = [
        ("pending", "Pending"),
        ("paid", "Paid"),
        ("refunded", "Refunded"),
    ]

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    order = models.ForeignKey(Order, on_delete=models.CASCADE,related_name='order_payment')  # Link to Order model
    razorpay_order_id = models.CharField(max_length=255, blank=True, null=True)  
    payment_id = models.CharField(max_length=255, blank=True, null=True)
    payment_status = models.CharField(max_length=10, choices=PAYMENT_STATUS_CHOICES, default="pending")
    created_at = models.DateTimeField(auto_now_add=True)

    @property
    def total_price(self):
        """Fetch total price from related Order model."""
        return self.order.total_price

    def __str__(self):
        return f"Payment {self.id} - {self.payment_status}"

class Enquiry(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()
    subject = models.CharField(max_length=255)
    message = models.TextField()
    is_replied = models.BooleanField(default=False)  # Track reply status
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Inquiry from {self.name} - {self.subject}"
  
class Feedback(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    message = models.TextField()
    reply = models.TextField(blank=True, null=True)  # Stores admin reply
    replied = models.BooleanField(default=False)  # New field to track reply status
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Feedback from {self.user.username}"
    

