// busapi/model/printticketEmailModel.js

const nodemailer = require('nodemailer');
const mailConfig = require('../configs/mailConfig');
const ticketModel = require('../../busapi/model/ticketModel');
const path = require('path');

const facebookPath = path.join(__dirname, '..', 'assets', 'facebook.png');
const instagramPath = path.join(__dirname, '..', 'assets', 'instagram.png');
const linkedInPath  = path.join(__dirname, '..', 'assets', 'linkedin.png');



async function printticketEmailModel(trimmedTin) {
  const data = await ticketModel.printTicket(trimmedTin);
  if (!data) return null;

  // Extract core fields
  const {
    bookingFee,
    busType,
    travels,
    cancellationPolicy,
    vendorPnr,
    doj,
    status,
    pickUpContactNo,
    pickupLocation,
    pickUpLocationAddress,
    pickupLocationLandmark,
    sourceCity,
    destinationCity
  } = data;

  let items = data.inventoryItems;
  if (!Array.isArray(items)) {
    items = items ? [items] : [];
  }

  // Determine passenger email
  const pmail = items[0]?.passenger?.email || '';
  console.log('email sent to print TICK:', pmail);

  if (!pmail) {
    throw new Error(`No passenger email found for TIN ${trimmedTin}`);
  }

  // Time formatting
  const pickupTimeMin = Number(data.pickupTime);
  const reportingTimeMin = pickupTimeMin - 15;
  function decodeTime(mins) {
    let h = Math.floor(mins / 60) % 24;
    const m = mins % 60;
    const period = h >= 12 ? 'PM' : 'AM';
    h = h % 12 || 12;
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')} ${period}`;
  }
  const formattedPickupTime = decodeTime(pickupTimeMin);
  const formattedReportingTime = decodeTime(reportingTimeMin);

  // Format journey date
  console.log('RAW DOJ VALUE:', doj, typeof doj);
  const dateObject = new Date(doj);
  const formattedDate = dateObject.toLocaleDateString('en-GB', {
    day: '2-digit', month: 'short', year: 'numeric'
  });

  // Build passenger rows (each passenger gets their own row)
  const passengerRows = items.map(item => `
    <tr>
      <td>${item.passenger.name}</td>
      <td>${item.seatName}</td>
      <td>Confirmed</td>
    </tr>
  `).join('');

  // Calculate fare totals
  const totalBaseFare = items.reduce((sum, i) => sum + parseFloat(i.baseFare || 0), 0);
  const totalServiceTax = items.reduce((sum, i) => sum + parseFloat(i.serviceTax || 0), 0);
  const totalFare = items.reduce((sum, i) => sum + parseFloat(i.fare || 0), 0);

  // Build cancellation policy rows with better formatting
  const cancellationRows = cancellationPolicy.split(';').map(segment => {
    const [start, end, percent] = segment.split(':');
    let timeDesc = '';
    
    if (end && end !== '-1' && start) {
      timeDesc = `${end}-${start} hours before`;
    } else if (start) {
      if (start === '0') {
        timeDesc = 'Less than 1 hour before';
      } else {
        timeDesc = `More than ${start} hours before`;
      }
    }
    
    return `
      <tr>
        <td>${timeDesc}</td>
        <td>${percent}%</td>
      </tr>
    `;
  }).join('');

  const trip = `${sourceCity} to ${destinationCity}`;

  // Enhanced HTML template

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>${trip}</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">
    <!-- Header -->
<div class="header">
  <h1>BOBROS-BUS TICKET</h1>
  <div class="route">${sourceCity} → ${destinationCity}</div>
  <div class="operator">Bus Operator: ${travels}</div>
  <div class="date">Date of Journey: ${formattedDate}</div>
  <div class="reporting-time">Reporting Time: ${formattedReportingTime}</div>
</div>


      <!-- Passenger Details -->
      <div class="section">
        <div class="section-title">Passenger Details</div>
        <div class="table-container">
          <table>
            <thead>
              <tr><th>Name</th><th>Seat No.</th><th>Status</th></tr>
            </thead>
            <tbody>${passengerRows}</tbody>
          </table>
        </div>
      </div>

      <!-- Trip Details -->
      <div class="section">
        <div class="section-title">Trip Details</div>
        <table class="details-table">
        <tr><td class="label">Booking ID</td><td class="value">${trimmedTin}</td></tr>
         <tr>
            <td class="label">Booking Status</td>
            <td class="value" style="color:${status === 'CANCELLED' ? 'red' : 'green'};">
              <strong>${status}</strong>
            </td>
          </tr>
          <tr><td class="label">Bus Operator</td><td class="value">${travels}</td></tr>
          <tr><td class="label">Bus Type</td><td class="value">${busType}</td></tr>
          <tr><td class="label">Pick Up Location</td><td class="value">${pickupLocation}</td></tr>
          <tr><td class="label">Pick Up Time</td><td class="value">${formattedPickupTime}</td></tr>
          <tr><td class="label">Reporting Time</td><td class="value">${formattedReportingTime}</td></tr>
          <tr><td class="label">Contact Number</td><td class="value">${pickUpContactNo}</td></tr>
          <tr><td class="label">PNR Number</td><td class="value">${vendorPnr}</td></tr>
          
          <tr><td class="label">Email Sent To</td><td class="value">${pmail}</td></tr>
        </table>
      </div>

      

      <!-- Fare Breakdown -->
      <div class="section">
        <div class="section-title">Fare Breakdown</div>
        <div class="table-container fare-table">
          <table>
            <tbody>
              <tr><td>Description</td><td>Amount (₹)</td></tr>
              <tr><td>Base Fare</td><td>₹ ${totalBaseFare.toFixed(2)}</td></tr>
              <tr><td>Service Tax</td><td>₹ ${totalServiceTax.toFixed(2)}</td></tr>
              <tr class="total-row"><td>Total Fare</td><td>₹ ${totalFare.toFixed(2)}</td></tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Cancellation Policy -->
      <div class="section">
        <div class="section-title">Cancellation Policy</div>
        <div class="table-container">
          <table>
            <thead><tr><th>Time Before Journey</th><th>Cancellation fee %</th></tr></thead>
            <tbody>${cancellationRows}</tbody>
          </table>
        </div>
      </div>

      <!-- Terms & Conditions -->
<div class="section">
  <div class="section-title">Terms &amp; Conditions</div>
  <div style="font-size:14px; color:#475569; line-height:1.6; margin-top:12px;">
    <p style="margin-bottom:12px;">
      <strong>BOBROS</strong> acts purely as a ticket‑booking agent and does not operate any buses directly. To give you the best choice of departure times, operators, and fares, we partner with multiple bus companies and inventory‑sharing services.
    </p>

    <p style="margin-bottom:12px;">
      We recommend booking with operators whose service standards you know and trust. While we facilitate your booking, the bus operator is ultimately responsible for on‑board service, schedule adherence, and amenities.
    </p>

    <p style="margin-bottom:12px;">
      <strong>Company Details:</strong><br>
      BOBROS Consultancy Services Pvt. Ltd. (CIN: U74999AP2013PTC090141)<br>
      Registered Office: 1‑232, Mulakaluru, Narasaraopet, Andhra Pradesh – 522 601
    </p>

    <p style="margin-bottom:0;">
      For our full Terms &amp; Conditions and Cancellation Policy, please visit 
      <a href="https://www.bobrosone.com" style="color:#FD561E; text-decoration:none;">www.bobrosone.com</a> 
      or call <strong>91‑9133 133 456</strong> (9:30 AM–7:00 PM Mon–Sat, excl. public holidays).
    </p>
  </div>
</div>


      <!-- Our Responsibilities -->
      <div class="section">
        <div class="section-title">Our Responsibilities</div>
        <ul style="margin:12px 0 0 20px;color:#334155;font-size:14px;line-height:1.6;">
          <li>Issuing a valid ticket that will be accepted by the bus operator.</li>
          <li>Providing refunds and support in case of cancellation.</li>
          <li>Offering customer support if there are delays or other inconveniences.</li>
        </ul>
      </div>

      <!-- What We Are Not Responsible For -->
      <div class="section">
        <div class="section-title">What We Are Not Responsible For</div>
        <ul style="margin:12px 0 0 20px;color:#334155;font-size:14px;line-height:1.6;">
          <li>The bus operator’s vehicle not departing or arriving on time.</li>
          <li>Bus‑operator staff demeanor or conduct.</li>
          <li>Seat quality or onboard amenities provided by the bus operator.</li>
          <li>Cancellations by the bus operator for reasons beyond our control.</li>
        </ul>
        <p style="font-size:14px;color:#475569;line-height:1.6;margin-top:12px;">
          We will, however, make every effort to address your concerns with the relevant service provider.
        </p>
      </div>

       <!-- 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>
`;


  // Send email
  const transporter = nodemailer.createTransport(mailConfig);
  const mailOptions = {
    from: `"BOBROS" <customersupport@bobrosone.com>`,
    to: pmail,
    bcc: ['admin@bobrosconsultancy.com', 'customersupport@bobrosone.com'],
    subject: `Your Booking Confirmation: ${vendorPnr}`,
    html: emailHtml,
    attachments: [
      
      {
        filename: 'facebook.png',
        path: facebookPath,
        cid: 'icon_facebook'
      },
      {
        filename: 'instagram.png',
        path: instagramPath,
        cid: 'icon_instagram'
      },
      {
        filename: 'linkedin.png',
        path: linkedInPath,
        cid: 'icon_linkedin'
      }
    ]
  };
  
  await transporter.sendMail(mailOptions);

  return { ...data, pmail };
}

module.exports = { printticketEmailModel };