// npm install express nodemailer cors dotenv --f   //packages

// //Running Backend on a Server (Production)
// npm install -g pm2     //- Install Production Process Manager
// pm2 start server.cjs --name "chennora-backend"    //- Start your server

const express = require('express');
const nodemailer = require('nodemailer');
const cors = require('cors');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

app.post('/api/contact', async (req, res) => {
  const { name, email, phone, subject, message } = req.body;

  const transporter = nodemailer.createTransport({
    service: 'gmail', // or use "host", "port", "auth" for other providers
    auth: {
      user: process.env.MAIL_USER,
      pass: process.env.MAIL_PASS,
    },
  });

  const mailOptions = {
    from: email,
    to: process.env.MAIL_USER,
    subject: `New message from ${name} - ${subject}`,
    html: `
      <h3>Contact Details</h3>
      <p><b>Name:</b> ${name}</p>
      <p><b>Email:</b> ${email}</p>
      <p><b>Phone:</b> ${phone}</p>
      <p><b>Subject:</b> ${subject}</p>
      <p><b>Message:</b></p>
      <p>${message}</p>
    `,
  };

  try {
    await transporter.sendMail(mailOptions);
    res.status(200).send({ success: true, message: 'Email sent successfully' });
  } catch (err) {
    console.error('Error sending email:', err);
    res.status(500).send({ success: false, message: 'Email failed to send' });
  }
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
