const db = require("../config/db"); // Assuming you have set up the database connection
const jwt = require("jsonwebtoken");
const bcrypt = require('bcrypt');
const axios = require("axios"); // Import axios for making HTTP requests
const https = require('https');
const fs = require('fs');
const path = require('path');
const CryptoJS = require('crypto-js'); // Import the crypto-js library

// Helper function to write logs to a file
const logToFile1 = (message) => {
  const logMessage = `${new Date().toISOString()} - ${message}\n`;
  const logFilePath = path.join(__dirname, 'logs', 'server.log'); // Ensure the logs directory exists

  // Check if the 'logs' directory exists, if not, create it
  if (!fs.existsSync(path.dirname(logFilePath))) {
    try {
    fs.mkdirSync(path.dirname(logFilePath), { recursive: true });
  } catch (error) {
    // console.error("Error creating log directory:", error);
  }
  }

  // Append log message to the file
  fs.appendFileSync(logFilePath, logMessage, 'utf8');
};

const generateUniqueHashId = () => {
  const timestamp = Date.now(); // Current timestamp (milliseconds)
  return timestamp.toString(36); // timestamp unique per mili sec
};



// Common functions 

// FOR BUNNY - START 


const BUNNY_REGION = 'ny'; // Your Bunny CDN region
const BUNNY_BASE_HOSTNAME = 'storage.bunnycdn.com';
const BUNNY_HOSTNAME = BUNNY_REGION ? `${BUNNY_REGION}.${BUNNY_BASE_HOSTNAME}` : BUNNY_BASE_HOSTNAME;
const BUNNY_STORAGE_ZONE_NAME = 'bigscreensocial'; // Your Bunny Storage Zone Name
const BUNNY_ACCESS_KEY = 'a4d9fb3d-c17a-4a78-bcfb0fe2f1ae-8767-4b0d';
const BUNNY_STREAM_ACCESS_KEY='96e74369-2f81-4a63-9811b265f755-cf10-474d';
const BUNNY_CDN_BASE_URL = 'https://BigScreenSocial.b-cdn.net';
const BUNNY_LIBRARY_ID = '366380';
const BUNNY_STREAM_BASE_URL = 'https://vz-3d811857-5d8.b-cdn.net';

// Function to calculate SHA-256 signature
function bunnyVideoSHA256(str) {
  return CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex);
}

// Function to calculate the signature
function bunnyVideoCalculateSignature(library_id, api_key, expiration_time, video_id) {
  const string_signature = library_id + api_key + expiration_time + video_id;
  return bunnyVideoSHA256(string_signature); // Generate and return the signature
}

// Helper function to upload files to Bunny CDN
const uploadFileToBunny = async (file_name, file_path, file_save_prefix_folder='') => {
  
  logToFile1(`Starting file upload: ${file_name}`); // Log start of the upload

  return new Promise((resolve, reject) => {
    const readStream = fs.createReadStream(file_path);
    
    // Encode the file name to escape special characters
    const encodedFileName = encodeURIComponent(file_name);
    
    let bunny_full_path;
    let bunny_prefix_plus_filename;
    
    if(file_save_prefix_folder)
    {
        bunny_full_path=`/${BUNNY_STORAGE_ZONE_NAME}/${file_save_prefix_folder}/${encodedFileName}`;
        bunny_prefix_plus_filename=`${file_save_prefix_folder}/${encodedFileName}`;
    }
    else
    {
        bunny_full_path=`/${BUNNY_STORAGE_ZONE_NAME}/${encodedFileName}`;
        bunny_prefix_plus_filename=encodedFileName;
    }
    

    const options = {
      method: 'PUT',
      host: BUNNY_HOSTNAME,
      path: bunny_full_path,
      headers: {
        AccessKey: BUNNY_ACCESS_KEY,
        'Content-Type': 'application/octet-stream',
      },
    };

    const req = https.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => {
        data += chunk.toString('utf8');
      });

      res.on('end', () => {
        const fileUrl = `${BUNNY_CDN_BASE_URL}/${bunny_prefix_plus_filename}`;
        logToFile1(`File uploaded successfully: ${fileUrl}`); // Log successful upload
        resolve(fileUrl); // Return the file URL
      });
    });

    req.on('error', (error) => {
      logToFile1(`Error uploading file: ${error.message}`); // Log error
      reject(error);
    });

    readStream.pipe(req);
    logToFile1(`File upload initiated for: ${file_name}`); // Log file upload initiation
  });
};


const deleteFileFromBunny = async (fileName) => {
    try {
        logToFile1(`Starting file deletion: ${fileName}`); // Log the start of the deletion
        const url = `https://${BUNNY_HOSTNAME}/${BUNNY_STORAGE_ZONE_NAME}/${fileName}`;

        const headers = {
            'AccessKey': BUNNY_ACCESS_KEY,
            'Content-Type': 'application/octet-stream'
        };

        const response = await axios.delete(url, { headers });
        logToFile1(`File deleted successfully: ${fileName}`); // Log successful deletion
        return response.data;
    } catch (error) {
        logToFile1(`Error deleting file: ${error.message}`); // Log error
        // console.error('Error deleting file:', error);
        // throw error;  // Rethrow or handle as necessary
    }
};


const bunnyCreateCollection = async (unique_file_name) => {
  try {

    // Construct the API URL
    const url = `https://video.bunnycdn.com/library/${BUNNY_LIBRARY_ID}/collections`;

    // Payload for the request
    const payload = {
      name: unique_file_name,
    };

    // Make the POST request to the Bunny CDN API
    const response = await axios.post(url, payload, {
      headers: {
        'Accesskey': BUNNY_STREAM_ACCESS_KEY,
        'Accept': 'application/json',
        'Content-Type': 'application/*+json',
      },
    });

    // Extract collection ID from the response
    const collection_id = response.data.guid;
    return collection_id;
  } catch (error) {
    console.error('Error creating collection:', error.message);
    // throw error; // Or handle it as needed
  }
};


const bunnyDeleteCollection = async (collectionId) => {
  try {
    // Construct the API URL
    const url = `https://video.bunnycdn.com/library/${BUNNY_LIBRARY_ID}/collections/${collectionId}`;

    // Make the DELETE request to the Bunny CDN API
    const response = await axios.delete(url, {
      headers: {
        'Accesskey': BUNNY_STREAM_ACCESS_KEY,
        'Accept': 'application/json',
      },
    });

    // Return the response if successful
    return response.data;
  } catch (error) {
    console.error('Error deleting collection:', error.message);
    // throw error; // Or handle it as needed
  }
};



const bunnyCreateVideo = async (collection_id) => {
  try {

    // Construct the API URL
    const url = `https://video.bunnycdn.com/library/${BUNNY_LIBRARY_ID}/videos`;
    
    // Generate a unique video ID using userId and a random suffix (similar to PHP's uniqid())
    const uniquePrefixId = 'video_' + Date.now().toString(36) + Math.random().toString(36).substr(2, 9); 

    // Payload for the request
    const payload = {
      collectionId: collection_id,
      title: uniquePrefixId,
    };

    // Make the POST request to the Bunny CDN API
    const response = await axios.post(url, payload, {
      headers: {
        'Accesskey': BUNNY_STREAM_ACCESS_KEY,
        'Accept': 'application/json',
        'Content-Type': 'application/*+json',
      },
    });

    // Extract collection ID from the response
    const video_id = response.data.guid;
    return video_id;
  } catch (error) {
    console.error('Error creating collection:', error.message);
    throw error; // Or handle it as needed
  }
};


const getBunnyVideoInfo = async (video_id) => {
  try {

    // Construct the API URL
    const url = `https://video.bunnycdn.com/library/${BUNNY_LIBRARY_ID}/videos/${video_id}`;
    
    const response = await axios.get(url, {
      headers: {
        'Accesskey': BUNNY_STREAM_ACCESS_KEY,
        'Accept': 'application/json',
      }
    });

    // Extract collection ID from the response
    return response.data;
  } catch (error) {
    console.error('Error creating collection:', error.message);
    // throw error; // Or handle it as needed
  }
};



// FOR BUNNY - END



// Events 

const addEvent = async (req, res) => {
  const {
    event_name,
    event_location,
    event_date,
    event_start_time,
    length_of_event,
    event_url_slug,
    notification_status,
    notification_emails,
    script_ids,
    ads_group_id,
    ads_per_post,
    event_status,
    password,
    wall_speed,
    wall_layout,
    page_title,
    page_description,
    page_keywords,
    // brand_custom_logo,
    // brand_social_share_image_path,
    // brand_watermark_image,
    contact_information = 'off', // Default value
    legal = 'off', // Default value
    copyright = 'off', // Default value
    top_brand_color,
    top_banner_text_color,
    bottom_brand_color,
    bottom_banner_text_color,
    cta_button_color,
    cta_button_text_color,
    top_banner_text= "",
    bottom_banner_text= "",
    cta_text= "", 
    cta_url= ""
  } = req.body; // Extract data from the request body


  if (!event_name || !event_start_time || !event_date || !length_of_event) {
    return res.status(400).json({ message: "Event Name, Start Time, Length of Event and Date are mandatory" });
  }
  
  logToFile1(`Starting upload event_name : ${event_name}`); // Log start of the upload
  
//   return res.status(200).json({ message: req.body });

  try {
      
      
      // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token 
      
    // Generate a unique hash for the screen
    const uniqueHashId = user_id+'-'+generateUniqueHashId();  
    
    const file_save_prefix_folder='eu'+user_id+'/images/'+uniqueHashId;

    // Check if event_url_slug already exists in the database (for uniqueness)
    const checkQuery = "SELECT * FROM events WHERE event_url_slug = ?";
    const [existingEvent] = await db.query(checkQuery, [event_url_slug]);

    if (existingEvent.length > 0) {
      return res.status(400).json({ message: "Event URL Slug already exists" });
    }

    // Hash the password if provided
    let hashedPassword = null;
    if (password) {
      hashedPassword = await bcrypt.hash(password, 10); // 10 is the salt rounds
    }
    
    const event_hash_id = uniqueHashId; 
    
    // get Collection id
    const bunnyCollectionId = await bunnyCreateCollection(event_hash_id); // Assuming event_hash_id is unique enough for collection creation
    

// File upload and deletion handling (one by one)
let uploadedLogoUrl = null;
let uploadedSocialShareImageUrl = null;
let uploadedWatermarkUrl = null;

if (req.files['brand_custom_logo']) {
  const logoPath = req.files['brand_custom_logo'][0].path;
  const logoName = req.files['brand_custom_logo'][0].filename;

  logToFile1(`Starting upload for brand_custom_logo: ${logoName}`);  // Log the start of the upload
  uploadedLogoUrl = await uploadFileToBunny(logoName, logoPath, file_save_prefix_folder);
  logToFile1(`brand_custom_logo uploadedLogoUrl: ${uploadedLogoUrl}`);

  // Log file deletion
  logToFile1(`Scheduled deletion for brand_custom_logo: ${logoPath}`); // Log deletion scheduling
  await fs.promises.unlink(logoPath);  // Wait for deletion of file
  logToFile1(`Deleted file: ${logoPath}`);
}

if (req.files['brand_social_share_image']) {
  const socialSharePath = req.files['brand_social_share_image'][0].path;
  const socialShareName = req.files['brand_social_share_image'][0].filename;

  logToFile1(`Starting upload for brand_social_share_image: ${socialShareName}`); // Log the start of the upload
  uploadedSocialShareImageUrl = await uploadFileToBunny(socialShareName, socialSharePath, file_save_prefix_folder);
  logToFile1(`brand_social_share_image uploadedSocialShareImageUrl: ${uploadedSocialShareImageUrl}`);

  // Log file deletion
  logToFile1(`Scheduled deletion for brand_social_share_image: ${socialSharePath}`); // Log deletion scheduling
  await fs.promises.unlink(socialSharePath);  // Wait for deletion of file
  logToFile1(`Deleted file: ${socialSharePath}`);
}

if (req.files['brand_watermark_image']) {
  const watermarkPath = req.files['brand_watermark_image'][0].path;
  const watermarkName = req.files['brand_watermark_image'][0].filename;

  logToFile1(`Starting upload for brand_watermark_image: ${watermarkName}`); // Log the start of the upload
  uploadedWatermarkUrl = await uploadFileToBunny(watermarkName, watermarkPath, file_save_prefix_folder);
  logToFile1(`brand_watermark_image uploadedWatermarkUrl: ${uploadedWatermarkUrl}`);

  // Log file deletion
  logToFile1(`Scheduled deletion for brand_watermark_image: ${watermarkPath}`); // Log deletion scheduling
  await fs.promises.unlink(watermarkPath);  // Wait for deletion of file
  logToFile1(`Deleted file: ${watermarkPath}`);
}

// Final URLs after uploading files one by one
const brand_custom_logo_url = uploadedLogoUrl || req.body.brand_custom_logo;
const brand_social_share_image_url = uploadedSocialShareImageUrl || req.body.brand_social_share_image;
const brand_watermark_image_url = uploadedWatermarkUrl || req.body.brand_watermark_image;

// logToFile1(`Upload completed. URLs: `); // Log final URLs
// logToFile1(`brand_custom_logo_url: ${brand_custom_logo_url}`);
// logToFile1(`brand_social_share_image_url: ${brand_social_share_image_url}`);
// logToFile1(`brand_watermark_image_url: ${brand_watermark_image_url}`);
    

    // Insert the new event into the database with all the provided values
    const query = `
      INSERT INTO events (
        user_id, event_name, event_location, event_date, event_start_time, length_of_event,
        event_url_slug, notification_status, notification_emails, ads_group_id, ads_per_post, event_status, password,
        wall_speed, wall_layout, page_title, page_description, page_keywords, brand_custom_logo_url,
        brand_social_share_image_url, brand_watermark_image_url, contact_information, legal, copyright,
        top_brand_color, top_banner_text_color, bottom_brand_color, bottom_banner_text_color, cta_button_color,
        cta_button_text_color,top_banner_text, bottom_banner_text, cta_text, cta_url,event_hash_id,bunny_collection_id
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    const [result] = await db.query(query, [
      user_id, event_name, event_location, event_date, event_start_time, length_of_event,
      event_url_slug, notification_status, notification_emails || null, ads_group_id || null, ads_per_post, event_status, hashedPassword,
      wall_speed, wall_layout, page_title, page_description, page_keywords, brand_custom_logo_url,
      brand_social_share_image_url, brand_watermark_image_url, contact_information, legal, copyright,
      top_brand_color, top_banner_text_color, bottom_brand_color, bottom_banner_text_color, cta_button_color,
      cta_button_text_color,top_banner_text, bottom_banner_text, cta_text, cta_url,uniqueHashId,bunnyCollectionId
    ]);
    
    // Get the id of the newly created ads group
    const lastInsertId = result.insertId;
    
    // Step 1: Get script_ids from the request body (assumed to be a comma-separated string)
    
    if(script_ids)
    {
        let scriptIds = script_ids;
    
        // Step 2: Convert the comma-separated string into an array of integers
        scriptIds = scriptIds.split(',').map(id => parseInt(id.trim(), 10));
        
        // Step 3: Insert the new ads into the event_ads_group_pivot table
        const pivotData = scriptIds.map(script_id => [lastInsertId, script_id]);
        
        if (pivotData.length > 0) {
          const pivotQuery = `
            INSERT INTO event_scripts_pivot (event_id, script_id)
            VALUES ?
          `;
          await db.query(pivotQuery, [pivotData]);
        }
    }
    

    // Respond with success message
    res.status(201).json({ message: "Event added successfully"});
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while adding the event",
      error: error.message,  // Send the actual error message
    });
  }
};






// Controller to get all events
// Controller to get all events based on role
const getEvents = async (req, res) => {

  try {
      
    // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token 


    // Query to get events along with their associated script details from event_scripts_pivot and event_scripts tables
    const query = `
      SELECT 
        events.*, 
        GROUP_CONCAT(event_scripts.id SEPARATOR ';') AS script_ids,
        GROUP_CONCAT(event_scripts.script_name SEPARATOR '|||') AS script_names
      FROM 
        events
      LEFT JOIN 
        event_scripts_pivot ON events.id = event_scripts_pivot.event_id
      LEFT JOIN 
        event_scripts ON event_scripts_pivot.script_id = event_scripts.id
      WHERE 
        events.user_id = ?
      GROUP BY 
        events.id
    `;

    const [events] = await db.query(query, [user_id]); // Execute the query with appropriate parameters
    
    // Process each event to split the concatenated fields into arrays
    const formattedEvents = events.map(event => ({
      ...event,
      script_ids: event.script_ids ? event.script_ids.split(';').map(id => parseInt(id)) : [], // Convert script_ids to array of integers
      script_names: event.script_names ? event.script_names.split('|||') : [] // Convert script_names to array
    }));

    res.status(200).json(formattedEvents); // Send the events as a JSON response
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while fetching the events",
      error,
    });
  }
};


const updateEvent = async (req, res) => {
  const {
    password,
    event_name,
    event_location,
    event_date,
    event_start_time,
    length_of_event,
    event_url_slug,
    notification_status,
    notification_emails,
    script_ids,
    ads_group_id=null,
    ads_per_post,
    event_status,
    wall_speed,
    wall_layout,
    page_title,
    page_description,
    page_keywords,
    contact_information = 'off',
    legal = 'off',
    copyright = 'off',
    top_brand_color,
    top_banner_text_color,
    bottom_brand_color,
    bottom_banner_text_color,
    cta_button_color,
    cta_button_text_color,
    top_banner_text= "",
    bottom_banner_text= "",
    cta_text= "", 
    cta_url= "" 
  } = req.body; // Extract data from the request body
  const eventId = req.params.id; // Get the event ID from the URL parameter
  

    // return res.status(400).json({
    //   message: "Ad Group Name is required!",
    //   requestBody: req.body // Include the entire request body in the response
    // });

  try {
      
      // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token 
      
    // Check user authentication to perform action - start
    const [userCheck] = await db.query("SELECT role FROM users WHERE id = ? LIMIT 1", [user_id]);
    if (userCheck.length === 0) {
      return res.status(404).json({ message: "User not found" });
    }
    
    const userRole = userCheck[0].role;
    
    if (userRole != 'super_admin') {
        
    // Fetch the event from the DB using eventId to get event_hash_id
    const checkExistenceQuery = 'SELECT id FROM events WHERE id = ? AND user_id = ? LIMIT 1';
    const [checkExistenceResult] = await db.query(checkExistenceQuery, [eventId,user_id]);

    // Check if the event exists
    if (checkExistenceResult.length === 0) {
      return res.status(404).json({ message: "Event not found or you are not authorize to take this action" });
    }    
        
    }
    // Check user authentication to perform action - start  
      
    // Fetch the event from the DB using eventId to get event_hash_id
    const eventQuery = 'SELECT user_id,event_hash_id FROM events WHERE id = ?';
    const [eventResult] = await db.query(eventQuery, [eventId]);

    // Check if the event exists
    if (eventResult.length === 0) {
      return res.status(404).json({ message: "Event not found" });
    }
    
    // Extract event_hash_id from the result
    const event_hash_id = eventResult[0].event_hash_id;
    const event_user_id = eventResult[0].user_id;
    
    const file_save_prefix_folder='eu'+event_user_id+'/images/'+event_hash_id;
    
    // return res.status(404).json({ message: "video_id: "+ video_id });

    let updateFields = [];
    let values = [];

    // Check if password is provided, then hash it
    if (password) {
      const hashedPassword = await bcrypt.hash(password, 10); // Hash the password
      updateFields.push("password = ?");
      values.push(hashedPassword);
    }

    // Other fields to update
    if (event_name) {
      updateFields.push("event_name = ?");
      values.push(event_name);
    }
    if (event_location) {
      updateFields.push("event_location = ?");
      values.push(event_location);
    }
    if (event_date) {
      updateFields.push("event_date = ?");
      values.push(event_date);
    }
    if (event_start_time) {
      updateFields.push("event_start_time = ?");
      values.push(event_start_time);
    }
    if (length_of_event) {
      updateFields.push("length_of_event = ?");
      values.push(length_of_event);
    }
    if (event_url_slug) {
      updateFields.push("event_url_slug = ?");
      values.push(event_url_slug);
    }
    if (notification_status) {
      updateFields.push("notification_status = ?");
      values.push(notification_status);
    }
    if (notification_emails) {
      updateFields.push("notification_emails = ?");
      values.push(notification_emails);
    }
    // if (script_ids) {
    //   updateFields.push("script_ids = ?");
    //   values.push(script_ids);
    // }
    // ads_group_id can be null, if user want to deselect it, that's why we have not added if case
    updateFields.push("ads_group_id = ?");
    values.push(ads_group_id);

    // ads_per_post can be 0, if user want to deselect it, that's why we have not added if case
    updateFields.push("ads_per_post = ?");
    values.push(ads_per_post);
      
    if (event_status) {
      updateFields.push("event_status = ?");
      values.push(event_status);
    }
    if (wall_speed) {
      updateFields.push("wall_speed = ?");
      values.push(wall_speed);
    }
    if (wall_layout) {
      updateFields.push("wall_layout = ?");
      values.push(wall_layout);
    }
    if (page_title) {
      updateFields.push("page_title = ?");
      values.push(page_title);
    }
    if (page_description) {
      updateFields.push("page_description = ?");
      values.push(page_description);
    }
    if (page_keywords) {
      updateFields.push("page_keywords = ?");
      values.push(page_keywords);
    }
    
    if (contact_information) {
    updateFields.push("contact_information = ?");
    values.push(contact_information);
    }
    
    if (legal) {
    updateFields.push("legal = ?");
    values.push(legal);
    }
    
    if (copyright) {
    updateFields.push("copyright = ?");
    values.push(copyright);
    }

    if (top_brand_color) {
      updateFields.push("top_brand_color = ?");
      values.push(top_brand_color);
    }
    if (top_banner_text_color) {
      updateFields.push("top_banner_text_color = ?");
      values.push(top_banner_text_color);
    }
    if (bottom_brand_color) {
      updateFields.push("bottom_brand_color = ?");
      values.push(bottom_brand_color);
    }
    if (bottom_banner_text_color) {
      updateFields.push("bottom_banner_text_color = ?");
      values.push(bottom_banner_text_color);
    }
    if (cta_button_color) {
      updateFields.push("cta_button_color = ?");
      values.push(cta_button_color);
    }
    if (cta_button_text_color) {
      updateFields.push("cta_button_text_color = ?");
      values.push(cta_button_text_color);
    }
    
    // New fields added
    if (top_banner_text) {
      updateFields.push("top_banner_text = ?");
      values.push(top_banner_text);
    }
    if (bottom_banner_text) {
      updateFields.push("bottom_banner_text = ?");
      values.push(bottom_banner_text);
    }
    if (cta_text) {
      updateFields.push("cta_text = ?");
      values.push(cta_text);
    }
    if (cta_url) {
      updateFields.push("cta_url = ?");
      values.push(cta_url);
    }

    // File upload and deletion handling (one by one)
    let uploadedLogoUrl = null;
    let uploadedSocialShareImageUrl = null;
    let uploadedWatermarkUrl = null;

    if (req.files['brand_custom_logo']) {
      const logoPath = req.files['brand_custom_logo'][0].path;
      const logoName = req.files['brand_custom_logo'][0].filename;

      logToFile1(`Starting upload for brand_custom_logo: ${logoName}`);
      uploadedLogoUrl = await uploadFileToBunny(logoName, logoPath, file_save_prefix_folder);
      logToFile1(`brand_custom_logo uploadedLogoUrl: ${uploadedLogoUrl}`);

      // Log file deletion
      logToFile1(`Scheduled deletion for brand_custom_logo: ${logoPath}`);
      await fs.promises.unlink(logoPath); // Wait for deletion of file
      logToFile1(`Deleted file: ${logoPath}`);

      updateFields.push("brand_custom_logo_url = ?");
      values.push(uploadedLogoUrl);
    }

    if (req.files['brand_social_share_image']) {
      const socialSharePath = req.files['brand_social_share_image'][0].path;
      const socialShareName = req.files['brand_social_share_image'][0].filename;

      logToFile1(`Starting upload for brand_social_share_image: ${socialShareName}`);
      uploadedSocialShareImageUrl = await uploadFileToBunny(socialShareName, socialSharePath, file_save_prefix_folder);
      logToFile1(`brand_social_share_image uploadedSocialShareImageUrl: ${uploadedSocialShareImageUrl}`);

      // Log file deletion
      logToFile1(`Scheduled deletion for brand_social_share_image: ${socialSharePath}`);
      await fs.promises.unlink(socialSharePath); // Wait for deletion of file
      logToFile1(`Deleted file: ${socialSharePath}`);

      updateFields.push("brand_social_share_image_url = ?");
      values.push(uploadedSocialShareImageUrl);
    }

    if (req.files['brand_watermark_image']) {
      const watermarkPath = req.files['brand_watermark_image'][0].path;
      const watermarkName = req.files['brand_watermark_image'][0].filename;

      logToFile1(`Starting upload for brand_watermark_image: ${watermarkName}`);
      uploadedWatermarkUrl = await uploadFileToBunny(watermarkName, watermarkPath, file_save_prefix_folder);
      logToFile1(`brand_watermark_image uploadedWatermarkUrl: ${uploadedWatermarkUrl}`);

      // Log file deletion
      logToFile1(`Scheduled deletion for brand_watermark_image: ${watermarkPath}`);
      await fs.promises.unlink(watermarkPath); // Wait for deletion of file
      logToFile1(`Deleted file: ${watermarkPath}`);

      updateFields.push("brand_watermark_image_url = ?");
      values.push(uploadedWatermarkUrl);
    }

    // Only update if there is any field to update
    if (updateFields.length === 0) {
      return res.status(400).json({ message: "No data to update" });
    }

    // Add event ID to the values
    values.push(eventId);

    // SQL query to update the event data by its ID
    const query = `UPDATE events 
                   SET ${updateFields.join(", ")} 
                   WHERE id = ?`;

    const result = await db.query(query, values);
    
    
    
    if(script_ids)
    {
        // Step 1: Get script_ids from the request body (assumed to be a comma-separated string)
        let scriptIds = req.body.script_ids;
        
        // Step 2: Convert the comma-separated string into an array of integers
        scriptIds = scriptIds.split(',').map(id => parseInt(id.trim(), 10));
        
        // Step 3: Delete the existing ads linked to this group in event_ads_group_pivot
        const deletePivotQuery = `DELETE FROM event_scripts_pivot WHERE event_id = ?`;
        await db.query(deletePivotQuery, [eventId]);
        
        // Step 4: Insert the new ads into the event_ads_group_pivot table
        const pivotData = scriptIds.map(script_id => [eventId, script_id]);
        
        if (pivotData.length > 0) {
          const pivotQuery = `
            INSERT INTO event_scripts_pivot (event_id, script_id)
            VALUES ?
          `;
          await db.query(pivotQuery, [pivotData]);
        }
    }
    
    
    

    // Check if the event was updated
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: "Event not found or not authorized to update" });
    }

    res.status(200).json({ message: "Event updated successfully" });
  } catch (error) {
    console.error("Error updating event:", error);
    res.status(500).json({ message: "An error occurred while updating the event", error: error.message });
  }
};


const getEventBySlug = async (req, res) => {
  const { eventUrlSlug } = req.params; // Extract eventUrlSlug from URL parameter

  try {
    // Query the database to get the event by its event_url_slug along with associated script details
    const query = `
      SELECT 
        events.*,
        user_details.company_name,
        user_details.website_url,
        user_details.phone_number,
        GROUP_CONCAT(event_scripts.id) AS script_ids
      FROM 
        events
      LEFT JOIN 
        event_scripts_pivot ON events.id = event_scripts_pivot.event_id
      LEFT JOIN 
        event_scripts ON event_scripts_pivot.script_id = event_scripts.id
      LEFT JOIN 
        user_details_pivot ON events.user_id = user_details_pivot.user_id
      LEFT JOIN 
        user_details ON user_details_pivot.user_details_id = user_details.id
      WHERE 
        events.event_url_slug = ?
      GROUP BY 
        events.id
    `;
    
    const [event] = await db.query(query, [eventUrlSlug]);

    if (event.length === 0) {
      return res.status(404).json({ message: "Event not found" });
    }

    // Return the event details along with script_ids and scripts as a JSON response
    res.status(200).json(event[0]);
  } catch (error) {
    console.error("Error fetching event by URL slug:", error);
    res.status(500).json({
      message: "An error occurred while fetching the event",
      error: error.message, // Send the actual error message
    });
  }
};

// const getEventBySlug = async (req, res) => {
//   const { eventUrlSlug } = req.params; // Extract eventUrlSlug from URL parameter

//   try {
//     // Query the database to get the event by its event_url_slug along with associated script details
//     const query = `
//       SELECT 
//         events.*, 
//         GROUP_CONCAT(event_scripts.id SEPARATOR ';') AS script_ids,
//         GROUP_CONCAT(event_scripts.script SEPARATOR '|||') AS scripts
//       FROM 
//         events
//       LEFT JOIN 
//         event_scripts_pivot ON events.id = event_scripts_pivot.event_id
//       LEFT JOIN 
//         event_scripts ON event_scripts_pivot.script_id = event_scripts.id
//       WHERE 
//         events.event_url_slug = ?
//       GROUP BY 
//         events.id
//     `;
    
//     const [event] = await db.query(query, [eventUrlSlug]);

//     if (event.length === 0) {
//       return res.status(404).json({ message: "Event not found" });
//     }

//     // Process the event to split the concatenated fields into arrays
//     const formattedEvent = {
//       ...event[0],
//       script_ids: event[0].script_ids ? event[0].script_ids.split(';').map(id => parseInt(id)) : [], // Convert script_ids to array of integers
//       scripts: event[0].scripts ? event[0].scripts.split('|||') : [] // Convert scripts to array
//     };

//     // Return the event details along with script_ids and scripts as a JSON response
//     res.status(200).json(formattedEvent);
//   } catch (error) {
//     console.error("Error fetching event by URL slug:", error);
//     res.status(500).json({
//       message: "An error occurred while fetching the event",
//       error: error.message, // Send the actual error message
//     });
//   }
// };


// // Controller to get an event by event_url_slug
// const getEventBySlug = async (req, res) => {
//   const { eventUrlSlug } = req.params; // Extract eventUrlSlug from URL parameter

//   try {
//     // Query the database to get the event by its event_url_slug
//     const query = "SELECT * FROM events WHERE event_url_slug = ?";
//     const [event] = await db.query(query, [eventUrlSlug]);

//     if (event.length === 0) {
//       return res.status(404).json({ message: "Event not found" });
//     }

//     // Return the event details as a JSON response
//     res.status(200).json(event[0]);
//   } catch (error) {
//     console.error("Error fetching event by URL slug:", error);
//     res.status(500).json({
//       message: "An error occurred while fetching the event",
//       error: error.message, // Send the actual error message
//     });
//   }
// };

const addEventPost = async (req, res) => {
  try {
    // Validate form data
    const { event_id, person_name, person_email_id, person_city, caption, media_type, video_id=null } = req.body;
    // const media = req.files ? req.files.media : null; // Handle file upload

    if (!event_id || !person_name || !person_email_id || !person_city || !caption || !media_type) {
      return res.status(400).json({ message: "All fields are required!" });
    }
    
    // Fetch the event from the DB using eventId to get event_hash_id
    const eventQuery = 'SELECT user_id,event_hash_id FROM events WHERE id = ?';
    const [eventResult] = await db.query(eventQuery, [event_id]);

    // Check if the event exists
    if (eventResult.length === 0) {
      return res.status(404).json({ message: "Event not found" });
    }
    
    // Extract event_hash_id from the result
    const event_hash_id = eventResult[0].event_hash_id;
    const event_user_id = eventResult[0].user_id;
    
    const file_save_prefix_folder='eu'+event_user_id+'/images/'+event_hash_id;
    
    // File upload and deletion handling (one by one)
    let mediaUrl = null;
    let thumbnail_media_url = null;
    let mediaType = 'image'; // Default type to 'image'
    
    if(media_type=='image')
    {
        if (req.files['media']) {
          const mediaPath = req.files['media'][0].path;
          const mediaName = req.files['media'][0].filename;
          const mediaType = req.files['media'][0].mimetype.split('/')[0];
        
          logToFile1(`Starting upload for media: ${mediaName}`);  // Log the start of the upload
          mediaUrl = await uploadFileToBunny(mediaName, mediaPath,file_save_prefix_folder);
          logToFile1(`media uploadedMediaUrl: ${mediaUrl}`);
          
          thumbnail_media_url=mediaUrl;
        
          // Log file deletion
          logToFile1(`Scheduled deletion for media: ${mediaPath}`); // Log deletion scheduling
          await fs.promises.unlink(mediaPath);  // Wait for deletion of file
          logToFile1(`Deleted file: ${mediaPath}`);
        }
    }
    else 
    {
        thumbnail_media_url=BUNNY_STREAM_BASE_URL+'/'+video_id+'/thumbnail.jpg';
    }
    

    // Insert the new event post into the database with all the provided values
    const query = `
      INSERT INTO event_posts (
        event_id, person_name, person_email_id, person_city, caption, media_url, thumbnail_media_url, media_file_type, bunny_video_id
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;

    await db.query(query, [
      event_id, person_name, person_email_id, person_city, caption, mediaUrl, thumbnail_media_url, media_type, video_id
    ]);

    // Return success response
    return res.status(201).json({
      message: 'Event post created successfully!',
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: 'Server error. Unable to create event post.',error:error.message });
  }
};

const getEventPosts = async (req, res) => {
  const { event_id } = req.params;

  if (!event_id) {
    return res.status(400).json({ message: "Event ID is required" });
  }

  try {
    // Query to fetch posts for the given event ID
    const query = "SELECT * FROM event_posts WHERE event_id = ?";
    const [posts] = await db.query(query, [event_id]);

    if (posts.length === 0) {
      return res.status(404).json({ message: "No posts found for this event" });
    }

    res.status(200).json(posts);
  } catch (error) {
    console.error("Error fetching posts:", error);
    res.status(500).json({ message: "An error occurred while fetching the posts", error: error.message });
  }
};


const getApprovedEventPosts = async (req, res) => {
  const { event_id } = req.params;

  if (!event_id) {
    return res.status(400).json({ message: "Event ID is required" });
  }

  try {
    // Query to fetch posts for the given event ID
    const query = "SELECT * FROM event_posts WHERE status='approve' AND event_id = ?";
    const [posts] = await db.query(query, [event_id]);

    if (posts.length === 0) {
      return res.status(404).json({ message: "No posts found for this event" });
    }

    res.status(200).json(posts);
  } catch (error) {
    console.error("Error fetching posts:", error);
    res.status(500).json({ message: "An error occurred while fetching the posts", error: error.message });
  }
};



const getAllEventPosts = async (req, res) => {

  try {
    // Query to fetch posts for the given event ID
    // const query = "SELECT * FROM event_posts";
    const query = `
      SELECT ep.*, e.event_name, e.event_date, e.event_location
      FROM event_posts ep
      JOIN events e ON ep.event_id = e.id ORDER BY ep.created_at DESC`;
    const [posts] = await db.query(query);

    if (posts.length === 0) {
      return res.status(404).json({ message: "No posts found for this event" });
    }

    res.status(200).json(posts);
  } catch (error) {
    console.error("Error fetching posts:", error);
    res.status(500).json({ message: "An error occurred while fetching the posts", error: error.message });
  }
};


const updateEventPostFavourite = async (req, res) => {
  const { post_id } = req.params; // Get the post_id from the URL parameters
  const { is_favourite } = req.body; // Get the 'is_favourite' value from the request body

  if (!post_id || !is_favourite) {
    return res.status(400).json({ message: "Post ID and 'is_favourite' are required" });
  }

  // Ensure 'is_favourite' value is either 'yes' or 'no'
  if (is_favourite !== 'yes' && is_favourite !== 'no') {
    return res.status(400).json({ message: "Invalid value for 'is_favourite'. It must be 'yes' or 'no'" });
  }

  try {
    // Query to update the 'is_favourite' field for the specified post_id
    const query = "UPDATE event_posts SET is_favourite = ? WHERE id = ?";
    const result = await db.query(query, [is_favourite, post_id]);

    // Check if the post was found and updated
    if (result[0].affectedRows === 0) {
      return res.status(404).json({ message: "Post not found" });
    }

    // Return the updated post or a success message
    res.status(200).json({ message: "Post favourite status updated successfully" });
  } catch (error) {
    console.error("Error updating favourite status:", error);
    res.status(500).json({ message: "An error occurred while updating the favourite status", error: error.message });
  }
};

const updateEventPostStatus = async (req, res) => {
  const { post_id } = req.params; // Get the post_id from the URL
  const { status } = req.body;    // Get status value ('approve', 'private', 'banned', 'delete')

  // Validate input
  if (!post_id || !status) {
    return res.status(400).json({ message: "Post ID and status are required" });
  }

  // Ensure status is one of the allowed values
  const validStatuses = ["approve", "private", "banned", "delete"];
  if (!validStatuses.includes(status)) {
    return res.status(400).json({ message: "Invalid status value. It must be 'approve', 'private', 'banned', or 'delete'" });
  }

  try {
    // SQL query to update the status of the post in the database
    const query = "UPDATE event_posts SET status = ? WHERE id = ?";
    const [result] = await db.query(query, [status, post_id]);

    // Check if the post was found and updated
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: "Post not found" });
    }
    
    if(status=='approve')
    {
        // Retrieve the post data (assuming the 'event_id' and 'event_url_slug' are in the post record)
        const postQuery = "SELECT * FROM event_posts WHERE id = ?";
        const [post] = await db.query(postQuery, [post_id]);
    
        if (!post) {
          return res.status(404).json({ message: "Post not found" });
        }
        
        const event_id=post[0].event_id;
    
        // // Emit the new post to all connected clients for this event
        // io.emit('newPost', {
        //   ...post,
        //   event_id: event_id, // Send event identifier along with the post
        // });
    
        // Make a POST request to the /api/emit-to-socket endpoint
        await axios.post("https://bigscreensocial.wearedeveloper.site/api/emit-new-event-post", {
            event_id,
            post: post[0]
        });
    }
    


    // Return a success message if the update was successful
    res.status(200).json({ message: "Post status updated successfully" });
  } catch (error) {
    console.error("Error updating status:", error);
    res.status(500).json({ message: "An error occurred while updating the status", error: error.message });
  }
};


// Controller to get an event by event_url_slug
const getVideoId = async (req, res) => {
  // Get the user_id from the query parameters
    const { event_id } = req.query;

  try {
    // Query the database to get the event by its event_url_slug
    const query = "SELECT * FROM events WHERE id = ?";
    const [event] = await db.query(query, [event_id]);

    if (event.length === 0) {
      return res.status(404).json({ message: "Event not found" });
    }
    
    const bunny_collection_id=event[0].bunny_collection_id;
    
    const video_id=await bunnyCreateVideo(bunny_collection_id);
    
    // Calculate expiration_time (in seconds) for the signature
    const expiration_time = Math.floor(new Date().getTime() / 1000) + 200000; // 200000 seconds from now

    // Generate the presigned_signature using the bunnyVideoCalculateSignature function
    const presigned_signature = bunnyVideoCalculateSignature(BUNNY_LIBRARY_ID, BUNNY_STREAM_ACCESS_KEY, expiration_time, video_id);

    // Return the event details as a JSON response
    res.status(200).json({video_id, presigned_signature});
  } catch (error) {
    console.error("Error fetching event by URL slug:", error);
    res.status(500).json({
      message: "An error occurred while fetching the event",
      error: error.message, // Send the actual error message
    });
  }
};

// Webhook endpoint for video processing updates
const updateVideoWebhook = async (req, res) => {
  const json_data = req.body; // Express automatically parses JSON payload
  console.log(json_data); // Log the incoming data for debugging
  logToFile1(`Video Webhook: ${JSON.stringify(json_data)}`); // Log start of the upload
  
  const bunny_video_id = json_data.VideoGuid;
  const video_status = json_data.Status;
  const update = {};
  const values = [];  // Initialize the values array to store the values for the SQL query
  const updateFields = [];

  if (video_status === 3) {
    try {
      // Video is processed and ready for further actions
      const result_video = await getBunnyVideoInfo(bunny_video_id);

      if (result_video) {
        // Assuming `availableResolutions` is a comma-separated string
        const availableResolutions = result_video.availableResolutions;
        const resolutions = availableResolutions.split(',');

        let max_resolution = 0;

        // Loop through resolutions and find the maximum
        resolutions.forEach((resolution) => {
          const resolutionValue = parseInt(resolution.replace('p', ''), 10);
          if (resolutionValue > max_resolution) {
            max_resolution = resolutionValue;
          }
        });

        // As Bunny only produces max 720p video
        if (max_resolution > 720) {
          max_resolution = 720;
        }

        updateFields.push('bunny_video_max_resolution_height');
        values.push(max_resolution);

        // Mark as processing complete
        updateFields.push('is_bunny_video_processing_complete');
        values.push('yes');

        const video_file_mp4_url = BUNNY_STREAM_BASE_URL + '/' + bunny_video_id + '/play_' + max_resolution + 'p.mp4';

        // Mark as processing complete
        updateFields.push('media_url');
        values.push(video_file_mp4_url);

        let query = '';
        let tableUpdated = false;  // Flag to track whether a table was updated

        // First, check if the bunny_video_id exists in the event_posts table
        const checkEventPostsQuery = `SELECT bunny_video_id FROM event_posts WHERE bunny_video_id = ? LIMIT 1`;
        const [checkEventPostsResult] = await db.query(checkEventPostsQuery, [bunny_video_id]);

        if (checkEventPostsResult.length > 0) {
          // If found in event_posts, update event_posts
          query = `UPDATE event_posts
                   SET ${updateFields.map((field) => `${field} = ?`).join(", ")}
                   WHERE bunny_video_id = ?`;
          tableUpdated = true;
        }

        // If not found in event_posts, check the event_ads table
        if (!tableUpdated) {
          const checkEventAdsQuery = `SELECT bunny_video_id FROM event_ads WHERE bunny_video_id = ? LIMIT 1`;
          const [checkEventAdsResult] = await db.query(checkEventAdsQuery, [bunny_video_id]);

          if (checkEventAdsResult.length > 0) {
            // If found in event_ads, update event_ads
            query = `UPDATE event_ads
                     SET ${updateFields.map((field) => `${field} = ?`).join(", ")}
                     WHERE bunny_video_id = ?`;
            tableUpdated = true;
          }
        }

        if (tableUpdated) {
          // Add bunny_video_id to the end of the values array for the query
          values.push(bunny_video_id);

          const [updateResult] = await db.query(query, values);

          if (updateResult.affectedRows > 0) {
            res.status(200).send({ message: 'Video processed successfully' });
          } else {
            res.status(500).send({ message: 'Error updating video' });
          }
        } else {
          res.status(404).send({ message: 'Video ID not found in either event_posts or event_ads' });
        }
      } else {
        res.status(400).send({ message: 'Video info not found on bunny' });
      }

    } catch (error) {
      console.error("Error executing query:", error);
      res.status(500).send({ message: 'Database update error', error: error.message });
    }
  } else {
    res.status(200).send({ message: 'Video status is not completed yet' });
  }
};


// Controller to delete an existing event by its ID
const deleteEvent = async (req, res) => {
  const { id } = req.params; // Get the event_id from the URL params

  if (!id) {
    return res.status(400).json({ message: "Event ID is required" });
  }

  try {
      
      // Access the Authorization token from the request headers
    const authHeader = req.headers['authorization']; // Get the 'Authorization' header
    if (!authHeader) {
      return res.status(401).json({ message: "Unauthorized Access" });
    }
    const accessToken = authHeader.split(' ')[1];  //Extract the token (it will be in the form "Bearer <token>")
    const decodedData = jwt.verify(accessToken, process.env.JWT_SECRET_KEY); // Verify and decode the token
    const user_id = decodedData.user_id; // Assuming 'user_id' is stored in the payload of the token 
      
    // Check user authentication to perform action - start
    const [userCheck] = await db.query("SELECT role FROM users WHERE id = ? LIMIT 1", [user_id]);
    if (userCheck.length === 0) {
      return res.status(404).json({ message: "User not found" });
    }
    
    const userRole = userCheck[0].role;
    
    if (userRole != 'super_admin') {
        
    // Fetch the event from the DB using eventId to get event_hash_id
    const checkExistenceQuery = 'SELECT id FROM events WHERE id = ? AND user_id = ? LIMIT 1';
    const [checkExistenceResult] = await db.query(checkExistenceQuery, [id,user_id]);

    // Check if the event exists
    if (checkExistenceResult.length === 0) {
      return res.status(404).json({ message: "Event not found or you are not authorize to take this action" });
    }    
        
    }
    // Check user authentication to perform action - start   
      
    // Ensure the event exists before attempting to delete
    const checkQuery = `SELECT * FROM events WHERE id = ?`;
    const [existingEvent] = await db.query(checkQuery, [id]);

    if (existingEvent.length === 0) {
      return res.status(404).json({ message: "Event not found for the provided ID!" });
    }
    
    // Extract event_hash_id from the result
    const event_hash_id = existingEvent[0].event_hash_id;
    const event_user_id = existingEvent[0].user_id;
    const bunny_collection_id = existingEvent[0].bunny_collection_id;
    
    const file_save_prefix_folder='eu'+event_user_id+'/images/'+event_hash_id;
    
    // delete collection
    await bunnyDeleteCollection(bunny_collection_id);
    
    
    // Delete brand custom logo if it exists
    if (existingEvent[0].brand_custom_logo_url) {
      let logo_url = existingEvent[0].brand_custom_logo_url;
      let fileName = logo_url.replace(BUNNY_CDN_BASE_URL + '/', ''); // Remove the base URL
      await deleteFileFromBunny(fileName); // Call your existing function to delete the file
    }

    // Delete brand social share image if it exists
    if (existingEvent[0].brand_social_share_image_url) {
      let socialShareImage_url = existingEvent[0].brand_social_share_image_url;
      let fileName = socialShareImage_url.replace(BUNNY_CDN_BASE_URL + '/', ''); // Remove the base URL
      await deleteFileFromBunny(fileName); // Call your existing function to delete the file
    }

    // Delete brand watermark image if it exists
    if (existingEvent[0].brand_watermark_image_url) {
      let watermarkImage_url = existingEvent[0].brand_watermark_image_url;
      let fileName = watermarkImage_url.replace(BUNNY_CDN_BASE_URL + '/', ''); // Remove the base URL
      await deleteFileFromBunny(fileName); // Call your existing function to delete the file
    }
    
    const checkEventPostQuery = `SELECT * FROM event_posts WHERE event_id = ?`;
    const [existingEventPosts] = await db.query(checkEventPostQuery, [id]);

    if (existingEventPosts.length > 0) {
        
      // Loop through the event posts and delete associated files from Bunny CDN
      for (const post of existingEventPosts) {
        // Only delete if the media file is an image
        if (post.media_file_type === 'image') {
          let file_url = post.media_url;
          if (file_url) {
            let fileName = file_url.replace(BUNNY_CDN_BASE_URL + '/', ''); // Remove the base URL
            
            // Delete the file from Bunny CDN
            await deleteFileFromBunny(fileName); // Call your existing function to delete the file
          }
        }
      }
        
    // Delete all event posts related to the event
    const deleteEventPostsQuery = `DELETE FROM event_posts WHERE event_id = ?`;
    await db.query(deleteEventPostsQuery, [id]);
    }
    
    // // delete folder (but not working )
    // await deleteFileFromBunny(file_save_prefix_folder); // Call your existing function to delete the file

    // Delete the event from the events table
    const deleteEventQuery = `DELETE FROM events WHERE id = ?`;
    await db.query(deleteEventQuery, [id]);

    res.status(200).json({ message: "Event deleted successfully" });
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while deleting the Event",
      error: error.message,
    });
  }
};



module.exports = { addEvent, getEvents, updateEvent, deleteEvent, getEventBySlug, addEventPost, getEventPosts, getApprovedEventPosts, getVideoId, updateVideoWebhook, getAllEventPosts, updateEventPostFavourite, updateEventPostStatus };
