Imports System.Net.Mail
Imports System.Configuration
Imports System.Net
Imports System.Net.Security
Imports System.Net.Sockets
Imports System.Security.Authentication
Imports System.Security.Cryptography.X509Certificates
Imports System.Text

Public Class EmailService
   Private Shared ReadOnly SmtpServer As String = ConfigurationManager.AppSettings("SmtpServer")
   Private Shared ReadOnly SmtpPort As Integer = Integer.Parse(ConfigurationManager.AppSettings("SmtpPort"))
   Private Shared ReadOnly SmtpUsername As String = ConfigurationManager.AppSettings("SmtpUsername")
   Private Shared ReadOnly SmtpPassword As String = ConfigurationManager.AppSettings("SmtpPassword")
   Private Shared ReadOnly FromEmail As String = ConfigurationManager.AppSettings("FromEmail")
   Private Shared ReadOnly FromName As String = ConfigurationManager.AppSettings("FromName")

   Public Shared Function SendPasswordResetEmail(toEmail As String, userName As String, password As String, loginUrl As String) As Boolean
      Try
         ' Set global SSL/TLS settings
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
         ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateServerCertificate

         ' Create SmtpClient with host and port in constructor
         Using client As New SmtpClient(SmtpServer, SmtpPort)
            System.Diagnostics.Debug.WriteLine("Configuring SMTP client...")
            client.EnableSsl = True
            client.UseDefaultCredentials = False
            client.Credentials = New System.Net.NetworkCredential(SmtpUsername, SmtpPassword)
            client.Timeout = 60000 ' Increase timeout to 60 seconds

            Using message As New MailMessage()
               message.From = New MailAddress(FromEmail, FromName)
               message.To.Add(toEmail)
               message.Subject = "PERNOD Staff Password"
               message.Body = GetPasswordResetEmailBody(userName, password, loginUrl)
               message.IsBodyHtml = True
               
               If Not String.IsNullOrEmpty(ConfigurationManager.AppSettings("BccEmail")) Then
                  message.Bcc.Add(ConfigurationManager.AppSettings("BccEmail"))
               End If

               System.Diagnostics.Debug.WriteLine("Attempting to send email...")
               client.Send(message)
               System.Diagnostics.Debug.WriteLine("Email sent successfully to: " & toEmail)
               Return True
            End Using
         End Using
      Catch ex As Exception
         System.Diagnostics.Debug.WriteLine("Email Error: " & ex.Message)
         System.Diagnostics.Debug.WriteLine("Stack Trace: " & ex.StackTrace)
         ErrorLogger.Log("EmailService", "PasswordReset", Nothing, ex, toEmail)
         Return False
      End Try
   End Function

   Private Shared Function ValidateServerCertificate(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) As Boolean
      ' Log certificate details for debugging
      System.Diagnostics.Debug.WriteLine("Certificate Subject: " & certificate.Subject)
      System.Diagnostics.Debug.WriteLine("Certificate Issuer: " & certificate.Issuer)
      System.Diagnostics.Debug.WriteLine("SSL Policy Errors: " & sslPolicyErrors.ToString())

      ' Accept all certificates for testing
      Return True
   End Function

   Public Shared Function SendAccountActivationEmail(toEmail As String, activationLink As String, firstName As String, lastName As String) As Boolean
      Try
         ' Set global SSL/TLS settings
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
         ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateServerCertificate

         Using client As New SmtpClient(SmtpServer, SmtpPort)
            client.EnableSsl = True
            client.UseDefaultCredentials = False
            client.Credentials = New System.Net.NetworkCredential(SmtpUsername, SmtpPassword)
            client.Timeout = 60000

            Using message As New MailMessage()
               message.From = New MailAddress(FromEmail, FromName)
               message.To.Add(toEmail)
               message.Subject = "Account Activation"
               message.Body = GetActivationEmailBody(activationLink, firstName, lastName)
               message.IsBodyHtml = True

               client.Send(message)
               Return True
            End Using
         End Using
      Catch ex As Exception
         System.Diagnostics.Debug.WriteLine("Email Error: " & ex.Message)
         System.Diagnostics.Debug.WriteLine("Stack Trace: " & ex.StackTrace)
         ErrorLogger.Log("EmailService", "AccountActivation", Nothing, ex, toEmail)
         Return False
      End Try
   End Function

   Private Shared Function GetPasswordResetEmailBody(userName As String, password As String, loginUrl As String) As String
      Return "<html>" &
             "<body>" &
             "Hello " & userName & "<br>" &
             "<br>" &
             "<a href='" & loginUrl & "'>Please click here to sign in to your account.</a><br><br>" &
             "Your password is: " & password & 
             "<br><br>" &
             "<br><br>" &
             "Thank you<br>" &
             "</body>" &
             "</html>"
   End Function

   Private Shared Function GetActivationEmailBody(activationLink As String, firstName As String, lastName As String) As String
      Return "<html>" &
             "<body>" &
             "<h2>Account Activation</h2>" &
             "<p>Hello " & firstName & " " & lastName & ",</p>" &
             "<p>Thank you for registering with Pernod Ricard. Please click the link below to activate your account:</p>" &
             "<p><a href='" & activationLink & "'>" & activationLink & "</a></p>" &
             "<p>If you did not create this account, please ignore this email.</p>" &
             "<p>This link will expire in 24 hours.</p>" &
             "<br/>" &
             "<p>Best regards,<br/>Pernod Ricard Team</p>" &
             "</body>" &
             "</html>"
   End Function

   Public Shared Function SendOrderConfirmationEmail(ByVal userEmail As String, ByVal firstName As String, ByVal orderNumber As String, ByVal warehouse As String, ByVal orderDate As String, ByVal status As String, ByVal orderDetails As String) As Boolean
      Try
         ' Set global SSL/TLS settings
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
         ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateServerCertificate

         ' Create SmtpClient with host and port in constructor
         Using client As New SmtpClient(SmtpServer, SmtpPort)
            client.EnableSsl = True
            client.UseDefaultCredentials = False
            client.Credentials = New System.Net.NetworkCredential(SmtpUsername, SmtpPassword)
            client.Timeout = 60000 ' Increase timeout to 60 seconds

            Using message As New MailMessage()
               message.From = New MailAddress(FromEmail, FromName)
               message.To.Add(userEmail)
               message.Subject = "Pernod Ricard | Staff Order Confirmed - " & orderNumber
               message.IsBodyHtml = True

               If Not String.IsNullOrEmpty(ConfigurationManager.AppSettings("BccEmail")) Then
                  message.Bcc.Add(ConfigurationManager.AppSettings("BccEmail"))
               End If

               ' Build modern HTML email body
               Dim orderQueriesContact As String = ConfigurationManager.AppSettings("OrderQueriesContact")
               Dim portalUrl As String = ConfigurationManager.AppSettings("WEBSITE")

               Dim emailBody As New StringBuilder()
               emailBody.AppendLine("<!DOCTYPE html>")
               emailBody.AppendLine("<html lang='en'>")
               emailBody.AppendLine("<head>")
               emailBody.AppendLine("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />")
               emailBody.AppendLine("<meta name='viewport' content='width=device-width, initial-scale=1' />")
               emailBody.AppendLine("<style>")
               emailBody.AppendLine("  body{margin:0;padding:0;background:#f6f7fb;font-family:Segoe UI,Roboto,Helvetica,Arial,sans-serif;color:#1f2937;}")
               emailBody.AppendLine("  .container{width:100%;padding:24px 0;}")
               emailBody.AppendLine("  .card{max-width:640px;margin:0 auto;background:#ffffff;border-radius:12px;overflow:hidden;border:1px solid #e5e7eb;}")
               emailBody.AppendLine("  .header{background:#123F75;color:#ffffff;padding:20px 24px;font-size:20px;font-weight:600;}")
               emailBody.AppendLine("  .content{padding:24px;}")
               emailBody.AppendLine("  .meta{margin:16px 0;padding:16px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:8px;}")
               emailBody.AppendLine("  .meta-row{display:flex;flex-wrap:wrap;margin:0 -8px;}")
               emailBody.AppendLine("  .meta-col{flex:1 1 240px;padding:8px;}")
               emailBody.AppendLine("  .meta-label{font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:.02em;}")
               emailBody.AppendLine("  .meta-value{font-size:14px;color:#111827;font-weight:600;}")
               emailBody.AppendLine("  .table-wrap{margin-top:12px;border:1px solid #e5e7eb;border-radius:8px;overflow:hidden;}")
               emailBody.AppendLine("  table{width:100%;border-collapse:collapse;}")
               emailBody.AppendLine("  thead th{background:#f3f4f6;color:#374151;font-size:12px;text-align:left;padding:12px;border-bottom:1px solid #e5e7eb;}")
               emailBody.AppendLine("  tbody td{font-size:13px;color:#1f2937;padding:12px;border-bottom:1px solid #eef2f7;}")
               emailBody.AppendLine("  tbody tr:last-child td{border-bottom:none;}")
               emailBody.AppendLine("  .footer{padding:16px 24px;background:#f9fafb;border-top:1px solid #e5e7eb;font-size:12px;color:#6b7280;}")
               emailBody.AppendLine("  .cta{display:inline-block;margin-top:12px;padding:10px 16px;background:#123F75;color:#ffffff;text-decoration:none;border-radius:8px;font-weight:600;}")
               emailBody.AppendLine("  @media (max-width:600px){.content{padding:16px}.header{padding:16px}}")
               emailBody.AppendLine("</style>")
               emailBody.AppendLine("</head>")
               emailBody.AppendLine("<body>")
               emailBody.AppendLine("  <div class='container'>")
               emailBody.AppendLine("    <div class='card'>")
               emailBody.AppendLine("      <div class='header'>Order Confirmation</div>")
               emailBody.AppendLine("      <div class='content'>")
               emailBody.AppendLine("        <div style='font-size:15px;'>Hi " & firstName & ",</div>")
               emailBody.AppendLine("        <div style='margin-top:8px;font-size:14px;color:#374151;'>Thanks for ordering through the online portal. Your order has been received.</div>")
               emailBody.AppendLine("        <div class='meta'>")
               emailBody.AppendLine("          <div class='meta-row'>")
               emailBody.AppendLine("            <div class='meta-col'><div class='meta-label'>Order Number</div><div class='meta-value'>" & orderNumber & "</div></div>")
               emailBody.AppendLine("            <div class='meta-col'><div class='meta-label'>Warehouse</div><div class='meta-value'>" & warehouse & "</div></div>")
               emailBody.AppendLine("            <div class='meta-col'><div class='meta-label'>Order Date</div><div class='meta-value'>" & orderDate & "</div></div>")
               emailBody.AppendLine("            <div class='meta-col'><div class='meta-label'>Status</div><div class='meta-value'>" & status & "</div></div>")
               emailBody.AppendLine("          </div>")
               emailBody.AppendLine("        </div>")
               emailBody.AppendLine("        <div class='table-wrap'>")
               emailBody.AppendLine("          <table role='presentation'>")
               emailBody.AppendLine("            <thead>")
               emailBody.AppendLine("              <tr>")
               emailBody.AppendLine("                <th>Product Description</th>")
               emailBody.AppendLine("                <th>Stock Code</th>")
               emailBody.AppendLine("                <th style='text-align:center;'>Qty</th>")
               emailBody.AppendLine("                <th style='text-align:right;'>Price</th>")
               emailBody.AppendLine("                <th style='text-align:right;'>Total</th>")
               emailBody.AppendLine("              </tr>")
               emailBody.AppendLine("            </thead>")
               emailBody.AppendLine("            <tbody>")
               emailBody.AppendLine(orderDetails)
               emailBody.AppendLine("            </tbody>")
               emailBody.AppendLine("          </table>")
               emailBody.AppendLine("        </div>")
               emailBody.AppendLine("        <a href='" & portalUrl & "' class='cta' target='_blank' rel='noopener'>Go to Portal</a>")
               emailBody.AppendLine("        <div style='margin-top:16px;font-size:13px;color:#374151;'>")
               emailBody.AppendLine("          <strong>Order queries?</strong><br/>")
               emailBody.AppendLine("          Contact " & orderQueriesContact & "")
               emailBody.AppendLine("        </div>")
               emailBody.AppendLine("        <div style='margin-top:16px;font-size:13px;color:#374151;'>")
               emailBody.AppendLine("          Thank you,<br/>")
               emailBody.AppendLine("          Pernod Ricard Staff Ordering Portal")
               emailBody.AppendLine("        </div>")
               emailBody.AppendLine("      </div>")
               emailBody.AppendLine("      <div class='footer'>This is an automated message. Please do not reply.</div>")
               emailBody.AppendLine("    </div>")
               emailBody.AppendLine("  </div>")
               emailBody.AppendLine("</body>")
               emailBody.AppendLine("</html>")

               message.Body = emailBody.ToString()

               System.Diagnostics.Debug.WriteLine("Attempting to send order confirmation email...")
               client.Send(message)
               System.Diagnostics.Debug.WriteLine("Order confirmation email sent successfully to: " & userEmail)
               Return True
            End Using
         End Using
      Catch ex As Exception
         System.Diagnostics.Debug.WriteLine("Order Confirmation Email Error: " & ex.Message)
         System.Diagnostics.Debug.WriteLine("Stack Trace: " & ex.StackTrace)
         ErrorLogger.Log("EmailService", "OrderConfirmation", Nothing, ex, userEmail)
         Return False
      End Try
   End Function
End Class