import nodemailer from 'nodemailer' import { getSystemSettings } from '@/lib/settings' interface EmailOptions { to: string subject: string html: string text?: string } class EmailServiceClass { private transporter: nodemailer.Transporter | null = null private isConfigured: boolean = false constructor() { this.initializeTransporter() } private initializeTransporter() { try { // Check if SMTP credentials are configured const smtpUser = process.env.SMTP_USER const smtpPass = process.env.SMTP_PASSWORD // Changed from SMTP_PASS if (!smtpUser || !smtpPass) { console.warn('SMTP credentials not configured. Email notifications will be disabled.') return } this.transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST || 'smtp.gmail.com', port: parseInt(process.env.SMTP_PORT || '587'), secure: false, auth: { user: smtpUser, pass: smtpPass, }, }) this.isConfigured = true console.log('Email service initialized successfully') } catch (error) { console.error('Failed to initialize email service:', error) this.isConfigured = false } } async sendEmail({ to, subject, html, text }: EmailOptions) { if (!this.isConfigured || !this.transporter) { console.log(`Email would be sent to ${to}: ${subject}`) console.log('Email service not configured - skipping email send') return { messageId: 'not-configured', skipped: true } } try { const settings = await getSystemSettings() const mailOptions = { from: process.env.SMTP_FROM || `"${settings.siteName}" <${process.env.SMTP_USER}>`, // Use SMTP_FROM if available to, subject, html, text: text || this.htmlToText(html) } const result = await this.transporter.sendMail(mailOptions) console.log('Email sent successfully:', result.messageId) return result } catch (error) { console.error('Email sending failed:', error) // Don't throw error, just log it so the main process continues const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred' return { messageId: 'failed', error: errorMessage } } } private htmlToText(html: string): string { return html.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim() } // Order confirmation email async sendOrderConfirmation(userEmail: string, userName: string, order: any) { const html = `

Order Confirmed! 🎉

Hi ${userName},

Thank you for your order! We're excited to process it for you.

Order Details:

Order ID: #${order.id.slice(-8)}

Total: ₹${order.total.toFixed(2)}

Status: ${order.status}

Date: ${new Date(order.createdAt).toLocaleDateString()}

Items Ordered:

${order.orderItems.map((item: any) => `

${item.product.name}

Quantity: ${item.quantity} | Price: ₹${item.price.toFixed(2)}

`).join('')}

We'll send you another email when your order ships.

Thanks for shopping with us!

If you have any questions, reply to this email or contact our support team.

` return await this.sendEmail({ to: userEmail, subject: `Order Confirmation - #${order.id.slice(-8)}`, html }) } // Commission earned email async sendCommissionAlert(userEmail: string, userName: string, commission: any) { const html = `

Commission Earned! 💰

Hi ${userName},

Great news! You've earned a new commission.

Commission Details:

Amount: ₹${commission.amount.toFixed(2)}

Level: ${commission.level}

Type: ${commission.type}

From: ${commission.fromUser.name}

Date: ${new Date(commission.createdAt).toLocaleDateString()}

This commission has been added to your wallet.

Keep up the great work building your network!

View All Commissions
` return await this.sendEmail({ to: userEmail, subject: `New Commission Earned - ₹${commission.amount.toFixed(2)}`, html }) } // Rank achievement email async sendRankAchievement(userEmail: string, userName: string, newRank: any) { const html = `

Congratulations! 🏆

Hi ${userName},

Amazing news! You've achieved a new rank in our program.

🎉 ${newRank.name} 🎉

${newRank.description}

Rank Benefits:

This achievement reflects your dedication and success. Keep growing your network to unlock even more rewards!

View Dashboard
` return await this.sendEmail({ to: userEmail, subject: `🏆 Congratulations! You've achieved ${newRank.name} rank!`, html }) } // Partner application admin notification async sendPartnerApplicationAdminNotification(data: any, newUser: any) { const html = `

New Partner Application Received

Partner Information

Name: ${data.firstName} ${data.lastName}

Email: ${data.email}

Phone: ${data.phone}

Partnership Tier: ${data.partnershipTier}

Expected Customers: ${data.expectedCustomers}

Business Information

Business Name: ${data.businessName || 'N/A'}

Business Type: ${data.businessType}

Experience: ${data.experience}

Address

${data.address}

${data.city}, ${data.state} ${data.zipCode}

Additional Information

Motivation: ${data.motivation}

Marketing Plan: ${data.marketingPlan}

✅ User has been automatically created and approved as a MEMBER.

User ID: ${newUser.id}

Referral Code: ${newUser.referralCode}

` return await this.sendEmail({ to: process.env.ADMIN_EMAIL || 'info@padmajarice.com', subject: `New Partner Application - ${data.partnershipTier} Tier`, html }) } // Partner welcome email async sendPartnerWelcomeEmail(data: any, newUser: any, randomPassword: string) { const html = `

Welcome to Padmaaja Rasooi!

Your partnership application has been approved

Congratulations, ${data.firstName}!

We're excited to welcome you as a ${data.partnershipTier} partner in the Padmaaja Rasooi family.

Your Login Details

Website: ${process.env.NEXTAUTH_URL || 'http://localhost:3000'}

Email: ${data.email}

Password: ${randomPassword}

Your Referral Code: ${newUser.referralCode}

Partnership Details

Tier: ${data.partnershipTier}

Required Members: Minimum 3 members must be added

Commission Structure: Earn commissions on all purchases made by your referrals

Next Steps

  1. Log in to your partner dashboard using the credentials above
  2. Complete your profile setup
  3. Add minimum 3 members using your referral code
  4. Track your earnings and commissions in real-time

Important Notes

  • You must add at least 3 members to maintain your partnership
  • You'll earn commissions on all purchases made by your referrals
  • Please change your password after first login for security
  • Contact support for any questions: ${process.env.SUPPORT_EMAIL || 'info@padmajarice.com'}
Login to Your Dashboard

Thank you for joining Padmaaja Rasooi. We look forward to a successful partnership!

Best regards,
The Padmaaja Rasooi Team

` return await this.sendEmail({ to: data.email, subject: 'Welcome to Padmaaja Rasooi Partnership Program!', html }) } // Member added admin notification async sendMemberAddedAdminNotification(partner: any, newMember: any) { const html = `

New Member Added

Partner Information

Partner: ${partner.name} (${partner.email})

Partner Tier: ${partner.partnerTier || 'N/A'}

Current Members: ${partner.referrals.length + 1}

Min Required: ${partner.minReferrals}

Status: ${partner.referrals.length + 1 >= partner.minReferrals ? '✅ Meeting minimum requirement' : '⚠️ Building minimum members'}

New Member Information

Name: ${newMember.name}

Email: ${newMember.email}

Phone: ${newMember.phone}

User ID: ${newMember.id}

Referral Code: ${newMember.referralCode}

` return await this.sendEmail({ to: process.env.ADMIN_EMAIL || 'info@padmajarice.com', subject: `New Member Added by Partner: ${partner.name}`, html }) } // Member welcome email async sendMemberWelcomeEmail(memberData: any, partner: any, randomPassword: string) { const html = `

Welcome to Padmaaja Rasooi!

You've been added by our partner: ${partner.name}

Hello ${memberData.name}!

Welcome to the Padmaaja Rasooi family! You've been added as a member by our partner ${partner.name}.

Your Account Details

Website: ${process.env.NEXTAUTH_URL || 'http://localhost:3000'}

Email: ${memberData.email}

Password: ${randomPassword}

What's Next?

  1. Log in to your account using the credentials above
  2. Browse our premium spice collection
  3. Place your first order and enjoy exclusive member benefits
  4. Earn rewards and commissions through our referral program

Member Benefits

  • Exclusive access to premium spices and masalas
  • Special member pricing and discounts
  • Earn commissions by referring others
  • Priority customer support
Login to Your Account

Important: Please change your password after first login for security.

If you have any questions, contact us at ${process.env.SUPPORT_EMAIL || 'info@padmajarice.com'}

Best regards,
The Padmaaja Rasooi Team

` return await this.sendEmail({ to: memberData.email, subject: 'Welcome to Padmaaja Rasooi!', html }) } // Wholesaler welcome email async sendWholesalerWelcomeEmail(wholesalerData: { to: string name: string email: string password: string businessName: string }) { const html = `

Welcome to Padmaaja Rasooi Wholesaler Network! 🏪

Dear ${wholesalerData.name},

Congratulations! Your wholesaler registration has been approved. You are now part of our exclusive wholesaler network.

🎉 Welcome ${wholesalerData.businessName}! 🎉

You now have access to wholesale benefits

Your Login Credentials

Email: ${wholesalerData.email}

Temporary Password: ${wholesalerData.password}

Important: Please change your password after first login.

🎁 Your Wholesale Benefits

  • 25% Discount on all bulk orders
  • Dedicated account manager
  • Priority customer support
  • Flexible payment terms
  • Quality guarantee on all products
  • Fast order processing

Next Steps

  1. Login to your account using the credentials above
  2. Complete your profile information
  3. Browse our wholesale catalog
  4. Place your first bulk order to enjoy 25% discount
  5. Contact your account manager for assistance
Login to Your Wholesaler Account

Our team will contact you within 24 hours to assist with your first order and answer any questions.

For immediate assistance, contact us at ${process.env.SUPPORT_EMAIL || 'info@padmajarice.com'} or call our wholesaler hotline.

Best regards,
The Padmaaja Rasooi Wholesale Team

` return await this.sendEmail({ to: wholesalerData.to, subject: 'Welcome to Padmaaja Rasooi Wholesale Network!', html }) } // Admin notification for new wholesaler registration async sendWholesalerAdminNotification(wholesalerData: { wholesalerName: string wholesalerEmail: string businessName: string businessType: string phone: string expectedVolume: string registrationDate: string }) { const settings = await getSystemSettings() const html = `

🏪 New Wholesaler Registration

A new wholesaler has registered on the platform.

Wholesaler Details

Name: ${wholesalerData.wholesalerName}

Email: ${wholesalerData.wholesalerEmail}

Business Name: ${wholesalerData.businessName}

Business Type: ${wholesalerData.businessType}

Phone: ${wholesalerData.phone}

Expected Volume: ${wholesalerData.expectedVolume}

Registration Date: ${wholesalerData.registrationDate}

Required Actions

  • Review the wholesaler's application
  • Contact the wholesaler within 24 hours
  • Assign an account manager
  • Set up wholesale pricing if needed
  • Provide product catalogs and information
View in Admin Panel

The wholesaler has been automatically approved and given access to 25% wholesale discounts on bulk orders.

This is an automated notification from Padmaaja Rasooi

` return await this.sendEmail({ to: settings.supportEmail, subject: `New Wholesaler Registration - ${wholesalerData.businessName}`, html }) } async sendPartTimeWelcomeEmail(partTimeData: { to: string name: string email: string password: string preferredRole: string }) { const settings = await getSystemSettings() const html = `

Welcome to Padmaaja!

Part-Time Job Application Received

Dear ${partTimeData.name},

Thank you for applying for a part-time position with Padmaaja! We're excited about your interest in joining our team.

Application Details:

Preferred Role: ${partTimeData.preferredRole}

Application Status: Under Review

Your Login Credentials:

Email: ${partTimeData.email}

Password: ${partTimeData.password}

Please keep these credentials safe. You can use them to log in to your dashboard.

What's Next?

  • Our HR team will review your application within 2-3 business days
  • You'll receive a call to discuss the opportunity
  • Complete a brief interview process
  • Start your part-time job journey with us!

If you have any questions, feel free to contact our support team.

Best regards,
Padmaaja Team

© 2024 Padmaaja. All rights reserved.

` return await this.sendEmail({ to: partTimeData.to, subject: 'Part-Time Job Application Received - Padmaaja', html }) } async sendPartTimeAdminNotification(partTimeData: { applicantName: string applicantEmail: string preferredRole: string phone: string availableHours: string availableDays: string motivation: string registrationDate: string }) { const settings = await getSystemSettings() const html = `

New Part-Time Job Application

Application received on ${partTimeData.registrationDate}

Application Details:

Applicant Information:

Name: ${partTimeData.applicantName}

Email: ${partTimeData.applicantEmail}

Phone: ${partTimeData.phone}

Job Preferences:

Preferred Role: ${partTimeData.preferredRole}

Available Hours: ${partTimeData.availableHours} per day

Available Days: ${partTimeData.availableDays}

Motivation:

${partTimeData.motivation}

Please review this application and contact the applicant for the next steps.

© 2024 Padmaaja Admin Panel

` return await this.sendEmail({ to: settings.supportEmail, subject: `New Part-Time Application - ${partTimeData.applicantName}`, html }) } // B2B Inquiry confirmation email to customer async sendB2BInquiryConfirmation(data: { customerEmail: string customerName: string companyName: string inquiryId: string productName?: string }) { const html = ` B2B Inquiry Confirmation

Inquiry Received Successfully

Thank you for your business inquiry

Dear ${data.customerName},

Thank you for your inquiry regarding bulk procurement ${data.productName ? `of ${data.productName}` : 'from Padmaaja Rasooi'}. We have received your detailed requirements and our team is reviewing them.

Inquiry Details

What happens next?

  1. Our procurement team will review your requirements within 2-4 business hours
  2. We will prepare a detailed quotation including pricing, terms, and delivery schedules
  3. A dedicated account manager will contact you within 24 hours to discuss your needs
  4. We will provide samples if required and finalize the order details

Priority Response: As a bulk inquiry, your request has been marked as high priority. Our business development team will reach out to you shortly.

Need immediate assistance?

Contact our B2B Sales Team:

This is an automated confirmation. Please do not reply to this email.

© 2024 Padmaaja Rasooi Pvt. Ltd. | Premium Rice & Grains

` await this.sendEmail({ to: data.customerEmail, subject: `B2B Inquiry Confirmation - ${data.companyName} | Padmaaja Rasooi`, html }) } // B2B Inquiry admin notification async sendB2BInquiryAdminNotification(data: { inquiryData: any inquiryId: string }) { const inquiry = data.inquiryData const html = ` New B2B Inquiry - Priority

🚨 New B2B Inquiry - HIGH PRIORITY

Immediate attention required

⏰ Response Required Within 24 Hours

Company Information

Company:
${inquiry.companyName}
Business Type:
${inquiry.businessType}
Contact Person:
${inquiry.contactPerson}
Designation:
${inquiry.designation}
Email:
${inquiry.email}
Phone:
${inquiry.phone}
${inquiry.gstNumber ? `
GST Number: ${inquiry.gstNumber}
` : ''}
Address:
${inquiry.address}
${inquiry.productName ? `

Product Inquiry

Product:
${inquiry.productName}
Category:
${inquiry.productCategory || 'N/A'}
Listed Price:
₹${inquiry.productPrice || 'N/A'}
Product ID:
${inquiry.productId || 'N/A'}
` : ''}

Requirements

Quantity Required:
${inquiry.quantityRequired} ${inquiry.quantityUnit}
Delivery Location:
${inquiry.deliveryLocation}
${inquiry.expectedDeliveryDate ? `
Expected Delivery: ${inquiry.expectedDeliveryDate}
` : ''}
Detailed Requirements:
${inquiry.message.replace(/\n/g, '
')}
${inquiry.hearAboutUs ? `
How they heard about us: ${inquiry.hearAboutUs}
` : ''}

Admin Actions

Inquiry ID: ${data.inquiryId}

View in Admin Panel Reply to Customer

Submitted: ${new Date().toLocaleString('en-IN')} | Priority: HIGH

© 2024 Padmaaja Admin Panel

` await this.sendEmail({ to: process.env.ADMIN_EMAIL || 'info@padmajarice.com', subject: `🚨 URGENT: New B2B Inquiry from ${inquiry.companyName} - ${inquiry.quantityRequired} ${inquiry.quantityUnit}`, html }) } } export const emailService = new EmailServiceClass() // Export the class properly without circular reference export const EmailService = EmailServiceClass export default EmailServiceClass