const db = require("../db");

// 📋 LISTE
function listMedications(req, res, next) {
  const sql = `
    SELECT
      v.id,
      m.name AS medication,
      f.name AS form,
      v.dosage,
      v.package
    FROM medication_variants v
    JOIN medications m ON v.medication_id = m.id
    JOIN medication_forms f ON v.form_id = f.id
    ORDER BY m.name, v.dosage
  `;

  db.query(sql, (err, rows) => {
    if (err) return next(err);

    res.render("medications", {
      rows,
      user: req.session.user
    });
  });
}

// 💾 UPDATE
function updateMedication(req, res, next) {
  const { medication, form, dosage, package: pkg } = req.body;
  const id = req.params.id;

  const sql = `
    UPDATE medication_variants
    SET
      dosage = ?,
      package = ?
    WHERE id = ?
  `;

  db.query(sql, [dosage, pkg, id], err => {
    if (err) return next(err);

    req.session.flash = {  type: "success",  message: "Medikament gespeichert"};
    res.redirect("/medications");
  });
}

module.exports = {
  listMedications,
  updateMedication
};

