"use server"

import { sendEmail, formatFormDataAsHTML } from "@/lib/email"

export async function submitProgramApplication(formData: FormData) {
  try {
    const data = {
      "Form Type": "Program Application",
      Program: formData.get("program") as string,
      "Full Name": formData.get("fullName") as string,
      Email: formData.get("email") as string,
      Phone: formData.get("phone") as string,
      "Date of Birth": formData.get("dateOfBirth") as string,
      City: formData.get("city") as string,
      Address: formData.get("address") as string,
      "Educational Background": formData.get("education") as string,
      "Current Employment Status": formData.get("employmentStatus") as string,
      "Why Join This Program": formData.get("motivation") as string,
      "What You Hope to Achieve": formData.get("goals") as string,
      "Emergency Contact Name": formData.get("emergencyName") as string,
      "Emergency Contact Phone": formData.get("emergencyPhone") as string,
      "Privacy Consent": formData.get("privacyConsent") === "true" ? "Yes" : "No",
      "Submitted At": new Date().toLocaleString("en-ZA", { timeZone: "Africa/Johannesburg" }),
    }

    const emailBody = formatFormDataAsHTML(data)
    await sendEmail({
      subject: `New ${data.Program} Application - ${data["Full Name"]}`,
      body: emailBody,
      replyTo: data.Email,
    })

    return {
      success: true,
      message: "Thank you for your application! We'll review it and contact you soon.",
    }
  } catch (error) {
    console.error("Program application error:", error)
    return {
      success: false,
      message: "There was an error submitting your application. Please try again.",
    }
  }
}
