const db = require('../lib/connection');
const path = require('path');
const { sendRegistrationEmail } = require('../lib/service');

exports.handleFormSubmission = (req, res) => {
  const { firstName, surname, businessName, cacRegistered, slotOption } = req.body;
  const photo = req.file ? req.file.filename : null;

  const sql = `
    INSERT INTO registrations 
    (first_name, surname, business_name, cac_registered, slot_option, photo)
    VALUES (?, ?, ?, ?, ?, ?)
  `;

  db.query(
    sql,
    [firstName, surname, businessName, cacRegistered, slotOption, photo],
    async (err, result) => {
      if (err) {
        console.error('Insert error:', err);
        return res.status(500).json({ error: 'Database insert failed' });
      }

      try {
        await sendRegistrationEmail({ firstName, surname, businessName, cacRegistered, slotOption });
        console.log('Email notification sent');
      } catch (mailErr) {
        console.error('Email send error:', mailErr);
      }

      res.status(200).json({ message: 'Form submitted successfully' });
    }
  );
};
