import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from flask import current_app, render_template

# def send_email(to_email, otp, user_type):
#     try:
#         msg = MIMEMultipart()
#         msg['From'] = current_app.config['EMAIL_USER']
#         msg['To'] = to_email
#         msg['Subject'] = f'{user_type} Email Verification | VRVIDYA'
#         html_content = render_template('email/otp.html', otp=otp)
#         msg.attach(MIMEText(html_content, 'html'))
#         with smtplib.SMTP(current_app.config['EMAIL_HOST'], current_app.config['EMAIL_PORT']) as server:
#             server.starttls()
#             server.login(current_app.config['EMAIL_USER'], current_app.config['EMAIL_PASSWORD'])
#             server.sendmail(msg['From'], msg['To'], msg.as_string())
#         return {'status': True, 'message': 'Email sent successfully'}
#     except Exception as e:
#         print(f"❌ Email sending failed: {e}")
#         return {'status': False, 'message': f'Failed to send email: {str(e)}'}


def send_email(to_email, otp, user_type):
    try:
        print("🔧 Email sending triggered...")
        print("To:", to_email)
        print("Using SMTP Host:", current_app.config['EMAIL_HOST'])
        print("Port:", current_app.config['EMAIL_PORT'])
        print("From:", current_app.config['EMAIL_USER'])

        msg = MIMEMultipart()
        msg['From'] = current_app.config['EMAIL_USER']
        msg['To'] = to_email
        msg['Subject'] = f'{user_type} Email Verification | EduRuby'

        html_content = f"""
        <h2>EduRuby Email Verification</h2>
        <p>Your OTP for email verification is: <strong>{otp}</strong></p>
        <p>Please use this OTP to verify your email address.</p>
        """

        msg.attach(MIMEText(html_content, 'html'))

        print("📨 Connecting to SMTP server...")
        with smtplib.SMTP(current_app.config['EMAIL_HOST'], int(current_app.config['EMAIL_PORT'])) as server:
            server.set_debuglevel(1)  # ← Adds SMTP logs
            server.starttls()
            print("🔐 Logging in to SMTP...")
            print(f"📤 Sending email to {to_email}...")
            server.sendmail(msg['From'], msg['To'], msg.as_string())

        print("✅ Email successfully sent!")
        return {'status': True, 'message': 'Email sent successfully'}
    
    except Exception as e:
        print("❌ Email sending failed:", e)
        return {'status': False, 'message': f'Failed to send email: {str(e)}'}
