const db = require("../db");
const ejs = require("ejs");
const path = require("path");
const fs = require("fs");
const pdf = require("html-pdf-node");

async function createInvoicePdf(req, res) {
  const patientId = req.params.id;

  try {
    // 1️⃣ Patient laden
    const [[patient]] = await db.promise().query(
      "SELECT * FROM patients WHERE id = ?",
      [patientId]
    );

    if (!patient) {
      return res.status(404).send("Patient nicht gefunden");
    }

    // 2️⃣ Leistungen laden (noch nicht abgerechnet)
    const [rows] = await db.promise().query(`
      SELECT
        ps.quantity,
        COALESCE(ps.price_override, s.price) AS price,

        CASE
          WHEN UPPER(TRIM(?)) = 'ES'
            THEN COALESCE(NULLIF(s.name_es, ''), s.name_de)
          ELSE s.name_de
        END AS name

      FROM patient_services ps
      JOIN services s ON ps.service_id = s.id
      WHERE ps.patient_id = ?
        AND ps.invoice_id IS NULL
    `, [patient.country, patientId]);

    if (rows.length === 0) {
      return res.send("Keine Leistungen vorhanden");
    }

    const services = rows.map(s => ({
      quantity: Number(s.quantity),
      name: s.name,
      price: Number(s.price),
      total: Number(s.price) * Number(s.quantity)
    }));

    const total = services.reduce((sum, s) => sum + s.total, 0);

    // 3️⃣ HTML aus EJS erzeugen
    const html = await ejs.renderFile(
      path.join(__dirname, "../views/invoices/invoice.ejs"),
      { patient, services, total }
    );

    // 4️⃣ PDF erzeugen
    const pdfBuffer = await pdf.generatePdf(
      { content: html },
      { format: "A4" }
    );

    // 5️⃣ Dateiname + Pfad
    const date = new Date().toISOString().split("T")[0]; // YYYY-MM-DD
    const fileName = `invoice_${patientId}_${date}.pdf`;
    const outputPath = path.join(__dirname, "..", "documents", fileName);

    // 6️⃣ PDF speichern
    fs.writeFileSync(outputPath, pdfBuffer);

    // 7️⃣ OPTIONAL: Rechnung in DB speichern (empfohlen)
    const [invoiceResult] = await db.promise().query(`
    INSERT INTO invoices
    (patient_id, invoice_date, total_amount, file_path, created_by, status)
      VALUES (?, CURDATE(), ?, ?, ?, 'open')
    `, [
      patientId,
      total,
      `documents/${fileName}`,
      req.session.user.id
    ]);

    const invoiceId = invoiceResult.insertId;

    // 8️⃣ Leistungen verknüpfen
    await db.promise().query(`
      UPDATE patient_services
      SET invoice_id = ?
      WHERE patient_id = ?
        AND invoice_id IS NULL
    `, [invoiceId, patientId]);

    // 9️⃣ PDF anzeigen
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      `inline; filename="${fileName}"`
    );

    res.send(pdfBuffer);

  } catch (err) {
    console.error("❌ PDF ERROR:", err);
    res.status(500).send("Fehler beim Erstellen der Rechnung");
  }
}

module.exports = { createInvoicePdf };
