const nodemailer = require('nodemailer');

// Create email transporter
const createTransporter = () => {
  // For development, use console logging if no email credentials
  if (!process.env.EMAIL_USER || process.env.EMAIL_USER === 'your-email@gmail.com') {
    console.log('⚠️  Email not configured. Using console logging for development.');
    return null;
  }

  return nodemailer.createTransporter({
    host: process.env.EMAIL_HOST || 'smtp.gmail.com',
    port: parseInt(process.env.EMAIL_PORT) || 587,
    secure: false,
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_PASS
    }
  });
};

// Send booking confirmation email
async function sendBookingConfirmation(bookingData) {
  const transporter = createTransporter();
  
  const emailHtml = `
    <!DOCTYPE html>
    <html>
    <head>
      <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: #1e40af; color: white; padding: 20px; text-align: center; }
        .content { padding: 20px; background: #f8f9fa; }
        .booking-details { background: white; padding: 15px; margin: 15px 0; border-left: 4px solid #fbbf24; }
        .detail-row { display: flex; justify-content: space-between; margin: 10px 0; }
        .label { font-weight: bold; color: #1e40af; }
        .price { font-size: 24px; font-weight: bold; color: #1e40af; margin: 20px 0; }
        .footer { text-align: center; padding: 20px; font-size: 12px; color: #666; }
      </style>
    </head>
    <body>
      <div class="container">
        <div class="header">
          <h1>🚗 Booking Confirmation</h1>
          <p>Mercedes E Class 2025 Transfers</p>
        </div>
        
        <div class="content">
          <h2>Thank you for your booking!</h2>
          <p>Your transfer has been confirmed. Here are your booking details:</p>
          
          <div class="booking-details">
            <div class="detail-row">
              <span class="label">Booking Reference:</span>
              <span><strong>${bookingData.booking_reference}</strong></span>
            </div>
            <div class="detail-row">
              <span class="label">Pickup:</span>
              <span>${bookingData.pickup_location}</span>
            </div>
            <div class="detail-row">
              <span class="label">Dropoff:</span>
              <span>${bookingData.dropoff_location}</span>
            </div>
            <div class="detail-row">
              <span class="label">Date & Time:</span>
              <span>${bookingData.pickup_date} at ${bookingData.pickup_time}</span>
            </div>
            <div class="detail-row">
              <span class="label">Distance:</span>
              <span>${bookingData.distance_miles} miles</span>
            </div>
            <div class="detail-row">
              <span class="label">Passengers:</span>
              <span>${bookingData.passengers}</span>
            </div>
            <div class="detail-row">
              <span class="label">Vehicle:</span>
              <span>${bookingData.vehicle_name || 'Mercedes E-Class'}</span>
            </div>
          </div>
          
          <div class="price">
            Total Price: £${bookingData.total_price.toFixed(2)}
          </div>
          
          ${bookingData.customer_notes ? `
            <div class="booking-details">
              <span class="label">Special Requirements:</span>
              <p>${bookingData.customer_notes}</p>
            </div>
          ` : ''}
          
          <p><strong>What happens next?</strong></p>
          <ul>
            <li>Our team will review your booking</li>
            <li>You'll receive a confirmation call/SMS shortly</li>
            <li>Payment can be made on the day or via invoice</li>
          </ul>
          
          <p>If you have any questions, please contact us:</p>
          <p>
            📧 Email: <a href="mailto:booking@ashtransfer.com">booking@ashtransfer.com</a><br>
            📱 Phone: <a href="tel:+447860261578">+44 7860 261578</a>
          </p>
        </div>
        
        <div class="footer">
          <p>© ${new Date().getFullYear()} ASH Transfer - Mercedes E Class 2025 Transfers</p>
          <p>Professional airport transfer service in Greater Manchester</p>
        </div>
      </div>
    </body>
    </html>
  `;
  
  // Email to customer
  const customerEmail = {
    from: process.env.EMAIL_FROM || 'noreply@ashtransfer.com',
    to: bookingData.guest_email || bookingData.user_email,
    subject: `Booking Confirmation - ${bookingData.booking_reference}`,
    html: emailHtml
  };
  
  // Email to booking team
  const bookingTeamEmail = {
    from: process.env.EMAIL_FROM || 'noreply@ashtransfer.com',
    to: process.env.BOOKING_EMAIL || 'booking@ashtransfer.com',
    subject: `New Booking: ${bookingData.booking_reference}`,
    html: `
      <h2>New Booking Received</h2>
      <p><strong>Reference:</strong> ${bookingData.booking_reference}</p>
      <p><strong>Customer:</strong> ${bookingData.guest_name || 'N/A'}</p>
      <p><strong>Email:</strong> ${bookingData.guest_email || 'N/A'}</p>
      <p><strong>Phone:</strong> ${bookingData.guest_phone || 'N/A'}</p>
      <p><strong>Pickup:</strong> ${bookingData.pickup_location}</p>
      <p><strong>Dropoff:</strong> ${bookingData.dropoff_location}</p>
      <p><strong>Date:</strong> ${bookingData.pickup_date} at ${bookingData.pickup_time}</p>
      <p><strong>Distance:</strong> ${bookingData.distance_miles} miles</p>
      <p><strong>Passengers:</strong> ${bookingData.passengers}</p>
      <p><strong>Price:</strong> £${bookingData.total_price.toFixed(2)}</p>
      ${bookingData.customer_notes ? `<p><strong>Notes:</strong> ${bookingData.customer_notes}</p>` : ''}
      <hr>
      <p><a href="http://localhost:3000/admin.html">View in Admin Panel</a></p>
    `
  };
  
  try {
    if (!transporter) {
      // Development mode - log to console
      console.log('\n📧 Email (Customer):');
      console.log('To:', customerEmail.to);
      console.log('Subject:', customerEmail.subject);
      console.log('\n📧 Email (Booking Team):');
      console.log('To:', bookingTeamEmail.to);
      console.log('Subject:', bookingTeamEmail.subject);
      console.log('\n✅ Booking emails logged (email not configured)\n');
      return { success: true, message: 'Email logged (development mode)' };
    }
    
    // Send emails
    await transporter.sendMail(customerEmail);
    await transporter.sendMail(bookingTeamEmail);
    
    console.log(`✅ Booking emails sent for ${bookingData.booking_reference}`);
    return { success: true, message: 'Emails sent successfully' };
  } catch (error) {
    console.error('❌ Email error:', error.message);
    // Don't fail the booking if email fails
    return { success: false, message: error.message };
  }
}

module.exports = {
  sendBookingConfirmation
};
