from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
import threading

# Import your SiteBranding model
from content.models import SiteBranding 

def _send_email_task(subject, plain_message, from_email, to_email, html_message):
    """The actual work of sending the email."""
    try:
        send_mail(
            subject,
            plain_message,
            from_email,
            [to_email],
            html_message=html_message
        )
    except Exception as e:
        print(f"ERROR in _send_email_task: Could not send email to {to_email}: {e}")

def send_payment_receipt_email(application):
    """
    Renders an HTML template for the receipt and emails it
    to the applicant IN A BACKGROUND THREAD.
    """
    subject = f"Payment Receipt for Your Application - {application.full_name}"
    
    # --- THIS IS THE FIX ---
    # Fetch the brand object
    brand = SiteBranding.objects.filter(is_active=True).first()
    
    # Use the site_name from the brand object, or fall back to settings
    institution_name = brand.site_name if brand and brand.site_name else settings.INSTITUTION_NAME
    
    context = {
        'application': application,
        'full_name': application.full_name,
        'amount_paid': application.fee_total,
        'txn_id': getattr(application, 'payment_txn_id', 'N/A'),
        'paid_at': application.paid_at,
        
        'brand': brand, # Pass the whole brand object
        'institution_name': institution_name, # Pass the corrected name
    }
    # --- END FIX ---

    try:
        html_message = render_to_string('emails/payment_receipt.html', context)
    except Exception as e:
        print(f"ERROR: Could not render email template 'emails/payment_receipt.html': {e}")
        return

    plain_message = strip_tags(html_message)
    from_email = settings.DEFAULT_FROM_EMAIL
    to_email = application.email

    t = threading.Thread(
        target=_send_email_task,
        args=[subject, plain_message, from_email, to_email, html_message]
    )
    t.daemon = True
    t.start()