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


const getEventAdsGroups = 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 
    
    // Define the query to get the ad groups and their associated ads
    const query = `
      SELECT eg.id AS ads_group_id, eg.ads_group_name, ea.id AS ads_id, ea.ad_name
      FROM event_ads_group eg
      LEFT JOIN event_ads_group_pivot egp ON eg.id = egp.ads_group_id
      LEFT JOIN event_ads ea ON egp.ads_id = ea.id
      WHERE eg.user_id = ?
    `;
    
    // Execute the query
    const [event_ads_groups] = await db.query(query, [user_id]);

    // If no results found, return a message
    if (event_ads_groups.length === 0) {
      return res.status(404).json({ message: "No ad groups found for the given user." });
    }

    // Organize the results into a structured format by ads group
    const result = [];
    event_ads_groups.forEach(row => {
      const existingGroup = result.find(group => group.id === row.ads_group_id); // Change here

      if (existingGroup) {
        existingGroup.ads.push({
          ads_id: row.ads_id,
          ad_name: row.ad_name,
        });
      } else {
        result.push({
          id: row.ads_group_id,  // Change here
          ads_group_name: row.ads_group_name,
          ads: [
            {
              ads_id: row.ads_id,
              ad_name: row.ad_name,
            }
          ],
        });
      }
    });

    // Return the structured data
    res.status(200).json(result);
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while fetching the ads",
      error: error.message,
    });
  }
};


const getAdsByGroupId = async (req, res) => {
  const { ads_group_id } = req.query; // Extract ads_group_id from query parameters

  if (!ads_group_id) {
    return res.status(400).json({ message: "Ads Group ID is required" });
  }

  try {
    // Define the query to get ads based on the ads_group_id
    const query = `
      SELECT ea.id AS ads_id, ea.ad_name, ea.media_url AS ads_media_url, ea.ad_url
      FROM event_ads ea
      JOIN event_ads_group_pivot egp ON ea.id = egp.ads_id
      WHERE egp.ads_group_id = ?`;

    // Execute the query
    const [ads] = await db.query(query, [ads_group_id]);

    // If no ads found, return a message
    if (ads.length === 0) {
      return res.status(404).json({ message: "No ads found for the given group ID." });
    }

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

const addEventAdsGroup = async (req, res) => {
    
    try {
  const { ads_group_name, ad_ids } = req.body;
  
  // 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 if ads_group_name is missing
  if (!ads_group_name) {
    console.log('Validation failed: ads_group_name is missing');
    return res.status(400).json({
      message: "Ad Group Name is required!",
      requestBody: req.body // Include the entire request body in the response
    });
  }



  // Check if user_id is missing
  if (!user_id) {
    console.log('Validation failed: user_id is missing');
    return res.status(400).json({ message: "User ID is required!" });
  }

  // Check if ad_ids is an array
  if (!Array.isArray(ad_ids)) {
    console.log('Validation failed: ad_ids is not an array');
    return res.status(400).json({ message: "Ads should be an array!" });
  }

  // Check if ad_ids array is empty
  if (ad_ids.length === 0) {
    console.log('Validation failed: ad_ids array is empty');
    return res.status(400).json({ message: "At least one ad is required!" });
  }

//   if (!ads_group_name || !ad_ids || !user_id || !Array.isArray(ad_ids) || ad_ids.length === 0) {
//     return res.status(400).json({ message: "Ad Group Name, Ads and user are required!" });
//   }

  
    // Insert the new ad group into the event_ads_group table
    const query = `
      INSERT INTO event_ads_group (user_id, ads_group_name)
      VALUES (?, ?)
    `;
    const [result] = await db.query(query, [user_id, ads_group_name]);

    // Get the id of the newly created ads group
    const adsGroupId = result.insertId;

    // Prepare the data for event_ads_group_pivot table
    const pivotData = ad_ids.map(ads_id => [adsGroupId, ads_id]);

    // Insert data into event_ads_group_pivot table
    if (pivotData.length > 0) {
      const pivotQuery = `
        INSERT INTO event_ads_group_pivot (ads_group_id, ads_id)
        VALUES ?
      `;
      await db.query(pivotQuery, [pivotData]);
    }

    // Return success response
    return res.status(201).json({
      message: 'Ad group and ads successfully created!',
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({
      message: 'Server error. Unable to create ad group and ads.',
      error: error.message,
    });
  }
};


const updateEventAdsGroup = async (req, res) => {
  const { ads_group_name, ad_ids } = req.body;
  const { id } = req.params; // Get the ads group ID from the URL parameters

  if (!ads_group_name || !ad_ids || !Array.isArray(ad_ids) || ad_ids.length === 0) {
    return res.status(400).json({ message: "Ad Group Name and Ads are 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 event_ads_group 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: "Ad group not found or you are not authorize to take this action" });
    }    
        
    }
    // Check user authentication to perform action - start    
      
    // Step 1: Check if the event_ads_group exists and if the user is authorized to update it
    const checkGroupQuery = `SELECT * FROM event_ads_group WHERE id = ?`;
    const [existingGroup] = await db.query(checkGroupQuery, [id]);
    
    //     const checkGroupQuery = `SELECT * FROM event_ads_group WHERE id = ? AND user_id = ?`;
    // const [existingGroup] = await db.query(checkGroupQuery, [id, user_id]);

    if (existingGroup.length === 0) {
      return res.status(404).json({ message: "Ad group not found or user not authorized" });
    }

    // Step 2: Update the event_ads_group with the new name
    const updateGroupQuery = `
      UPDATE event_ads_group 
      SET ads_group_name = ? 
      WHERE id = ?
    `;
    await db.query(updateGroupQuery, [ads_group_name, id]);

    // Step 3: Delete the existing ads linked to this group in event_ads_group_pivot
    const deletePivotQuery = `DELETE FROM event_ads_group_pivot WHERE ads_group_id = ?`;
    await db.query(deletePivotQuery, [id]);

    // Step 4: Insert the new ads into the event_ads_group_pivot table
    const pivotData = ad_ids.map(ads_id => [id, ads_id]);

    if (pivotData.length > 0) {
      const pivotQuery = `
        INSERT INTO event_ads_group_pivot (ads_group_id, ads_id)
        VALUES ?
      `;
      await db.query(pivotQuery, [pivotData]);
    }

    // Step 5: Return success response
    return res.status(200).json({
      message: "Ad group and associated ads updated successfully!",
    });
  } catch (error) {
    console.error(error);
    return res.status(500).json({
      message: "Server error. Unable to update ad group and ads.",
      error: error.message,
    });
  }
};


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

  if (!id) {
    return res.status(400).json({ message: "Ads Group 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 event_ads_group 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: "Ad group not found or you are not authorize to take this action" });
    }    
        
    }
    // Check user authentication to perform action - start    
      
    // Ensure the ads group exists before attempting to delete
    const checkQuery = `SELECT * FROM event_ads_group WHERE id = ?`;
    const [existingAdsGroup] = await db.query(checkQuery, [id]);

    if (existingAdsGroup.length === 0) {
      return res.status(404).json({ message: "Ads Group not found for the provided ID!" });
    }

    // Delete the ad group from the event_ads_group table
    const deleteQuery = `DELETE FROM event_ads_group WHERE id = ?`;
    await db.query(deleteQuery, [id]);

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


module.exports = { getEventAdsGroups, getAdsByGroupId, addEventAdsGroup, updateEventAdsGroup, deleteEventAdsGroup};
