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

/**
 * Helper: leere Strings → NULL
 */
const safe = (v) => {
  if (typeof v !== "string") return null;
  const t = v.trim();
  return t.length > 0 ? t : null;
};

/**
 * GET: Firmendaten anzeigen
 */
async function getCompanySettings(req, res) {
  try {
    const [[company]] = await db
      .promise()
      .query("SELECT * FROM company_settings LIMIT 1");

    res.render("admin/company-settings", {
      layout: "layout",                 // 🔥 wichtig
      title: "Firmendaten", // 🔥 DAS FEHLTE
      active: "companySettings",         // 🔥 Sidebar aktiv
      sidebarPartial: "partials/admin-sidebar",

      company: company || {},

      user: req.session.user,            // 🔥 konsistent
      lang: req.session.lang || "de"
      // t kommt aus res.locals
    });
  } catch (err) {
    console.error(err);
    res.status(500).send("Datenbankfehler");
  }
}

/**
 * POST: Firmendaten speichern (INSERT oder UPDATE)
 */
async function saveCompanySettings(req, res) {
  try {
    const data = req.body;

    // 🔒 Pflichtfeld
    if (!data.company_name || data.company_name.trim() === "") {
      return res.status(400).send("Firmenname darf nicht leer sein");
    }

    // 🖼 Logo (optional)
    let logoPath = null;
    if (req.file) {
      logoPath = "/images/" + req.file.filename;
    }

    // 🔍 Existierenden Datensatz laden
    const [[existing]] = await db.promise().query(
      "SELECT * FROM company_settings LIMIT 1"
    );

    const oldData = existing ? { ...existing } : null;

    if (existing) {
      // 🔁 UPDATE
      await db.promise().query(
        `
        UPDATE company_settings SET
          company_name = ?,
          company_legal_form = ?,
          company_owner = ?,
          street = ?,
          house_number = ?,
          postal_code = ?,
          city = ?,
          country = ?,
          phone = ?,
          email = ?,
          vat_id = ?,
          bank_name = ?,
          iban = ?,
          bic = ?,
          invoice_footer_text = ?,
          invoice_logo_path = ?
        WHERE id = ?
        `,
        [
          data.company_name.trim(),          // NOT NULL
          safe(data.company_legal_form),
          safe(data.company_owner),
          safe(data.street),
          safe(data.house_number),
          safe(data.postal_code),
          safe(data.city),
          safe(data.country),
          safe(data.phone),
          safe(data.email),
          safe(data.vat_id),
          safe(data.bank_name),
          safe(data.iban),
          safe(data.bic),
          safe(data.invoice_footer_text),
          logoPath || existing.invoice_logo_path,
          existing.id
        ]
      );
    } else {
      // ➕ INSERT
      await db.promise().query(
        `
        INSERT INTO company_settings (
          company_name,
          company_legal_form,
          company_owner,
          street,
          house_number,
          postal_code,
          city,
          country,
          phone,
          email,
          vat_id,
          bank_name,
          iban,
          bic,
          invoice_footer_text,
          invoice_logo_path
        ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
        `,
        [
          data.company_name.trim(),          // NOT NULL
          safe(data.company_legal_form),
          safe(data.company_owner),
          safe(data.street),
          safe(data.house_number),
          safe(data.postal_code),
          safe(data.city),
          safe(data.country),
          safe(data.phone),
          safe(data.email),
          safe(data.vat_id),
          safe(data.bank_name),
          safe(data.iban),
          safe(data.bic),
          safe(data.invoice_footer_text),
          logoPath
        ]
      );
    }

    // 📝 Audit-Log
    await db.promise().query(
      `
      INSERT INTO company_settings_logs (changed_by, old_data, new_data)
      VALUES (?, ?, ?)
      `,
      [
        req.user.id,
        JSON.stringify(oldData || {}),
        JSON.stringify(data)
      ]
    );

    res.redirect("/admin/company-settings");

  } catch (err) {
    console.error("❌ COMPANY SETTINGS ERROR:", err);
    res.status(500).send("Fehler beim Speichern der Firmendaten");
  }
}

module.exports = {
  getCompanySettings,
  saveCompanySettings
};
