const express = require("express")
const mysql = require("mysql2")
const session = require("express-session")
const path = require("path")

const app = express()

app.use(express.urlencoded({ extended: true }))
app.use(express.json())

app.use(session({
  secret: "secretkey",
  resave: false,
  saveUninitialized: true
}))

app.use(express.static("public"))

const db = mysql.createConnection({
  host: "localhost",
  user: "danielld2027_nodeuser",
  password: "Drivehub2026!",
  database: "danielld2027_drivehub"
})
db.connect(err => {
  if (err) throw err
  console.log("mysql connected")
})

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "public", "main.html"))
})
app.post("/add-car", (req, res) => {
  const { make, model, year, price } = req.body

  const sql = `
    INSERT INTO cars (make, model, year, price)
    VALUES (?, ?, ?, ?)
  `

  db.query(sql, [make, model, year, price], (err) => {
    if (err) throw err
    res.send("car added")
  })
})

app.get("/cars", (req, res) => {
  const sql = "SELECT * FROM cars"

  db.query(sql, (err, results) => {
    if (err) throw err
    res.json(results)
  })
})

app.listen(3000, () => {
  console.log("server running on port 3000")
})

