// Import necessary libraries
const express = require('express');
const nodemailer = require('nodemailer');
const dotenv = require('dotenv');

// Initialize environment variables
dotenv.config();

// Create the Express app
const app = express();
app.use(express.json());

// Sample member data (You can replace this with a database connection)
const members = [
  { name: 'John Doe', email: 'john@example.com', endDate: '2024-09-30' },
  { name: 'Jane Doe', email: 'jane@example.com', endDate: '2024-10-05' }
];

// Create reusable transporter object using SMTP transport (Gmail example)
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: process.env.EMAIL_USER, // Your Gmail address
    pass: process.env.EMAIL_PASS  // Your Gmail password (or app password)
  }
});

// Function to send reminder email
async function sendReminderEmail(member) {
  try {
    let info = await transporter.sendMail({
      from: '"Gym Management" <your-email@gmail.com>', // Sender address
      to: member.email, // List of receivers
      subject: 'Gym Membership Expiration Reminder', // Subject line
      text: `Dear ${member.name},\n\nYour gym membership is about to expire on ${member.endDate}. Please renew to continue enjoying our services.\n\nBest regards,\nGym Management`, // Plain text body
      html: `<p>Dear ${member.name},</p><p>Your gym membership is about to expire on <b>${member.endDate}</b>. Please renew to continue enjoying our services.</p><p>Best regards,<br>Gym Management</p>` // HTML body
    });
    console.log(`Reminder email sent to ${member.email}`);
  } catch (error) {
    console.error('Error sending email:', error);
  }
}

// Function to check for expiring memberships
function checkExpiringMemberships() {
  const today = new Date();
  const daysBeforeExpiration = 7; // Notify 7 days before expiration

  members.forEach(member => {
    const endDate = new Date(member.endDate);
    const diffTime = endDate - today;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); // Convert milliseconds to days

    // Send reminder if membership is expiring within the next 7 days
    if (diffDays > 0 && diffDays <= daysBeforeExpiration) {
      sendReminderEmail(member);
    }
  });
}

// Set up a cron job or interval to check memberships daily
setInterval(checkExpiringMemberships, 24 * 60 * 60 * 1000); // Check once per day

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  checkExpiringMemberships(); // Initial check when server starts
});

