const nodemailer = require('nodemailer');
const mailConfig = require('../configs/mailConfig');

const sendITServiceEmail = async (
  userName,
  userEmail,
  userMobile,
  packageName,
  paymentPlan,// can be array or string
  additionalInfo
) => {
  if (!userEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userEmail)) {
    throw new Error('Invalid recipient email address');
  }

  const transporter = nodemailer.createTransport(mailConfig);

  // ✅ Handle multiple packages
  let packageList = '';
  if (Array.isArray(packageName)) {
    packageList = packageName.join(', ');
  } else {
    packageList = packageName || 'N/A';
  }
  
  const paymentPlanList = Array.isArray(paymentPlan)
  ? paymentPlan.join(', ')
  : paymentPlan || 'N/A';
  
  const escapeHTML = (str) =>
  str?.replace(/[&<>"']/g, (m) => ({
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
  }[m]));


const emailHtml = `
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>IT SERVICES</title>
  <style>
    * { box-sizing: border-box; }
    body { margin:0; padding:0; font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif; background:#f8f9fa; line-height:1.2; }
    .wrapper { width:100%; padding:10px; background:#f8f9fa; }
    .container { max-width:600px; margin:0 auto; background:#fff; border-radius:8px; overflow:hidden; box-shadow:0 2px 10px rgba(0,0,0,0.05); }
    .header { background:linear-gradient(135deg,#FD561E 0%,#ff6b35 100%); color:#fff; text-align:center; padding:16px; }
    .header h1 { margin:0;font-size:24px;letter-spacing:1px; }
    .header .route { font-size:16px; margin:4px 0; }
    .header .date { font-size:14px; opacity:0.9; }
    .header .operator {
  font-size: 14px;
  font-weight: normal;
  color: #ffffff;
}

    .section { padding:16px; }
    .section-title { font-size:16px; font-weight:600; color:#2d3748; margin-bottom:12px; border-bottom:1px solid #e2e8f0; padding-bottom:4px; }
    .details-table { width:100%; border-collapse:collapse; margin-bottom:16px; }
    .details-table td { padding:8px; font-size:14px; color:#334155; border:1px solid #e2e8f0; }
    .details-table .label { background:#f1f5f9; font-weight:600; width:35%; }
    .details-table .value { background:#fff; }

    .table-container { overflow-x:auto; }
    table { width:100%; border-collapse:collapse; }
    th,td { padding:8px; font-size:14px; color:#334155; border:1px solid #e2e8f0; }
    th { background:#f1f5f9; font-weight:600; }
    .fare-table th, .fare-table td { border:none; }
    .fare-table { margin-top:8px; }
    .fare-table .total-row td { background:#FD561E; color:#fff; font-weight:600; }

    .footer { background:#f8f9fa; padding:12px; text-align:center; font-size:12px; color:#64748b; border-top:1px solid #e2e8f0; }
    .footer a { color:#FD561E; text-decoration:none; font-weight:500; }

    @media only screen and (max-width:600px) {
      .container { border-radius:0; }
      .header h1 { font-size:20px; }
      .header .route { font-size:14px; }
      .header .date { font-size:12px; }
      .section { padding:12px; }
      .section-title { font-size:14px; }
      .details-table td { padding:6px; font-size:12px; }
      th,td { padding:6px; font-size:12px; }
      .footer { font-size:10px; padding:8px; }
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="container">
            
    <p>Dear ${escapeHTML(userName)},</p>

        <p>Thank you for showing interest in <strong>BOBROS IT Services</strong>! 💻</p>

        <p>We’ve successfully received your enquiry regarding your digital service requirements. Our IT Solutions Team will contact you within <strong>24–48 hours</strong> to discuss your needs and provide tailored pricing and plans.</p>

      <!-- Enquiry Details -->
      <!-- Header -->
        <div class="header">
            <h1>BOBROS-IT SERVICES</h1>
        </div>
      <div class="section">
        <div class="section-title">Your Submitted Details:</div>
        <table class="details-table">
        
        <tr><td class="label">Name</td><td class="value">${escapeHTML(userName)}</td></tr>
         
          <tr><td class="label">Mobile</td><td class="value">${escapeHTML(userMobile)}</td></tr>
          <tr><td class="label">packageName</td><td class="value">${packageList}</td></tr>
          <tr><td class="label">paymentPlan</td><td class="value">${paymentPlanList}</td></tr>
          <tr><td class="label">additionalInfo</td><td class="value">${escapeHTML(additionalInfo || 'N/A')}</td></tr>
        </table>
      </div>
      
    <p>If you’d like to share more details or modify your enquiry, you can reply to this email or contact our IT Support team directly:</p>

        <p>
          📞 <strong>91-9133 133 456</strong><br>
          ✉️ <a href="mailto:customersupport@bobrosone.com">customersupport@bobrosone.com</a><br>
          🌐 <a href="https://bobrosone.com/">https://bobrosone.com</a>
        </p>

        <p>We’re excited to collaborate with you to bring your digital ideas to life! 🚀</p>

        <br>
        <p>Warm Regards,<br>
        <strong>Team BOBROS IT Services</strong><br>
        <em>Empowering Digital Transformations</em></p>
     

       <!-- Social Follow Section -->
    <div class="social" style="text-align:center; padding:16px 0; background:#f8f9fa;">
      <div style="font-weight:600; color:#334155; font-size:14px; margin-bottom:4px;">
        Follow us yet?
      </div>
      <div style="font-size:12px; color:#64748b; margin-bottom:12px;">
        From holiday packages to bus & flight tickets, web services and bill payments—discover it all here! 🌟
      </div>
      <a href="https://www.linkedin.com/company/bobros/posts/?feedView=all" target="_blank" style="margin:0 6px; display:inline-block;">
        <img src="cid:icon_linkedin" width="42" height="42" alt="LinkedIn" style="display:block; border:0;" />
      </a>
      <a href="https://www.facebook.com/bobrosworld" target="_blank" style="margin:0 6px; display:inline-block;">
        <img src="cid:icon_facebook" width="42" height="42" alt="Facebook" style="display:block; border:0;" />
      </a>
      <a href="https://www.instagram.com/bobrosworld?igsh=MWc0Ync0dnZvZ3kybg==" target="_blank" style="margin:0 6px; display:inline-block;">
        <img src="cid:icon_instagram" width="42" height="42" alt="Instagram" style="display:block; border:0;" />
      </a>
    </div>

    <!-- Footer -->
    <div class="footer" style="text-align:center; padding:16px; font-size:12px; color:#64748b; background:#f8f9fa;">
      Visit <a href="https://www.bobrosone.com" style="color:#FD561E; text-decoration:none;">www.bobrosone.com</a> |
      Email <a href="mailto:customersupport@bobrosone.com" style="color:#FD561E; text-decoration:none;">customersupport@bobrosone.com</a><br>
      &copy; ${new Date().getFullYear()} BOBROS Consultancy Services Pvt. Ltd.
    </div>
     
  </div>
</body>
</html>`;


  // 🧾 User confirmation email
  const userMailOptions = {
    from: `"BOBROS IT Services" <customersupport@bobrosone.com>`,
    to: userEmail,
    bcc: [
      'admin@bobrosconsultancy.com',
      'customersupport@bobrosone.com',
      'venu.oguri@bobrosone.com',
    ],
    subject: `Thank you ${userName}! We have received your IT Service enquiry.`,
    html: emailHtml,
  };

  // 🧾 Internal team notification
  const internalMailOptions = {
    from: `"BOBROS IT Service Enquiry" <customersupport@bobrosone.com>`,
    to: 'customersupport@bobrosone.com',
    bcc: [
      'admin@bobrosconsultancy.com',
      'customersupport@bobrosone.com',
      'venu.oguri@bobrosone.com',
    ],
    subject: `New IT Service Enquiry from ${userName}`,
    html: `
      <h3>New IT Service Enquiry</h3>
      
      <p><strong>Name:</strong> ${escapeHTML(userName)}</p>
<p><strong>Additional Info:</strong><br>${escapeHTML(additionalInfo)}</p>
      
      
      <p><strong>Email:</strong> ${userEmail}</p>
      <p><strong>Mobile:</strong> ${userMobile}</p>
      <p><strong>Package(s) Selected:</strong> ${packageList}</p>
      <p><strong>Payment Plan Selected:</strong> ${paymentPlanList}</p>
      ${additionalInfo ? `<p><strong>Additional Info:</strong><br>${escapeHTML(additionalInfo)}</p>` : ''}
      <br>
      <p>--<br>BOBROS IT Services Enquiry Notification</p>
    `,
  };

  try {
  await transporter.sendMail(userMailOptions);
  return await transporter.sendMail(internalMailOptions);
} catch (err) {
  console.error('Email error:', err);
  throw err;
}
};

module.exports = { sendITServiceEmail };
