<%
'=======================================================================================================================
' Order-related outbound email: the "continue your order" link and the order-details
' confirmation sent after SubmitOrderDetails.
'=======================================================================================================================
Class OrderMailer_Class

    Public Sub SendContinuationEmail(email, token)
        Dim continueUrl
        continueUrl = Routes().AppURL & "order/continue?token=" & Server.URLEncode(token)

        Dim inner
        inner = "<div style=""color:#7c3bc0; font-weight:800; font-size:11px; letter-spacing:0.06em; text-transform:uppercase;"">Order Request Received</div>" & _
                "<h1 style=""color:#201a27; font-size:22px; margin:6px 0 12px; font-family:Arial, Helvetica, sans-serif;"">Continue your election materials order</h1>" & _
                "<p style=""color:#6d6574; font-size:13px; margin:0 0 20px;"">Click the button below to pick up where you left off.</p>" & _
                "<p style=""margin:0 0 20px;""><a href=""" & H(continueUrl) & """ style=""display:inline-block; background:#6529a0; color:#ffffff; font-weight:700; font-size:14px; padding:12px 28px; border-radius:10px; text-decoration:none;"">Continue your order</a></p>" & _
                "<p style=""color:#6d6574; font-size:12px; margin:0;"">Or copy and paste this link into your browser:<br /><a href=""" & H(continueUrl) & """ style=""color:#6529a0;"">" & H(continueUrl) & "</a></p>" & _
                "<p style=""color:#6d6574; font-size:12px; margin-top:16px;"">This link expires in " & H(GetAppSetting("OrderTokenExpirationHours")) & " hours and can only be used once.</p>"

        Dim mail : Set mail = NewConfiguredMail()
        mail.Subject    = "Continue your Purple Envelope order"
        mail.IsBodyHTML = True
        mail.Body       = EmailShell(inner)
        mail.AddRecipient "To", email
        mail.Send
    End Sub

    ' Best-effort: the order is already safely persisted by the time a caller reaches this -
    ' an SMTP hiccup here should not turn a successful submission into a failed one.
    Public Sub SendOrderDetailsEmail(order, model)
        On Error Resume Next

        Dim mail : Set mail = NewConfiguredMail()
        mail.Subject    = "Your Purple Envelope order details - Jurisdiction " & order("JurisdictionNumber")
        mail.IsBodyHTML = True
        mail.Body       = BuildOrderDetailsEmailBody(order, model)
        mail.AddRecipient "To", order("Email")
        mail.Send

        Err.Clear
        On Error GoTo 0
    End Sub

    '-------------------------------------------------------------------------------------------------------------------
    ' Private helpers
    '-------------------------------------------------------------------------------------------------------------------
    Private Function NewConfiguredMail()
        Dim smtpPort : smtpPort = GetAppSetting("SmtpPort")
        If Not IsNumeric(smtpPort) Then smtpPort = 25

        Dim mail : Set mail = CDOEmail()
        mail.SMTPServer   = GetAppSetting("SmtpServer")
        mail.SMTPPort     = CInt(smtpPort)
        mail.SMTPUsername = GetAppSetting("SmtpUsername")
        mail.SMTPPassword = GetAppSetting("SmtpPassword")
        mail.SMTPUseSSL   = (LCase(GetAppSetting("SmtpUseSSL")) = "true")
        mail.From         = GetAppSetting("SmtpFromAddress")
        Set NewConfiguredMail = mail
    End Function

    Private Function BuildOrderDetailsEmailBody(order, model)
        Dim html
        html = "<div style=""color:#7c3bc0; font-weight:800; font-size:11px; letter-spacing:0.06em; text-transform:uppercase;"">Order Received</div>" & _
               "<h1 style=""color:#201a27; font-size:22px; margin:6px 0 4px; font-family:Arial, Helvetica, sans-serif;"">Thanks! We've received your order details.</h1>" & _
               "<p style=""color:#6d6574; font-size:13px; margin:0 0 8px;"">Jurisdiction number <strong style=""color:#201a27;"">" & H(order("JurisdictionNumber")) & "</strong>" & _
               " &middot; submitted " & H(EmailDate(model.SubmittedAt)) & "</p>"

        html = html & EmailSection("Contact Information", _
            EmailRow("Contact Name", model.ContactName) & _
            EmailRow("Municipality", model.Municipality) & _
            EmailRow("Phone", model.Phone))

        If IsTrue(model.PurpleWantsQuote) Then
            Dim purpleBlueProviderLine
            purpleBlueProviderLine = LabelPurpleBlueProvider(model.PurpleBlueProvider)
            If purpleBlueProviderLine = "Other" And Len(Trim(model.PurpleBlueProviderOther & "")) > 0 Then
                purpleBlueProviderLine = model.PurpleBlueProviderOther
            End If

            html = html & EmailSection("Purple Ballot Envelopes", _
                EmailRow("Permanent ballot list count", model.PurplePermanentBallotListCount) & _
                EmailRow("Envelope stock", LabelEnvelopeStock(model.PurpleEnvelopeStock)) & _
                EmailRow("Print option", LabelPrintOption(model.PurplePrintOption)) & _
                EmailRow("Also wants KCI blue envelopes", EmailYesNo(model.PurpleWantsBlueEnvelopes)) & _
                EmailRow("Blue envelope provider", purpleBlueProviderLine) & _
                EmailRow("Print style", LabelPrintStyle(model.PurplePrintStyle)) & _
                EmailRow("Color coding by", LabelColorCodingBy(model.PurpleColorCodingBy)) & _
                EmailRow("Number of precincts", model.PurplePrecinctCount) & _
                EmailRow("Colors requested", model.PurpleColorNames) & _
                EmailRow("Track with TrackMI Ballot", EmailYesNo(model.PurpleTrackMIBallot)) & _
                EmailRow("Extra envelopes requested", model.PurpleExtraEnvelopeQty))
        End If

        If IsTrue(model.BlueWantsQuote) Then
            ' City/permit number are collected for an own-organization permit - a permit
            ' lookup can't be done from the nonprofit authorization code alone.
            Dim bluePermitLine
            bluePermitLine = ""
            If LabelPermitOwnership(model.BluePermitOwnership) = "My organization's permit" Then
                bluePermitLine = bluePermitLine & _
                                  EmailRow("City of permit holder", model.BluePermitCity) & _
                                  EmailRow("Permit number", model.BluePermitNumber)
            End If

            html = html & EmailSection("Blue AV Envelopes", _
                EmailRow("Print permit", EmailYesNo(model.BluePrintPermit)) & _
                EmailRow("Permit ownership", LabelPermitOwnership(model.BluePermitOwnership)) & _
                EmailRow("Confirmed nonprofit status with USPS", LabelNonprofitStatus(model.BlueHasNonprofitStatus)) & _
                bluePermitLine)
        End If

        If IsTrue(model.MailingWantsService) Then
            Dim mailingAuthCodeLine
            mailingAuthCodeLine = ""
            If CStr(model.MailingHasNonprofitStatus & "") = "Yes" Then
                If IsTrue(model.MailingNonprofitAuthCodeUnknown) Then
                    mailingAuthCodeLine = EmailRow("Nonprofit authorization code", "Unknown - customer needs help")
                Else
                    mailingAuthCodeLine = EmailRow("Nonprofit authorization code", model.MailingNonprofitAuthCode)
                End If
            End If

            html = html & EmailSection("Ballot Mailing Service", _
                EmailRow("Postage", LabelPostageOption(model.MailingPostageOption)) & _
                EmailRow("Nonprofit status with USPS", LabelNonprofitStatus(model.MailingHasNonprofitStatus)) & _
                mailingAuthCodeLine & _
                EmailRow("Estimated quantity", model.MailingEstimatedQuantity) & _
                EmailRow("Preferred pickup date", EmailDate(model.MailingPickupDate)))
        End If

        If NumOrZero(model.SecrecySleevesQty) > 0 Or NumOrZero(model.IVotedStickerRolls) > 0 Or NumOrZero(model.FutureVoterStickerRolls) > 0 Or Len(Trim(model.SpecialRequests & "")) > 0 Then
            html = html & EmailSection("Additional Election Items", _
                EmailRow("Secrecy sleeves (quantity)", model.SecrecySleevesQty) & _
                EmailRow("""I Voted"" stickers (rolls of 250)", model.IVotedStickerRolls) & _
                EmailRow("""Future Voter"" stickers (rolls of 500)", model.FutureVoterStickerRolls) & _
                EmailRow("Special requests", model.SpecialRequests))
        End If

        html = html & "<p style=""color:#6d6574; font-size:12px; margin-top:24px;"">Questions about this order? Just reply to this email.</p>"

        BuildOrderDetailsEmailBody = EmailShell(html)
    End Function

    ' Wraps inner body HTML in the same header/footer chrome used across the website - the
    ' navy KCI Election Printing bar (matching the site header/footer) and white content card.
    Private Function EmailShell(innerHtml)
        Dim logoUrl : logoUrl = Routes().AppURL & "images/KCI%20ELECTION%20printing%20(white).png"
        EmailShell = "<!doctype html><html><body style=""margin:0; padding:0; background:#faf7fd; font-family:Arial, Helvetica, sans-serif;"">" & _
               "<table role=""presentation"" width=""100%"" cellpadding=""0"" cellspacing=""0"" style=""background:#faf7fd; padding:24px 0;""><tr><td align=""center"">" & _
               "<table role=""presentation"" width=""600"" cellpadding=""0"" cellspacing=""0"" style=""background:#ffffff; border-radius:12px; overflow:hidden; box-shadow:0 4px 16px rgba(36,16,58,0.08);"">" & _
               "<tr><td style=""background:#254B74; padding:20px 32px; text-align:center;"">" & _
               "<img src=""" & H(logoUrl) & """ alt=""KCI Election Printing"" width=""160"" style=""display:block; margin:0 auto; height:auto; max-width:160px;"" />" & _
               "</td></tr>" & _
               "<tr><td style=""padding:32px;"">" & innerHtml & "</td></tr>" & _
               "<tr><td style=""background:#254B74; padding:20px 32px; text-align:center;"">" & _
               "<div style=""color:#ffffff; font-size:12px; font-weight:700;"">KCI Election Printing</div>" & _
               "<div style=""color:rgba(255,255,255,0.75); font-size:11px; margin-top:4px;"">616.957.2120 &middot; info@kentcommunications.com</div>" & _
               "</td></tr>" & _
               "</table></td></tr></table></body></html>"
    End Function

    Private Function EmailSection(sectionTitle, rowsHtml)
        If Len(rowsHtml) = 0 Then
            EmailSection = ""
        Else
            EmailSection = "<h2 style=""color:#4d1d78; font-size:14px; margin:24px 0 8px; padding-top:16px; border-top:1px solid #f0e7f8; font-family:Arial, Helvetica, sans-serif;"">" & _
                            H(sectionTitle) & "</h2>" & _
                            "<table role=""presentation"" width=""100%"" cellpadding=""0"" cellspacing=""0"">" & rowsHtml & "</table>"
        End If
    End Function

    Private Function EmailRow(label, value)
        If Len(Trim(value & "")) = 0 Then
            EmailRow = ""
        Else
            EmailRow = "<tr>" & _
                       "<td style=""padding:6px 0; color:#6d6574; font-size:13px; width:45%; vertical-align:top;"">" & H(label) & "</td>" & _
                       "<td style=""padding:6px 0; color:#201a27; font-size:13px; font-weight:600;"">" & H(value) & "</td>" & _
                       "</tr>"
        End If
    End Function

    ' Null-safe boolean check for gating whole sections - a section's top-level "do you want
    ' this?" question isn't marked required client-side, so it may be missing (Null) rather
    ' than explicitly false.
    Private Function IsTrue(v)
        If IsNull(v) Then
            IsTrue = False
        Else
            IsTrue = CBool(v)
        End If
    End Function

    Private Function EmailYesNo(v)
        If IsNull(v) Then
            EmailYesNo = ""
        ElseIf CBool(v) Then
            EmailYesNo = "Yes"
        Else
            EmailYesNo = "No"
        End If
    End Function

    Private Function EmailDate(v)
        If IsNull(v) Then
            EmailDate = ""
        Else
            On Error Resume Next
            EmailDate = MonthName(Month(v)) & " " & Day(v) & ", " & Year(v)
            If Err.Number <> 0 Then EmailDate = ""
            Err.Clear
            On Error GoTo 0
        End If
    End Function

    Private Function NumOrZero(v)
        If IsNull(v) Or Not IsNumeric(v) Then
            NumOrZero = 0
        Else
            NumOrZero = CDbl(v)
        End If
    End Function

End Class

Dim OrderMailer_Class__Singleton
Function OrderMailer()
    If IsEmpty(OrderMailer_Class__Singleton) Then
        Set OrderMailer_Class__Singleton = New OrderMailer_Class
    End If
    Set OrderMailer = OrderMailer_Class__Singleton
End Function
%>
