const nodemailer = require('nodemailer');

// Create Nodemailer transporter
const transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST,
    port: parseInt(process.env.SMTP_PORT),
    secure: process.env.SMTP_PORT == 465, // true for 465, false for other ports
    auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS
    }
});

async function sendEmail(receiver, content, subject = 'Elfit Arabia Login OTP') {
    const sender = process.env.SENDER_GMAIL_ADDRS;

    if (!process.env.SMTP_HOST || !sender) {
        throw new Error('Missing SMTP credentials');
    }

    // In development mode, log to console instead of sending
    if (process.env.NODE_ENV === 'development') {
        console.log('='.repeat(50));
        console.log('[DEV MODE] Email would be sent:');
        console.log(`To: ${receiver}`);
        console.log(`Subject: ${subject}`);
        console.log(`Content: ${content}`);
        console.log('='.repeat(50));
        return;
    }

    const mailOptions = {
        from: `"Elfit Arabia" <${sender}>`,
        to: receiver,
        subject: subject,
        html: content.replace(/\n/g, '<br>')
    };

    try {
        await transporter.sendMail(mailOptions);
        console.log('Email sent successfully to:', receiver);
    } catch (error) {
        console.error('Nodemailer error:', error);
        throw new Error(`Failed to send email via Nodemailer: ${error.message}`);
    }
}

async function sendOtpEmail(receiver, otp) {
    const content = `
    <p>Your OTP for <strong>Elfit Arabia B2B Portal</strong> is:</p>
    <h2>${otp}</h2>
    <p>This OTP is valid for <strong>10 minutes</strong>.</p>
    `;

    // In dev mode, always log the OTP
    console.log(`[OTP for ${receiver}]: ${otp}`);

    await sendEmail(receiver, content, 'Elfit Arabia Login OTP');
}

async function sendAccessDeniedEmail(receiver) {
    const content = `
    <h3>Access Request Denied</h3>
    <p>Your request to access the <strong>Elfit Arabia B2B Portal</strong> has been denied.</p>
    <p>This portal is restricted to authorized personnel only.</p>
    <p>If you believe this is an error, please contact our support team.</p>
    <br>
    <p>Best regards,<br><strong>Elfit Arabia Team</strong></p>
    `;

    await sendEmail(receiver, content, 'Elfit Arabia - Access Denied');
}

async function sendOrderNotificationEmail(adminEmail, orderDetails) {
    const { productName, expectedDate, quantity, comments, userEmail } = orderDetails;

    const content = `
    <div style="font-family:Arial; max-width:600px;">
        <h2>New Order Placed</h2>
        <p>A new order has been placed:</p>
        <hr>
        <p><strong>Product Name:</strong> ${productName}</p>
        <p><strong>Expected Date:</strong> ${expectedDate}</p>
        <p><strong>Quantity:</strong> ${quantity}</p>
        <p><strong>Comments:</strong> ${comments || 'None'}</p>
        <p><strong>Ordered by:</strong> ${userEmail}</p>
        <hr>
        <small>Elfit Arabia B2B Portal</small>
    </div>
    `;

    await sendEmail(adminEmail, content, 'New Order Placed');
}

async function sendQuotationEmail(clientEmail, orderId, orderName, orderQuantity, messageBody, attachmentData = null) {
    const content = `
    <div style="font-family:Arial; max-width:600px;">
        <h2>Quotation for Your Order</h2>
        <p><strong>Order ID:</strong> #${orderId}</p>
        <p><strong>Product:</strong> ${orderName}</p>
        <p><strong>Quantity:</strong> ${orderQuantity}</p>
        <hr>
        <p>${messageBody.replace(/\n/g, '<br>')}</p>
        <hr>
        <small>
            Elfit Arabia<br>
            B2B Procurement Platform<br>
            Please do not reply to this email
        </small>
    </div>
    `;

    const mailOptions = {
        from: `"Elfit Arabia" <${process.env.SENDER_GMAIL_ADDRS}>`,
        to: clientEmail,
        subject: `Quotation for Order #${orderId}: ${orderName} (${orderQuantity})`,
        html: content
    };

    // Add attachment if provided
    if (attachmentData) {
        mailOptions.attachments = [{
            content: attachmentData.content,
            filename: attachmentData.filename,
            contentType: attachmentData.type,
            encoding: 'base64'
        }];
    }

    if (process.env.NODE_ENV === 'development') {
        console.log('[DEV MODE] Quotation email would be sent to:', clientEmail);
        return;
    }

    await transporter.sendMail(mailOptions);
}

async function sendDispatchEmail(clientEmail, orderId, productName, quantity) {
    const content = `
    <div style="font-family:Arial; max-width:600px;">
        <h2>Your Order Has Been Dispatched 🚚</h2>
        <p>Good news! Your order has been dispatched and is on its way.</p>
        <hr>
        <p><strong>Order ID:</strong> #${orderId}</p>
        <p><strong>Product:</strong> ${productName}</p>
        <p><strong>Quantity:</strong> ${quantity}</p>
        <hr>
        <p>If you have any questions, feel free to contact us.</p>
        <small>
            Elfit Arabia<br>
            B2B Procurement Platform
        </small>
    </div>
    `;

    await sendEmail(clientEmail, content, `Order Dispatched – Order #${orderId}: ${productName}`);
}

async function sendDeliveredEmail(clientEmail, orderId, productName, quantity) {
    const content = `
    <div style="font-family:Arial; max-width:600px;">
        <h2>✅ Order Delivered Successfully</h2>
        <p>We're happy to inform you that your order has been successfully delivered.</p>
        <hr>
        <p><strong>Order ID:</strong> #${orderId}</p>
        <p><strong>Product:</strong> ${productName}</p>
        <p><strong>Quantity:</strong> ${quantity}</p>
        <hr>
        <p>Thank you for choosing <strong>Elfit Arabia</strong>. We hope you're satisfied with your purchase.</p>
        <small>
            Elfit Arabia<br>
            B2B Procurement Platform
        </small>
    </div>
    `;

    await sendEmail(clientEmail, content, `Order Delivered – Order #${orderId}: ${productName}`);
}

async function sendCancellationEmail(adminEmail, orderId, userEmail, orderName, orderQuantity) {
    const content = `
    <div style="font-family:Arial; max-width:600px;">
        <h2 style="color: #dc3545;">Order Cancelled by Client</h2>
        <p>A client has cancelled their order:</p>
        <hr>
        <p><strong>Order ID:</strong> #${orderId}</p>
        <p><strong>Client Email:</strong> ${userEmail}</p>
        <p><strong>Product:</strong> ${orderName}</p>
        <p><strong>Quantity:</strong> ${orderQuantity}</p>
        <hr>
        <small>
            Elfit Arabia B2B Portal<br>
            Automated Notification
        </small>
    </div>
    `;

    await sendEmail(adminEmail, content, `Order Cancelled - #${orderId}: ${orderName}`);
}

async function sendOrderConfirmationEmail(adminEmail, orderId, userEmail, orderName, orderQuantity) {
    const content = `
    <div style="font-family:Arial; max-width:600px;">
        <h2 style="color: #198754;">✅ New Order Confirmation</h2>
        <p>A client has confirmed their order:</p>
        <hr>
        <p><strong>Order ID:</strong> #${orderId}</p>
        <p><strong>Client Email:</strong> ${userEmail}</p>
        <p><strong>Product:</strong> ${orderName}</p>
        <p><strong>Quantity:</strong> ${orderQuantity}</p>
        <p><strong>Confirmed at:</strong> ${new Date().toISOString()}</p>
        <hr>
        <small>
            Elfit Arabia B2B Portal<br>
            Automated Notification
        </small>
    </div>
    `;

    await sendEmail(adminEmail, content, `✅ Order Confirmed - #${orderId}: ${orderName}`);
}

module.exports = {
    sendEmail,
    sendOtpEmail,
    sendAccessDeniedEmail,
    sendOrderNotificationEmail,
    sendQuotationEmail,
    sendDispatchEmail,
    sendDeliveredEmail,
    sendCancellationEmail,
    sendOrderConfirmationEmail
};
