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

// 📋 LISTE
function listMedications(req, res, next) {
  const { q, onlyActive } = req.query;

  let sql = `
    SELECT 
      v.id,
      m.id AS medication_id,
      m.name AS medication,
      m.active,
      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
    WHERE 1=1
  `;

  const params = [];

  if (q) {
    sql += `
      AND (
        m.name LIKE ?
        OR f.name LIKE ?
        OR v.dosage LIKE ?
        OR v.package LIKE ?
      )
    `;
    params.push(`%${q}%`, `%${q}%`, `%${q}%`, `%${q}%`);
  }

  if (onlyActive === "1") {
    sql += " AND m.active = 1";
  }

  sql += " ORDER BY m.name, v.dosage";

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

    res.render("medications", {
      title: "Medikamentenübersicht",

      // ✅ IMMER patient-sidebar verwenden
      sidebarPartial: "partials/sidebar-empty",
      backUrl: "/dashboard",
      active: "medications",

      rows,
      query: { q, onlyActive },
      user: req.session.user,
      lang: req.session.lang || "de",
    });
  });
}

// 💾 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");
  });
}

function toggleMedication(req, res, next) {
  const id = req.params.id;

  db.query(
    "UPDATE medications SET active = NOT active WHERE id = ?",
    [id],
    (err) => {
      if (err) return next(err);
      res.redirect("/medications");
    },
  );
}

function showCreateMedication(req, res) {
  const sql = "SELECT id, name FROM medication_forms ORDER BY name";

  db.query(sql, (err, forms) => {
    if (err) return res.send("DB Fehler");

    res.render("medication_create", {
      forms,
      user: req.session.user,
      error: null,
    });
  });
}

function createMedication(req, res) {
  const { name, form_id, dosage, package: pkg } = req.body;

  if (!name || !form_id || !dosage) {
    return res.send("Pflichtfelder fehlen");
  }

  db.query(
    "INSERT INTO medications (name, active) VALUES (?, 1)",
    [name],
    (err, result) => {
      if (err) return res.send("Fehler Medikament");

      const medicationId = result.insertId;

      db.query(
        `INSERT INTO medication_variants
         (medication_id, form_id, dosage, package)
         VALUES (?, ?, ?, ?)`,
        [medicationId, form_id, dosage, pkg || null],
        (err) => {
          if (err) return res.send("Fehler Variante");

          res.redirect("/medications");
        },
      );
    },
  );
}

module.exports = {
  listMedications,
  updateMedication,
  toggleMedication,
  showCreateMedication,
  createMedication,
};
