const express = require("express");
const dotenv = require("dotenv");
const path = require("path");
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");
const axios = require("axios");

// Load environment variables
dotenv.config();

const app = express();
const hostingPath = __dirname;

// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(hostingPath, "public")));

// Request logging
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
  next();
});

// Email config
const fromUser = "no-reply@karyaninfratech.co.in";
const password = "adminrl@1234";

const transporter = nodemailer.createTransport({
  host: "ns41.interactivedns.com",
  port: 25,
  secure: false,
  auth: { user: fromUser, pass: password },
  debug: true,
  logger: true,
});

transporter.verify((error, success) => {
  if (error) console.error("SMTP Error:", error);
  else console.log("SMTP Server Connection Successful");
});

// Reusable email sender
const sendEmail = (recipients, htmlTemplate, subject) => {
  return transporter.sendMail({
    from: fromUser,
    to: Array.isArray(recipients) ? recipients.join(", ") : recipients,
    subject,
    html: htmlTemplate,
  });
};

// Lead API (ASMX) submission
const sendToLeadAPI = async ({ name, email, mobile, formType }) => {
  try {
    const response = await axios.post(
      "https://helptrip.me/WebService/Lead.asmx/InsertLead",
      new URLSearchParams({
        Name: name,
        ProjectName: "Karyan Avenue-IV",
        City: "Gzb",
        Location: "NCR",
        Remark: `Lead from ${formType} Form`,
        Source: "Landing Page",
        Email: email,
        Mobile: mobile,
      }).toString(),
      { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
    );
    console.log(`Lead API Response for ${formType}:`, response.data);
  } catch (err) {
    console.error(`Lead API Error (${formType}):`, err.message);
  }
};

// Routes
app.get("/", (req, res) => {
  res.sendFile(path.join(hostingPath, "public", "index.html"));
});

app.get("/thank-you", (req, res) => {
  res.sendFile(path.join(hostingPath, "public", "thankyou.html"));
});

// Form 1 - Book a Site Visit
app.post("/api/lead-form", async (req, res) => {
  try {
    const { name, mobile, email } = req.body;
    if (!name || !mobile || !email) {
      return res.status(400).json({ success: false, message: "Missing fields" });
    }

    // Send to ASMX Lead API
    await sendToLeadAPI({ name, email, mobile, formType: "Book a Site Visit" });

    // Admin email
    const htmlAdmin = `
      <h2>New Lead - Karyan Avenue-IV</h2>
      <p><strong>Form Type:</strong> Book a Site Visit</p>
      <p><strong>Name:</strong> ${name}</p>
      <p><strong>Mobile:</strong> ${mobile}</p>
      <p><strong>Email:</strong> ${email}</p>
      <p><strong>Date:</strong> ${new Date().toLocaleString()}</p>
    `;
    await sendEmail(
      ["sales@globalrealtygroup.in", "amit.soam@globalrealtygroup.in"],
      htmlAdmin,
      "New Lead From - Karyan Avenue-IV"
    );

    // User email
    const htmlUser = `
      <p>Dear ${name},</p>
      <p>Thank you for your interest in <b>Karyan Avenue-IV</b>. Our team will contact you shortly.</p>
      <p><b>Karyan Infratech Group</b></p>
    `;
    await sendEmail(email, htmlUser, "Thank You - Karyan Avenue-IV");

    return res.redirect("/thank-you");
  } catch (error) {
    console.error("Error in lead form:", error);
    return res.status(500).json({ success: false, message: "Server error" });
  }
});

// Form 2 - Download Brochure
app.post("/api/download-broachur", async (req, res) => {
  try {
    const { name, email, phone } = req.body;
    if (!name || !email || !phone) {
      return res.status(400).json({ success: false, message: "Missing fields" });
    }

    // Send to ASMX Lead API
    await sendToLeadAPI({ name, email, mobile: phone, formType: "Brochure Download" });

    // Admin email
    const htmlAdmin = `
      <h2>New Lead - Karyan Avenue-IV</h2>
      <p><strong>Form Type:</strong> Brochure Download</p>
      <p><strong>Name:</strong> ${name}</p>
      <p><strong>Email:</strong> ${email}</p>
      <p><strong>Phone:</strong> ${phone}</p>
      <p><strong>Date:</strong> ${new Date().toLocaleString()}</p>
    `;
    await sendEmail(
      ["sales@globalrealtygroup.in", "amit.soam@globalrealtygroup.in"],
      htmlAdmin,
      "Brochure Download Request - Karyan Avenue-IV"
    );

    // User email with brochure link
    const htmlUser = `
      <p>Dear ${name},</p>
      <p>Thank you for your interest in <b>Karyan Avenue-IV</b>. Please find the brochure below:</p>
      <p><a href="https://karyaninfratech.co.in/images/kcB.pdf" target="_blank">📄 Download Brochure</a></p>
      <p><b>Karyan Infratech Group</b></p>
    `;
    await sendEmail(email, htmlUser, "Brochure - Karyan Avenue-IV");

    return res.redirect("/thank-you");
  } catch (error) {
    console.error("Error in brochure form:", error);
    return res.status(500).json({ success: false, message: "Server error" });
  }
});

// Global error handler
app.use((err, req, res, next) => {
  console.error("Unhandled Server Error:", err);
  res.status(500).json({ success: false, message: "Something went wrong" });
});

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
