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 getDashboardData = 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 
      
    // Fetch the role of the user from the database
    const roleQuery = `SELECT role FROM users WHERE id = ?`;
    const [userRoleResult] = await db.query(roleQuery, [user_id]);

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

    const role = userRoleResult[0].role; // Extract role from the result

    let query;
    let params = [];

    if (role === 'super_admin') {
      // If the role is super_admin, fetch all moderators and admins
      query = `SELECT * FROM users WHERE role IN ('admin')`;
    } else if (role === 'admin') {
      // If the role is admin, fetch all moderators created by the admin
      query = `SELECT * FROM users WHERE role = 'moderator' AND created_by = ?`;
      params.push(user_id); // Pass the admin's user_id for filtering
    } else {
      return res.status(403).json({
        message: "You do not have the required permissions to access this resource.",
      });
    }

    const [users] = await db.query(query, params); // Execute the query with appropriate parameters

    // Fetch additional data
    // Get total events created by the user
    const totalEventsQuery = `SELECT COUNT(*) AS total_events FROM events WHERE user_id = ?`;
    const [totalEventsResult] = await db.query(totalEventsQuery, [user_id]);
    const total_events = totalEventsResult[0].total_events;

    // Get total event posts linked to the user's events
    const totalEventPostsQuery = `
      SELECT COUNT(*) AS total_event_posts 
      FROM event_posts 
      WHERE event_id IN (SELECT id FROM events WHERE user_id = ?)
    `;
    const [totalEventPostsResult] = await db.query(totalEventPostsQuery, [user_id]);
    const total_event_posts = totalEventPostsResult[0].total_event_posts;

    // Get total event posts with status 'approved' linked to the user's events
    const totalEventApprovedPostsQuery = `
      SELECT COUNT(*) AS total_event_approved_posts 
      FROM event_posts 
      WHERE event_id IN (SELECT id FROM events WHERE user_id = ?) 
      AND status = 'approve'
    `;
    const [totalEventApprovedPostsResult] = await db.query(totalEventApprovedPostsQuery, [user_id]);
    const total_event_approved_posts = totalEventApprovedPostsResult[0].total_event_approved_posts;

    // Get total users in the system
    const totalUsersQuery = `SELECT COUNT(*) AS total_users FROM users`;
    const [totalUsersResult] = await db.query(totalUsersQuery);
    const total_users = totalUsersResult[0].total_users;

    // Send the response with all the data
    res.status(200).json({
      users,
      total_events,
      total_event_posts,
      total_event_approved_posts,
      total_users
    });
  } catch (error) {
    res.status(500).json({
      message: "An error occurred while fetching the data",
      error,
    });
  }
};


module.exports = { getDashboardData };
