import { NextRequest, NextResponse } from "next/server" import nodemailer from "nodemailer" import { formatPrice, type CalculationDetails } from "@/lib/calculations" import { FLOORING_TYPES } from "@/lib/constants" import { saveQuote } from "@/lib/db" interface QuoteRequestBody { customerInfo: { name: string email: string phone: string postalCode: string address?: string remarks?: string } calculationDetails: CalculationDetails } function createTransporter() { return nodemailer.createTransport({ host: process.env.SMTP_HOST, port: parseInt(process.env.SMTP_PORT || "587"), secure: process.env.SMTP_PORT === "465", auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS, }, }) } function getFlooringTypeName(type: string): string { return FLOORING_TYPES[type as keyof typeof FLOORING_TYPES]?.name || type } function formatCustomerEmail( customer: QuoteRequestBody["customerInfo"], details: CalculationDetails, trackingUrl: string ): string { const components = [] if (details.includeInsulation) components.push(`Isolering (${details.insulationThickness} cm)`) if (details.includeFloorHeating) components.push("Gulvvarme syntetisk net + Ø16 PEX (excl. tilslutning)") if (details.includeCompound) components.push(`Flydespartel (${getFlooringTypeName(details.flooringType)})`) return `

Foam King Gulve

Dit prisoverslag

Kære ${customer.name},

Tak for din interesse i Foam King Gulve. Her er dit prisoverslag baseret på de oplysninger du har indtastet:

${formatPrice(Math.round(details.totalInclVat))}
inkl. moms

Projektdetaljer

Inkluderet i prisen

Bemærk: Dette er et vejledende prisoverslag og kan variere med ±10.000 kr afhængigt af konkrete forhold på stedet.

Vi kontakter dig snarest for at aftale et uforpligtende besøg, hvor vi kan give dig et præcist og bindende tilbud.

Har du spørgsmål i mellemtiden, er du velkommen til at kontakte os.

Med venlig hilsen,
Foam King ApS
Tlf: 35 90 10 66
Email: info@foamking.dk

` } function formatFoamKingEmail( customer: QuoteRequestBody["customerInfo"], details: CalculationDetails, quoteLink: string, quoteId: number ): string { const components = [] if (details.includeInsulation) components.push( `Isolering: ${details.insulationThickness} cm (${formatPrice(Math.round(details.insulation))})` ) if (details.includeFloorHeating) { components.push(`Gulvvarme: ${formatPrice(Math.round(details.floorHeating))}`) components.push(`Syntetisk net: ${formatPrice(Math.round(details.syntheticNet))}`) } if (details.includeCompound) { components.push( `Flydespartel (${getFlooringTypeName(details.flooringType)}): ${formatPrice(Math.round(details.selfLevelingCompound))}` ) components.push( `Pumpebil (${details.compoundWeight} kg): ${formatPrice(Math.round(details.pumpTruckFee))}` ) } return `

Ny tilbudsanmodning #${quoteId}

Se detaljeret tilbud online →

Kundeoplysninger

${customer.address ? `` : ""}
Navn:${customer.name}
Email:${customer.email}
Telefon:${customer.phone}
Postnummer:${customer.postalCode}
Adresse:${customer.address}
${customer.remarks ? `
Bemærkninger fra kunden:
${customer.remarks}
` : ""}

Projektspecifikationer

Gulvareal:${details.area} m²
Gulvhøjde:${details.height} cm
Isoleringstykkelse:${details.insulationThickness} cm
Spartelvægt:${details.compoundWeight} kg
Afstand (tur/retur):${details.distance} km

Prisberegning

${components .map((c) => { const [label, price] = c.split(": ") return `` }) .join("")} ${details.bridgeFee > 0 ? `` : ""}
${label}:${price}
Startgebyr:${formatPrice(Math.round(details.startFee))}
Subtotal:${formatPrice(Math.round(details.subtotal))}
Afdækning (0.7%):${formatPrice(Math.round(details.coveringFee))}
Affald (0.25%):${formatPrice(Math.round(details.wasteFee))}
Transport:${formatPrice(Math.round(details.transport))}
Storebælt:${formatPrice(details.bridgeFee)}
Total ekskl. moms:${formatPrice(Math.round(details.totalExclVat))}
Moms (25%):${formatPrice(Math.round(details.vat))}
Total inkl. moms:${formatPrice(Math.round(details.totalInclVat))}

Denne anmodning er genereret automatisk fra prisberegneren på beregner.foamking.dk
Tidspunkt: ${new Date().toLocaleString("da-DK", { timeZone: "Europe/Copenhagen" })}

` } export async function POST(request: NextRequest) { try { const body: QuoteRequestBody = await request.json() const { customerInfo, calculationDetails } = body if (!customerInfo || !calculationDetails) { return NextResponse.json({ error: "Manglende data" }, { status: 400 }) } // Save quote to database const { id: quoteId, slug } = saveQuote({ postalCode: customerInfo.postalCode, address: customerInfo.address, area: calculationDetails.area, height: calculationDetails.height, includeFloorHeating: calculationDetails.includeFloorHeating, flooringType: calculationDetails.flooringType, customerName: customerInfo.name, customerEmail: customerInfo.email, customerPhone: customerInfo.phone, remarks: customerInfo.remarks, totalExclVat: calculationDetails.totalExclVat, totalInclVat: calculationDetails.totalInclVat, }) // Generate the quote link const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "https://beregner.foamking.dk" const quoteLink = `${baseUrl}/tilbud/${slug}` const transporter = createTransporter() // Get Foam King recipients (supports comma-separated emails) const foamKingEmails = (process.env.EMAIL_TO || "info@foamking.dk") .split(",") .map((email) => email.trim()) .filter((email) => email.length > 0) const fromName = process.env.EMAIL_FROM_NAME || "Foam King Prisberegner" // Generate tracking URL for email open tracking const trackingUrl = `${baseUrl}/api/track/${quoteId}` // Send email to customer await transporter.sendMail({ from: `"${fromName}" <${process.env.SMTP_USER}>`, to: customerInfo.email, subject: "Dit prisoverslag fra Foam King Gulve", html: formatCustomerEmail(customerInfo, calculationDetails, trackingUrl), }) // Send email to Foam King await transporter.sendMail({ from: `"${fromName}" <${process.env.SMTP_USER}>`, to: foamKingEmails, replyTo: customerInfo.email, subject: `Tilbud #${quoteId}: ${customerInfo.name} - ${customerInfo.postalCode} - ${calculationDetails.area} m²`, html: formatFoamKingEmail(customerInfo, calculationDetails, quoteLink, quoteId), }) return NextResponse.json({ success: true, message: "Tak! Vi har modtaget din anmodning og sendt en bekræftelse til din email.", }) } catch (error) { console.error("Quote request error:", error) return NextResponse.json({ error: "Der opstod en fejl. Prøv igen senere." }, { status: 500 }) } }