from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from .models import EmailTemplate, EmailLog  # Import EmailLog
import requests

def send_email_from_template(template_name, to_email, context_data):
    try:
        template = EmailTemplate.objects.get(name=template_name)
    except EmailTemplate.DoesNotExist:
        raise Exception(f"Email template '{template_name}' does not exist.")

    subject = template.subject
    body_text = template.body_text
    body_html = template.body_html

    # Replace ##KEY## placeholders manually
    for key, value in context_data.items():
        subject = subject.replace(f"##{key}##", str(value))
        body_text = body_text.replace(f"##{key}##", str(value))
        body_html = body_html.replace(f"##{key}##", str(value))

    print(f"Sending email to {to_email}")
    print(f"Subject: {subject}")

    # ZeptoMail payload
    payload = {
        "from": {
            "address": settings.ZEPTOMAIL_FROM_EMAIL,  # e.g., "noreply@skylink.net.in"
        },
        "to": [
            {
                "email_address": {
                    "address": to_email,
                    "name": context_data.get('name', '')  # Optional: receiver name
                }
            }
        ],
        "subject": subject,
        "htmlbody": body_html,
        "textbody": body_text,
    }

    headers = {
        'accept': "application/json",
        'content-type': "application/json",
        'authorization': f"Zoho-enczapikey {settings.ZEPTOMAIL_API_KEY}",  # safer to keep key in settings
    }

    try:
        response = requests.post(
            url=settings.ZEPTOMAIL_API_URL,
            json=payload,
            headers=headers
        )
        response_data = response.json()
        print(f"Response from ZeptoMail: {response_data}")
     
        # Save success log
        EmailLog.objects.create(
            to_email=to_email,
            subject=subject,
            body_text=body_text,
            body_html=body_html,
            status='Success',
            template_name=template_name,
        )
        print(f"Email sent successfully to {to_email}")
     

    except Exception as e:
        print(f"Failed to send email: {e}")
        EmailLog.objects.create(
            to_email=to_email,
            subject=subject,
            body_text=body_text,
            body_html=body_html,
            template_name=template_name,
            status='Failed',
            error_message=str(e)
        )