o
    hZ                     @   s   d dl Z d dlZd dlmZmZmZmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZ d dlmZmZ d d	lmZmZ d d
lmZ d dlmZ ddlmZmZ d dlmZm Z  e !e"Z#G dd dZ$e$ Z%dS )    N)TupleDictAnyOptional)MIMEText)MIMEMultipart)MIMEBase)encoders)settings)get_connectionEmailMultiAlternatives)TemplateContext)timezone)transaction   )EmailLogNotificationTemplate)SystemSettingsCompanyProfilec                   @   sl  e Zd ZdZdd Zdeeef fddZde	e
 fddZdeeef fd	d
Zd)deeef deeef fddZdedeeef defddZdededeeef defddZ		d*dedededededefddZ			d+dedededededeeef d edeeef fd!d"Zdeeef fd#d$Zd)dedeeef fd%d&Zdeeef fd'd(ZdS ),EmailServicezEEnhanced email service with complete settings integration and loggingc                 C   s    |   | _|  | _|   d S N)_load_email_settingsemail_settings_load_company_profilecompany_profile_validate_settingsself r   ;/var/www/html/optinet_system/notifications/email_service.py__init__   s   

zEmailService.__init__returnc           	   
   C   sL  t tddt tddt tddt tddt tdd	t td
dt tdddd}z]tjjdd}i }|D ]4}|j }|j}|dv rYzt|}W n t	t
fyX   ||d}Y nw |dv rc| dv }|||< q3i ||}td|d  d|d  d|d   |W S  ty } ztd|  td |W  Y d}~S d}~ww )z<Load email settings from SystemSettings model with fallbacks
EMAIL_HOSTzmail.optinet.co.ke
EMAIL_PORTK  EMAIL_HOST_USER EMAIL_HOST_PASSWORDEMAIL_USE_TLSTEMAIL_USE_SSLFDEFAULT_FROM_EMAILznoreply@optinet.co.ke   )HOSTPORT	HOST_USERHOST_PASSWORDUSE_TLSUSE_SSLr+   TIMEOUTemail)category)r.   r3   )r1   r2   )true1yesonzEmail settings loaded: HOST=r-   z, PORT=r.   z
, USE_TLS=r1   z,Error loading email settings from database: z1Using default email settings from Django settingsN)getattrr
   r   objectsfilterkeyuppervalueint
ValueError	TypeErrorgetlowerloggerinfo	Exceptionerror)	r   default_settingsr   db_settingssettingr=   r?   final_settingser   r   r    r      sB   








(
z!EmailService._load_email_settingsc              
   C   sD   zt j W S  ty! } ztd|  W Y d}~dS d}~ww )z(Load company profile for email templateszError loading company profile: N)r   r;   firstrG   rE   rH   )r   rM   r   r   r    r   G   s   z"EmailService._load_company_profilec                 C   s   g }| j ds|d | j ds|d | j ds#|d | j dd}t|tr3|d	kr8|d
 |rKd|}td|  d|fS dS )zValidate email configurationr-   zSMTP host is requiredr/   zSMTP username/email is requiredr0   zSMTP password is requiredr.   r%   r   zValid SMTP port is requiredz; z"Email settings validation failed: F)TzSettings valid)r   rC   append
isinstancer@   joinrE   rH   )r   errorsport	error_msgr   r   r    r   O   s   




zEmailService._validate_settingsNextra_contextc              
   C   s   dddddt  jt  dt  dd}| jr<|| jjp$|d | jjp)d| jjp.d| jj	p3d| jj
p8dd |rC|| |S )z:Get template context with company info and extra variablesOptiNet Solutionsr'   z%Y-%m-%d%Y-%m-%d %H:%M:%S)company_namecompany_emailcompany_phonecompany_websitecompany_addresscurrent_yearcurrent_datecurrent_datetimerX   )rX   rY   rZ   r[   r\   )r   nowyearstrftimer   updaterX   r4   phonewebsiteaddress)r   rU   contextr   r   r    _get_template_contextg   s(   




z"EmailService._get_template_contexttemplate_stringrg   c              
   C   sV   zt |}t|}||W S  ty* } ztd|  |W  Y d}~S d}~ww )z*Render Django template string with contextzError rendering template: N)r   r   renderrG   rE   rH   )r   ri   rg   templatedjango_contextrM   r   r   r    _render_template   s   zEmailService._render_templatesubjectplain_contentc                 C   s   |  ||}|dd}d| d|dd d| d|dd d	|d
r/d|d
 dnd d|dr@d|d dnd d|drQd|d dnd d|d d|dd d}|S )z&Create professional HTML email content
z<br>z
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>a	  </title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background-color: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .email-header {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .email-header h1 {
            margin: 0;
            font-size: 24px;
            font-weight: 600;
        }
        .email-body {
            padding: 30px;
        }
        .email-content {
            margin-bottom: 20px;
        }
        .button {
            display: inline-block;
            background-color: #007bff;
            color: white;
            padding: 12px 24px;
            text-decoration: none;
            border-radius: 5px;
            font-weight: 500;
            margin: 10px 0;
        }
        .button:hover {
            background-color: #0056b3;
        }
        .info-box {
            background-color: #e7f3ff;
            border-left: 4px solid #007bff;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }
        .success-box {
            background-color: #d4edda;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }
        .warning-box {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }
        .email-footer {
            background-color: #f8f9fa;
            padding: 20px 30px;
            text-align: center;
            color: #6c757d;
            font-size: 14px;
            border-top: 1px solid #e9ecef;
        }
        .footer-info {
            margin: 5px 0;
        }
        .disclaimer {
            margin-top: 15px;
            font-size: 12px;
            color: #999;
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <h1>rX   rV   zn</h1>
        </div>
        <div class="email-body">
            <div class="email-content">
                zs
            </div>
        </div>
        <div class="email-footer">
            <div class="footer-info"><strong>z</strong></div>
            rY   z <div class="footer-info">Email: z</div>r'   z
            rZ   z <div class="footer-info">Phone: r[   z"<div class="footer-info">Website: z-
            <div class="footer-info">&copy; r]    z. All rights reserved.</div>
            <div class="disclaimer">
                This is an automated email. Please do not reply to this message.
            </div>
        </div>
    </div>
</body>
</html>
        )rm   replacerC   )r   rn   ro   rg   rendered_contenthtml_contenthtml_templater   r   r    _create_html_email_content   s,   
`d
hijkl
lvz'EmailService._create_html_email_contentgeneralr'   recipient_emailcontent
email_typerecipient_namec                 K   s:   t jj||||||d|d|d|d|ddS )zCreate email log entrypendingcustomer_idemployee_id
invoice_id
payment_id)rx   r{   rn   messagerz   sent_bystatusr}   r~   r   r   )r   r;   createrC   )r   rx   rn   ry   rz   r{   r   kwargsr   r   r    _create_email_log  s   zEmailService._create_email_logcontext_datatemplate_typec	                 K   s  |du ri }|r.zt jj|dd}
|
jp|}|
j}W n t jy-   td| d Y nw | |}| 	||}| 	||}| j
d5||||||d|	}z|  \}}|sid|_d| |_|  d	|fW S | |||}| jd
 }| jdd	}| jdd}d| jv rt| jd }|rd	nt| jdd	}n2d| jv rt| jd }|rd	nd	}n|dkrd}d	}n|dkrd	}d}n|dkrd	}d	}nd	}d}t| jd || jd | jd ||| jddd	d}t||| jd|g|d}||d | }|rd|_|  td| d|  W dS d|_d|_|  W dS  tjyZ } z'dt| d }d|_||_|  td!| d"|  d	|fW  Y d}~S d}~w tjy } z+d#| jd  d$| jd
  d%}d|_||_|  td&|  d	|fW  Y d}~S d}~w ty } zMt| }d'|v sd(|v rd)t| d*}td+| jd
  d,| d-|  nd.t| }d|_||_|  td/|  d	|fW  Y d}~S d}~w tjy } z&d0| d1t| }d|_||_|  td2|  d	|fW  Y d}~S d}~w tjyN } z#d3t| }d|_||_|  td4|  d	|fW  Y d}~S d}~ww )6z8Send email with comprehensive error handling and loggingNT)r   	is_activez	Template z" not found, using provided contentrx   rn   ry   rz   r{   r   failedzSettings validation failed: Fr.   r2   r1     r%      r-   r/   r0   r3   r,   hostrS   usernamepassworduse_tlsuse_ssltimeoutfail_silentlyr+   )rn   body
from_emailto
connectionz	text/htmlsentzEmail sent successfully to z with subject: )TzEmail sent successfullyz4Email send returned 0 - possible configuration issue)Fz,Email send failed - check SMTP configurationzSMTP Authentication failed: z. Check your email credentials.zSMTP Auth error for : zCannot connect to SMTP server :z. Check host and port.zSMTP Connect error: zwrong version numbersslzSSL/TLS configuration error: zb. Try different SSL/TLS settings or check if the server supports the configured encryption method.z%SSL/TLS configuration error for port z
: use_ssl=z
, use_tls=z Unexpected error sending email: zEmail sending error: z
Recipient z was refused by server: zSMTP Recipients refused: z'SMTP server disconnected unexpectedly: zSMTP Server disconnected: r   ) r   r;   rC   rn   ry   DoesNotExistrE   warningrh   rm   r   r   r   error_messagesaverv   r   boolr   r   attach_alternativesendrF   smtplibSMTPAuthenticationErrorstrrH   SMTPConnectErrorrG   rD   SMTPRecipientsRefusedSMTPServerDisconnected)r   rx   rn   ry   rz   r{   r   r   r   r   rk   full_contextrendered_subjectrs   	email_logsettings_validvalidation_errorrt   rS   r   r   r   email_messageresultrM   rT   	error_strr   r   r    
send_email   s   








	$zEmailService.send_emailc           
      C   sv  | j d }| j d }| j d }| j d }g }|dkr'dddd	ddd
d	g}n3|dkr8dddd	dddd	g}n"|dkrIdddd	dddd	g}ndddd	dddd	ddd
d	g}|D ]\}z;td|d  d| d|  t|||||d |d ddd}|  |  d|d  }t| d|fW   S  ty }	 ztd|d  d|	  W Y d}	~	q\d}	~	ww dS )z:Test SMTP connection with different SSL/TLS configurationsr.   r-   r/   r0   r%   FTz#STARTTLS (recommended for port 587))r   r   desczNo encryptionr   z'Implicit SSL (recommended for port 465)STARTTLSr   zNo encryption (port 25)zImplicit SSLzTesting r   z on r   r   r   
   r   u   ✅ Connection successful with u   ❌ Failed with r   N)FuG   ❌ All SSL/TLS configurations failed. Check your SMTP server settings.)r   rE   rF   r   opencloserG   r   )
r   rS   r   r   r   test_configsconfigr   success_msgrM   r   r   r    test_smtp_connection  sZ   












 
z!EmailService.test_smtp_connectionc                 C   sr   d}dj || jd | jd | jdrdn	| jdrdnd	t d
|r*| ndd}| j|||dd|dS )zSend a comprehensive test emailz=Test Email from {{company_name}} - Configuration VerificationuR  
<div class="success-box">
    <h2>✅ Email Configuration Test Successful!</h2>
    <p>Congratulations! Your email system is working correctly.</p>
</div>

<h3>Test Details:</h3>
<div class="info-box">
    <ul>
        <li><strong>Recipient:</strong> {recipient_email}</li>
        <li><strong>SMTP Server:</strong> {smtp_host}:{smtp_port}</li>
        <li><strong>Encryption:</strong> {encryption_type}</li>
        <li><strong>Test Time:</strong> {test_time}</li>
        <li><strong>Sent By:</strong> {sent_by_name}</li>
    </ul>
</div>

<h3>System Information:</h3>
<p>Your {{{{company_name}}}} management system is successfully configured to send emails through your custom SMTP server.</p>

<div class="info-box">
    <h4>What this means:</h4>
    <ul>
        <li>Invoice notifications will be delivered</li>
        <li>Payment confirmations will be sent</li>
        <li>Password reset emails will work</li>
        <li>System notifications are operational</li>
    </ul>
</div>

<p>If you have any questions about your email configuration, please contact your system administrator.</p>
        r-   r.   r1   TLSr2   SSLNonerW   zSystem Administrator)rx   	smtp_host	smtp_portencryption_type	test_timesent_by_name
test_emailz	Test Userr   )formatr   rC   r   r`   rb   get_full_namer   )r   rx   r   rn   ry   r   r   r    send_test_email  s$   "(zEmailService.send_test_emailc                 C   sP   t jjdd t jjdd t jjdd t jjdt  d dS )zGet email statisticsr   )r   r   r|   )r   sent_at__date)
total_senttotal_failedtotal_pending
today_sent)r   r;   r<   countr   r`   dater   r   r   r    get_email_stats;  s   
zEmailService.get_email_statsr   )rw   r'   N)rw   r'   NNN)__name__
__module____qualname____doc__r!   r   r   r   r   r   r   r   r   r   r   rh   rm   rv   r   r   r   r   r   r@   r   r   r   r   r    r      sJ    ,$"
 



 *=5r   )&loggingr   typingr   r   r   r   email.mime.textr   email.mime.multipartr   email.mime.baser   r4   r	   django.confr
   django.core.mailr   r   django.templater   r   django.utilsr   	django.dbr   modelsr   r   settings.modelsr   r   	getLoggerr   rE   r   email_servicer   r   r   r    <module>   s*   
    
9