module.exports = (pool, transporter) => { const submitForm = async (req, res) => { const { firstName, lastName, organization, email, phone, contactMethod, message, privacyAccepted } = req.body; if ( !firstName || !lastName || !email || !message || typeof contactMethod === 'undefined' || typeof privacyAccepted === 'undefined' ) { console.error('Missing required fields in submission:', req.body); return res.status(400).json({ message: 'Missing required form fields.' }); } try { const result = await pool.query( `INSERT INTO submissions( first_name, last_name, organization, email, phone, contact_method, message, privacy_accepted, time_submitted ) VALUES($1, $2, $3, $4, $5, $6, $7, $8, NOW()) RETURNING *`, [ firstName, lastName, organization, email, phone, contactMethod, message, privacyAccepted ] ); console.log('Successfully saved submission to the database:', result.rows[0]); const mailOptions = { from: `"Contact Form" `, to: process.env.EMAIL_RCPT, subject: 'New Contact Form Submission', html: `

New Submission

Message:

${message}

`, }; const emailInfo = await transporter.sendMail(mailOptions); console.log('Message sent: %s', emailInfo.messageId); res.status(200).json({ message: 'Form submitted successfully and saved to the database!', dataReceived: req.body }); } catch (err) { console.error('Error occurred during form submission:', err.stack || err); res.status(500).json({ message: 'An error occurred while submitting the form.', error: err.message || 'Unknown error' }); } }; return { submitForm, }; };