const express = require("express")
const fs = require('fs')
const bodyParser = require('body-parser')

const app = express()
const PORT = process.env.PORT || 8996

app.use(express.static("public"))
app.use(bodyParser.urlencoded({ extended: true }))

app.post('/subscribe', (req, res) => {
  const name = req.body.name
  const email = req.body.email
  const msg = req.body.message.replace(/(?:\r|\n|\r\n)/g, '<br>')
  const currentDate = new Date();
  fs.appendFile('./database.txt', name + ";" + email + ";" + ";" + msg + ";" + currentDate + "\n", (err) => {
    if (err) {
        console.log(err);
    }
    else {
        // Get the file contents after the append operation 
        console.log("\nFile Contents of file after append:\n",
            fs.readFileSync("./database.txt", "utf8"));
    }
  })
  res.redirect('/subscribed.html')
})

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