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

function addPatientService(req, res) {
  const patientId = req.params.id;
  const { service_id, quantity } = req.body;

  if (!service_id) {
    req.session.flash = {
      type: "warning",
      message: "Bitte eine Leistung auswählen"
    };
    return res.redirect(`/patients/${patientId}/overview`);
  }

  db.query(
    "SELECT price FROM services WHERE id = ?",
    [service_id],
    (err, results) => {
      if (err || results.length === 0) {
        req.session.flash = {
          type: "danger",
          message: "Leistung nicht gefunden"
        };
        return res.redirect(`/patients/${patientId}/overview`);
      }

      const price = results[0].price;

      db.query(
        `INSERT INTO patient_services
        (patient_id, service_id, quantity, price, service_date, created_by)
        VALUES (?, ?, ?, ?, CURDATE(), ?) `,
        [
            patientId,
            service_id,
            quantity || 1,
            price,
            req.session.user.id // behandelnder Arzt
        ],
        err => {
          if (err) {
            req.session.flash = {
              type: "danger",
              message: "Fehler beim Speichern der Leistung"
            };
            return res.redirect(`/patients/${patientId}/overview`);
          }

          req.session.flash = {
            type: "success",
            message: "Leistung hinzugefügt"
          };

          res.redirect(`/patients/${patientId}/overview`);
        }
      );
    }
  );
}

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

  db.query(
    "DELETE FROM patient_services WHERE id = ?",
    [id],
    () => res.redirect("/services/open")
  );
}

function updatePatientServicePrice(req, res) {
  const id = req.params.id;
  const { price } = req.body;

  db.query(
    "UPDATE patient_services SET price_override = ? WHERE id = ?",
    [price, id],
    () => res.redirect("/services/open")
  );
}

function updatePatientServiceQuantity(req, res) {
  const id = req.params.id;
  const { quantity } = req.body;

  if (!quantity || quantity < 1) {
    return res.redirect("/services/open");
  }

  db.query(
    "UPDATE patient_services SET quantity = ? WHERE id = ?",
    [quantity, id],
    () => res.redirect("/services/open")
  );
}

module.exports = { 
  addPatientService,
  deletePatientService,
  updatePatientServicePrice,
  updatePatientServiceQuantity
 };
