const eventDbService = require("../services/eventDbService");
const newsletterDbService = require("../services/newsLetterDbService");
const nodemailer = require("nodemailer");

const getAllEvents = async (req, res) => {
  try {
    const baseURL = `${req.protocol}://${req.get("host")}/event-upload/`;
    const data = await eventDbService.getAllEvents();
    const result = data.map((item) => ({
      ...item,
      Img_url: baseURL + item.Image,
    }));
    res.status(200).json(result);
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when fetching events!",
      error: err.message,
    });
  }
};

const addEvent = async (req, res) => {
  try {
    const { Date, Title, Description, BlogCategory_idBlogCategory } = req.body;
    const Image = req.file?.filename;
    const add = await eventDbService.addEvent(
      Date,
      Title,
      Description,
      Image,
      BlogCategory_idBlogCategory
    );

    const insertId1 = add.insertId;
    const datanewusers = await newsletterDbService.getall();

    const transporter = nodemailer.createTransport({
      host: "premium54.web-hosting.com",
      port: 465,
      secure: true,
      auth: {
        user: "newsletter@gammatourz.com",
        pass: ",LAOn}D@F-[f",
      },
    });

    await Promise.all(
      datanewusers.map(async (item) => {
        const mailOptionsSubscriber = {
          from: "Gamma Tourz <newsletter@gammatourz.com>",
          to: item.Email,
          subject: "📢 New Blog Update from Gamma Tourz!",
          html: `
  <div style="font-family: Arial, sans-serif; background-color: #f9fafb; padding: 30px;">
    <div style="max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); overflow: hidden;">
      
      <!-- Header with Logo -->
      <div style="background-color: #1e3a8a; padding: 20px; text-align: center;">
      <a href="https://gammatourz.com"><img src="https://i.ibb.co/23qWxhXN/gammafoot.png" alt="gammafoot" border="0"></a>
        <h1 style="color: #ffffff; font-weight: 700; margin: 0;">Gamma Tourz Blog</h1>
      </div>

      <!-- Blog Update Title -->
      <div style="padding: 25px; color: #333333;">
        <h2 style="color: #1e3a8a; margin-top: 0;">📖 Check Out Our Latest Blog Post!</h2>
        <p style="font-size: 16px; line-height: 1.6;">
          Hi there,<br /><br />
          We just published a new blog post that we think you'll love! Discover exciting travel tips, destination guides, and inspiring stories to fuel your next adventure.
        </p>

        <!-- Blog Post Title and Short Description -->
        <h3 style="color: #1e3a8a; margin-bottom: 10px;">${Title}</h3>
        <p style="font-size: 15px; line-height: 1.5; color: #555555;">${Description.substring(
          0,
          150
        )}...</p>


        <div style="text-align: center; margin-top: 20px;">
  <img src="https://gammatourz.com/event-upload/${Image}" alt="Blog Image" style="max-width: 100%; height: auto; border-radius: 8px;" />
</div>

        <!-- Call to Action Button -->
        <div style="text-align: center; margin: 30px 0;">
          <a href="https://gammatourz.com/blog/${insertId1}" target="_blank" 
             style="background-color: #1e3a8a; color: #ffffff; padding: 12px 25px; border-radius: 6px; font-weight: 600; text-decoration: none; font-size: 16px;">
            Read the Full Blog
          </a>
        </div>

        <p style="font-size: 14px; color: #888888; margin-top: 40px;">
          Thank you for being part of our community! Stay tuned for more travel inspiration.
        </p>
        <p style="font-size: 14px; color: #888888;">
          With warm regards,<br />
          <strong>The Gamma Tourz Team</strong>
        </p>
      </div>

      <!-- Footer -->
      <div style="background-color: #e0e7ff; padding: 15px; text-align: center; font-size: 12px; color: #666666;">
        <p>Gamma Tourz | Your Gateway to Unforgettable Adventures</p>
<p style="font-size: 12px; color: #666666;">
  If you no longer wish to receive these emails, please <strong>reply to this email with "Unsubscribe"</strong>.
</p>
      </div>
    </div>
  </div>
  `,
        };

        await transporter.sendMail(mailOptionsSubscriber);
      })
    );

    res
      .status(201)
      .json({ success: true, message: "Event added successfully!" });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      Status: "Something went wrong when adding event!",
      error: err.message,
    });
  }
};

const getEventById = async (req, res) => {
  try {
    const baseURL = `${req.protocol}://${req.get("host")}/event-upload/`;
    const { idEvent } = req.params;
    const data = await eventDbService.getEventById(idEvent);
    const result = data.map((item) => ({
      ...item,
      Img_url: baseURL + item.Image,
    }));
    res.status(200).json(result);
  } catch (err) {
    console.log(err);
    res.status(500).json({
      Status: "Something went wrong when fetching event!",
      error: err.message,
    });
  }
};

const updateEventById = async (req, res) => {
  try {
    const { idEvent } = req.params;
    const { Date, Title, Description, BlogCategory_idBlogCategory } = req.body;
    const Image = req.file?.filename;
    if (Image) {
      await eventDbService.updateEventById(
        Date,
        Title,
        Description,
        Image,
        BlogCategory_idBlogCategory,
        idEvent
      );
    } else {
      await eventDbService.updateEventWithoutImage(
        Date,
        Title,
        Description,
        BlogCategory_idBlogCategory,
        idEvent
      );
    }

    res
      .status(200)
      .json({ success: true, message: "Event updated successfully!" });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      Status: "Something went wrong when updating event!",
      error: err.message,
    });
  }
};

const deleteEvent = async (req, res) => {
  try {
    const { idEvent } = req.params;
    await eventDbService.deleteEvent(idEvent);
    res
      .status(200)
      .json({ success: true, message: "Event deleted successfully!" });
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when deleting event!",
      error: err.message,
    });
  }
};

const getEventByLang = async (req, res) => {
  try {
    const baseURL = `${req.protocol}://${req.get("host")}/event-upload/`;
    const { lang } = req.params;
    const data = await eventDbService.getEventByLang(lang);
    const result = data.map((item) => ({
      ...item,
      Img_url: baseURL + item.Image,
    }));
    res.status(200).json(result);
  } catch (err) {
    res.status(500).json({
      Status: "Something went wrong when fetching events!",
      error: err.message,
    });
  }
};

module.exports = {
  getAllEvents,
  addEvent,
  getEventById,
  updateEventById,
  deleteEvent,
  getEventByLang,
};
