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')));
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: 'mail.karyaninfratech.co.in',
  port: 26,
  secure: false,
  auth: { user: fromUser, pass: password },
  debug: true,
  logger: true
});

transporter.verify(function (error, success) {
  if (error) console.error("SMTP Server Connection Error:", error);
  else console.log("SMTP Server Connection Successful");
});

const sendEmail = (recipients, htmlTemplate, subject) => {
  return new Promise((resolve, reject) => {
    const mailOptions = {
      from: fromUser,
      to: Array.isArray(recipients) ? recipients.join(', ') : recipients,
      subject,
      html: htmlTemplate,
    };
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) return reject(error);
      resolve(info);
    });
  });
};

// Function to send lead using form-urlencoded (same as Postman)
async function sendToLeadAPI({ name, email, mobile, formType }) {
  try {
    const response = await axios.post(
      "https://helptrip.me/WebService/Lead.asmx/InsertLead",
      new URLSearchParams({
        Name: name,
        ProjectName: "square",
        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(`Error sending lead (${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')));


// Lead Form - 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: 'Please provide all required information' });
    }

    // Send to Lead API
    await sendToLeadAPI({ name, email, mobile, formType: "Book a Site Visit" });

    // Email to admin
    const htmlTemplate = `
      <h2>New Property Inquiry - Karyan Square</h2>
      <p>Hi Team</p>
      <p>A new lead has been submitted on the landing page. Here are the details:</p>
      <p><strong>Project Name:</strong> Karyan Square</p>
      <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', 'crm@globalrealtygroup.in', 'anujpandit119@gmail.com'],
      htmlTemplate,
      'New Lead From - Karyan Square'
    );

    // Email to user
    const htmlTemplateUser = `
      <p>Dear ${name},</p>
      <p>Thank you for reaching out to us regarding the "Karyan Square" project. We truly appreciate your interest.</p>
      <p>Our team is excited to assist you and we'll be in touch with you soon to discuss your requirements and provide further details about the project.</p>
      <p>If you have any immediate questions or need additional information, please feel free to contact us.</p>
      <p><strong>Karyan Infratech Group</strong></p>
    `;
    await sendEmail(email, htmlTemplateUser, 'Thank You for Your Interest in - Karyan Square');

    // ✅ Respond with JSON redirect (not res.redirect)
    return res.json({ success: true, redirect: '/thank-you' });

  } catch (error) {
    console.error('Error processing lead form:', error);
    res.status(500).json({ success: false, message: 'An error occurred', error: error.message });
  }
});

// Brochure Download
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: 'Please provide all required information' });
    }

    // Send to Lead API
    await sendToLeadAPI({ name, email, mobile: phone, formType: "Brochure Download" });

    // Email to admin
    const htmlTemplate = `
      <h2>New Property Inquiry - Karyan Square</h2>
      <p>Hi Team</p>
      <p>A new lead has been submitted on the landing page. Here are the details:</p>
      <p><strong>Project Name:</strong> Karyan Square</p>
      <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'],
      htmlTemplate,
      'Brochure Download Request - Karyan Square'
    );

    // Email to user
    const htmlTemplateUser = `
      <p>Dear ${name},</p>
      <p>Thank you for reaching out to us regarding the "Karyan Square" project. We truly appreciate your interest.</p>
      <p>Our team is excited to assist you and we'll be in touch with you soon to discuss your requirements and provide further details about the project.</p>
      <p>If you have any immediate questions or need additional information, please feel free to contact us.</p>
      <p><strong>Karyan Infratech Group</strong></p>
    `;
    await sendEmail(email, htmlTemplateUser, 'Thank You for Your Interest in - Karyan Square');

    // ✅ Respond with JSON redirect
    return res.json({ success: true, redirect: '/thank-you' });

  } catch (error) {
    console.error('Error processing brochure download:', error);
    res.status(500).json({ success: false, message: 'An error occurred. Please try again later.' });
  }
});

// Error handler
app.use((err, req, res, next) => {
  console.error("Server Error:", err.stack);
  res.status(500).json({ success: false, message: "Something went wrong on the server. Please try again later." });
});

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
