const { pool } = require('../config/database');
class DashboardController {
    // Get comprehensive dashboard statistics
    static async getDashboardStats(req, res, next) {
        try {
            const userId = req.user.id;
            const userRole = req.user.role;
            const roleName = (userRole || '').toLowerCase();
            const isAdminLike = roleName.includes('admin');
            const isSuperAdmin = (user) => {
                if (!user)
                    return false;
                const roleName = (user.role || '').toLowerCase();
                return user.role_id === 1 || roleName === 'super admin' || roleName === 'super_admin';
            };
            const requestedOrgId = (() => {
                const v = req.query.organization_id;
                if (v === undefined || v === null || v === '')
                    return null;
                const n = Number(v);
                return Number.isNaN(n) ? null : n;
            })();
            const organizationId = (() => {
                if (isSuperAdmin(req.user)) {
                    return requestedOrgId || null;
                }
                if (isAdminLike) {
                    return requestedOrgId || req.user.organization_id;
                }
                return req.user.organization_id;
            })();
            // Get basic statistics
            const [totalContacts, activeConversations, onlineContacts, securityAlerts, recentActivity, conversationStats, userStats] = await Promise.all([
                DashboardController.getTotalContacts(userId, isAdminLike, organizationId),
                DashboardController.getActiveConversations(userId, isAdminLike, organizationId),
                DashboardController.getOnlineContacts(userId, isAdminLike, organizationId),
                DashboardController.getSecurityAlerts(userId, isAdminLike, organizationId),
                DashboardController.getRecentActivity(userId, isAdminLike, organizationId),
                DashboardController.getConversationStats(userId, isAdminLike, organizationId),
                DashboardController.getUserStats(userId, isAdminLike, organizationId)
            ]);
            res.status(200).json({
                status: 'success',
                data: {
                    totalContacts,
                    activeConversations,
                    onlineContacts,
                    securityAlerts,
                    recentActivity,
                    conversationStats,
                    userStats,
                    contacts: {
                        new_contacts_30d: (totalContacts && totalContacts.new_contacts_30d) ? totalContacts.new_contacts_30d : 0,
                        total_contacts: (totalContacts && totalContacts.total_contacts) ? totalContacts.total_contacts : 0,
                        active_contacts: (totalContacts && typeof totalContacts.active_contacts !== 'undefined') ? totalContacts.active_contacts : null,
                        inactive_contacts: (totalContacts && typeof totalContacts.inactive_contacts !== 'undefined') ? totalContacts.inactive_contacts : null
                    },
                    users: {
                        admin_users: userStats ? (userStats.admins || 0) : 0,
                        view_users: userStats ? (userStats.regular_users || 0) : 0
                    },
                    timestamp: new Date().toISOString()
                }
            });
        }
        catch (error) {
            next(error);
        }
    }
    // Get total contacts count
    static async getTotalContacts(userId, isAdminLike, organizationId) {
        try {
            let query = `
        SELECT 
          COUNT(*) as total_contacts
        FROM contacts c
        WHERE 1=1
      `;
            const params = [];
            let hasOrgColumn = false;
            let hasActiveColumn = false;
            try {
                const [cols] = await pool.execute(`SELECT COLUMN_NAME 
           FROM INFORMATION_SCHEMA.COLUMNS 
           WHERE TABLE_SCHEMA = DATABASE() 
             AND TABLE_NAME = 'contacts' 
             AND COLUMN_NAME IN ('organization_id','is_active')`);
                const names = new Set((cols || []).map(r => r.COLUMN_NAME));
                hasOrgColumn = names.has('organization_id');
                hasActiveColumn = names.has('is_active');
            }
            catch (_) { }
            if (organizationId && hasOrgColumn) {
                query += ' AND c.organization_id = ?';
                params.push(organizationId);
            }
            const [baseRows] = await pool.execute(query, params);
            const base = baseRows[0] || { total_contacts: 0 };
            const cutoff30d = new Date();
            cutoff30d.setDate(cutoff30d.getDate() - 30);
            const cutoffStr30d = cutoff30d.toISOString().slice(0, 10); // YYYY-MM-DD
            const cutoff7d = new Date();
            cutoff7d.setDate(cutoff7d.getDate() - 7);
            const cutoffStr7d = cutoff7d.toISOString().slice(0, 10);
            let newQuery = `
        SELECT 
          COUNT(CASE WHEN DATE(c.created_at) >= ? THEN 1 END) as new_contacts_30d,
          COUNT(CASE WHEN DATE(c.created_at) >= ? THEN 1 END) as new_contacts_7d
        FROM contacts c
        WHERE 1=1
      `;
            const newParams = [cutoffStr30d, cutoffStr7d];
            if (organizationId && hasOrgColumn) {
                newQuery += ' AND c.organization_id = ?';
                newParams.push(organizationId);
            }
            const [newRows] = await pool.execute(newQuery, newParams);
            const extras = newRows[0] || { new_contacts_30d: 0, new_contacts_7d: 0 };
            let active = { active_contacts: 0, inactive_contacts: 0 };
            if (hasActiveColumn) {
                let actQuery = `
          SELECT 
            COUNT(CASE WHEN c.is_active = 1 THEN 1 END) as active_contacts,
            COUNT(CASE WHEN c.is_active = 0 THEN 1 END) as inactive_contacts
          FROM contacts c
          WHERE 1=1
        `;
                const actParams = [];
                if (organizationId && hasOrgColumn) {
                    actQuery += ' AND c.organization_id = ?';
                    actParams.push(organizationId);
                }
                const [actRows] = await pool.execute(actQuery, actParams);
                active = actRows[0] || active;
            }
            return { ...base, ...extras, ...active };
        }
        catch (error) {
            throw new Error(`Error getting total contacts: ${error.message}`);
        }
    }
    // Get active conversations
    static async getActiveConversations(userId, isAdminLike, organizationId) {
        try {
            let query, params;
            if (isAdminLike) {
                if (organizationId) {
                    query = `
            SELECT 
              COUNT(DISTINCT c.id) as total_conversations,
              COUNT(DISTINCT CASE WHEN c.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN c.id END) as active_24h,
              COUNT(DISTINCT CASE WHEN c.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN c.id END) as active_7d,
              COUNT(DISTINCT CASE WHEN c.type = 'direct' THEN c.id END) as direct_conversations,
              COUNT(DISTINCT CASE WHEN c.type = 'group' THEN c.id END) as group_conversations
            FROM conversations c
            WHERE c.organization_id = ?
          `;
                    params = [organizationId];
                }
                else {
                    query = `
            SELECT 
              COUNT(DISTINCT c.id) as total_conversations,
              COUNT(DISTINCT CASE WHEN c.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN c.id END) as active_24h,
              COUNT(DISTINCT CASE WHEN c.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN c.id END) as active_7d,
              COUNT(DISTINCT CASE WHEN c.type = 'direct' THEN c.id END) as direct_conversations,
              COUNT(DISTINCT CASE WHEN c.type = 'group' THEN c.id END) as group_conversations
            FROM conversations c
          `;
                    params = [];
                }
            }
            else {
                // Regular users see their conversations in their organization
                query = `
          SELECT 
            COUNT(DISTINCT c.id) as total_conversations,
            COUNT(DISTINCT CASE WHEN c.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN c.id END) as active_24h,
            COUNT(DISTINCT CASE WHEN c.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN c.id END) as active_7d,
            COUNT(DISTINCT CASE WHEN c.type = 'direct' THEN c.id END) as direct_conversations,
            COUNT(DISTINCT CASE WHEN c.type = 'group' THEN c.id END) as group_conversations
          FROM conversations c
          JOIN conversation_participants cp ON c.id = cp.conversation_id
          WHERE cp.user_id = ? AND c.organization_id = ?
        `;
                params = [userId, organizationId];
            }
            const [rows] = await pool.execute(query, params);
            return rows[0];
        }
        catch (error) {
            throw new Error(`Error getting active conversations: ${error.message}`);
        }
    }
    // Get online contacts
    static async getOnlineContacts(userId, isAdminLike, organizationId) {
        try {
            let query, params;
            if (isAdminLike) {
                if (organizationId) {
                    query = `
            SELECT 
              COUNT(CASE WHEN status = 'online' THEN 1 END) as online_now,
              COUNT(CASE WHEN status = 'busy' THEN 1 END) as busy_now,
              COUNT(CASE WHEN status = 'offline' THEN 1 END) as offline_now,
              COUNT(CASE WHEN last_seen >= DATE_SUB(NOW(), INTERVAL 5 MINUTE) THEN 1 END) as recently_active,
              COUNT(CASE WHEN last_seen >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 END) as active_1h,
              COUNT(CASE WHEN last_seen >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as active_24h
            FROM users
            WHERE is_active = 1 AND organization_id = ?
          `;
                    params = [organizationId];
                }
                else {
                    query = `
            SELECT 
              COUNT(CASE WHEN status = 'online' THEN 1 END) as online_now,
              COUNT(CASE WHEN status = 'busy' THEN 1 END) as busy_now,
              COUNT(CASE WHEN status = 'offline' THEN 1 END) as offline_now,
              COUNT(CASE WHEN last_seen >= DATE_SUB(NOW(), INTERVAL 5 MINUTE) THEN 1 END) as recently_active,
              COUNT(CASE WHEN last_seen >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 END) as active_1h,
              COUNT(CASE WHEN last_seen >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as active_24h
            FROM users
            WHERE is_active = 1
          `;
                    params = [];
                }
            }
            else {
                // Regular users see online contacts they can communicate with in their organization
                query = `
          SELECT 
            COUNT(CASE WHEN u.status = 'online' THEN 1 END) as online_now,
            COUNT(CASE WHEN u.status = 'busy' THEN 1 END) as busy_now,
            COUNT(CASE WHEN u.status = 'offline' THEN 1 END) as offline_now,
            COUNT(CASE WHEN u.last_seen >= DATE_SUB(NOW(), INTERVAL 5 MINUTE) THEN 1 END) as recently_active,
            COUNT(CASE WHEN u.last_seen >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 END) as active_1h,
            COUNT(CASE WHEN u.last_seen >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as active_24h
          FROM users u
          WHERE u.id != ? AND u.is_active = 1 AND u.organization_id = ?
        `;
                params = [userId, organizationId];
            }
            const [rows] = await pool.execute(query, params);
            return rows[0];
        }
        catch (error) {
            throw new Error(`Error getting online contacts: ${error.message}`);
        }
    }
    // Get security alerts
    static async getSecurityAlerts(userId, isAdminLike, organizationId) {
        try {
            let query, params;
            if (isAdminLike) {
                if (organizationId) {
                    query = `
            SELECT 
              COUNT(CASE WHEN action LIKE '%LOGIN%' AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as failed_logins_24h,
              COUNT(CASE WHEN action LIKE '%LOGIN%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as failed_logins_7d,
              COUNT(CASE WHEN action LIKE '%PASSWORD%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as password_changes_7d,
              COUNT(CASE WHEN action LIKE '%DELETE%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as deletions_7d,
              COUNT(CASE WHEN action LIKE '%ADMIN%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as admin_actions_7d,
              COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 END) as total_activities_1h,
              COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as total_activities_24h
            FROM audit_logs
            WHERE organization_id = ?
          `;
                    params = [organizationId];
                }
                else {
                    query = `
            SELECT 
              COUNT(CASE WHEN action LIKE '%LOGIN%' AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as failed_logins_24h,
              COUNT(CASE WHEN action LIKE '%LOGIN%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as failed_logins_7d,
              COUNT(CASE WHEN action LIKE '%PASSWORD%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as password_changes_7d,
              COUNT(CASE WHEN action LIKE '%DELETE%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as deletions_7d,
              COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 END) as total_activities_1h,
              COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as total_activities_24h
            FROM audit_logs
          `;
                    params = [];
                }
            }
            else {
                // Regular users see their own security activities
                query = `
          SELECT 
            COUNT(CASE WHEN action LIKE '%LOGIN%' AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as failed_logins_24h,
            COUNT(CASE WHEN action LIKE '%LOGIN%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as failed_logins_7d,
            COUNT(CASE WHEN action LIKE '%PASSWORD%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as password_changes_7d,
            COUNT(CASE WHEN action LIKE '%DELETE%' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as deletions_7d,
            0 as admin_actions_7d,
            COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 END) as total_activities_1h,
            COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) THEN 1 END) as total_activities_24h
          FROM audit_logs
          WHERE user_id = ? AND organization_id = ?
        `;
                params = [userId, organizationId];
            }
            const [rows] = await pool.execute(query, params);
            return rows[0];
        }
        catch (error) {
            throw new Error(`Error getting security alerts: ${error.message}`);
        }
    }
    // Get recent activity
    static async getRecentActivity(userId, isAdminLike, organizationId) {
        try {
            let query, params;
            if (isAdminLike) {
                if (organizationId) {
                    query = `
            SELECT 
              al.action,
              al.target_type,
              al.target_name,
              al.details,
              al.created_at,
              u.name as user_name,
              r.name as user_rank
            FROM audit_logs al
            JOIN users u ON al.user_id = u.id
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE al.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
              AND al.organization_id = ?
            ORDER BY al.created_at DESC
            LIMIT 10
          `;
                    params = [organizationId];
                }
                else {
                    query = `
            SELECT 
              al.action,
              al.target_type,
              al.target_name,
              al.details,
              al.created_at,
              u.name as user_name,
              r.name as user_rank
            FROM audit_logs al
            JOIN users u ON al.user_id = u.id
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE al.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
            ORDER BY al.created_at DESC
            LIMIT 10
          `;
                    params = [];
                }
            }
            else {
                // Regular users see their own recent activities
                query = `
          SELECT 
            al.action,
            al.target_type,
            al.target_name,
            al.details,
            al.created_at,
            u.name as user_name,
            r.name as user_rank
          FROM audit_logs al
          JOIN users u ON al.user_id = u.id
          LEFT JOIN roles r ON u.role_id = r.id
          WHERE al.user_id = ? AND al.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
            AND al.organization_id = ?
          ORDER BY al.created_at DESC
          LIMIT 10
        `;
                params = [userId, organizationId];
            }
            const [rows] = await pool.execute(query, params);
            return rows;
        }
        catch (error) {
            throw new Error(`Error getting recent activity: ${error.message}`);
        }
    }
    // Get conversation statistics
    static async getConversationStats(userId, isAdminLike, _organizationId) {
        try {
            let query, params;
            if (isAdminLike) {
                query = `
          SELECT 
            COUNT(m.id) as total_messages_24h,
            COUNT(DISTINCT m.sender_id) as unique_senders_24h,
            COUNT(DISTINCT m.conversation_id) as active_conversations_24h,
            COUNT(CASE WHEN m.type = 'text' THEN 1 END) as text_messages_24h,
            COUNT(CASE WHEN m.type = 'system' THEN 1 END) as system_messages_24h
          FROM messages m
          WHERE m.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        `;
                params = [];
            }
            else {
                // Regular users see their conversation stats
                query = `
          SELECT 
            COUNT(m.id) as total_messages_24h,
            COUNT(DISTINCT m.sender_id) as unique_senders_24h,
            COUNT(DISTINCT m.conversation_id) as active_conversations_24h,
            COUNT(CASE WHEN m.type = 'text' THEN 1 END) as text_messages_24h,
            COUNT(CASE WHEN m.type = 'system' THEN 1 END) as system_messages_24h
          FROM messages m
          JOIN conversation_participants cp ON m.conversation_id = cp.conversation_id
          WHERE cp.user_id = ? AND m.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
        `;
                params = [userId];
            }
            const [rows] = await pool.execute(query, params);
            return rows[0];
        }
        catch (error) {
            throw new Error(`Error getting conversation stats: ${error.message}`);
        }
    }
    // Get user statistics
    static async getUserStats(userId, isAdminLike, organizationId) {
        try {
            let query, params;
            if (isAdminLike) {
                if (organizationId) {
                    query = `
            SELECT 
              COUNT(CASE WHEN r.id = 1 THEN 1 END) as super_admins,
              COUNT(CASE WHEN r.name LIKE '%admin%' AND r.id != 1 THEN 1 END) as admins,
              COUNT(CASE WHEN (r.name IS NULL OR r.name NOT LIKE '%admin%') AND (r.id IS NULL OR r.id != 1) THEN 1 END) as regular_users,
              0 as army_users,
              0 as navy_users,
              0 as air_force_users,
              COUNT(CASE WHEN u.updated_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as active_users_7d
            FROM users u
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE u.organization_id = ? AND u.is_active = 1
          `;
                    params = [organizationId];
                }
                else {
                    query = `
            SELECT 
              COUNT(CASE WHEN r.id = 1 THEN 1 END) as super_admins,
              COUNT(CASE WHEN r.name LIKE '%admin%' AND r.id != 1 THEN 1 END) as admins,
              COUNT(CASE WHEN (r.name IS NULL OR r.name NOT LIKE '%admin%') AND (r.id IS NULL OR r.id != 1) THEN 1 END) as regular_users,
              0 as army_users,
              0 as navy_users,
              0 as air_force_users,
              COUNT(CASE WHEN u.updated_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as active_users_7d
            FROM users u
            LEFT JOIN roles r ON u.role_id = r.id
            WHERE u.is_active = 1
          `;
                    params = [];
                }
            }
            else {
                // Regular users see limited stats
                query = `
          SELECT 
            COUNT(CASE WHEN r.id = 1 THEN 1 END) as super_admins,
            COUNT(CASE WHEN r.name LIKE '%admin%' AND r.id != 1 THEN 1 END) as admins,
            COUNT(CASE WHEN (r.name IS NULL OR r.name NOT LIKE '%admin%') AND (r.id IS NULL OR r.id != 1) THEN 1 END) as regular_users,
            0 as army_users,
            0 as navy_users,
            0 as air_force_users,
            COUNT(CASE WHEN u.updated_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as active_users_7d
          FROM users u
          LEFT JOIN roles r ON u.role_id = r.id
          WHERE u.is_active = 1 AND u.id != ?
        `;
                params = [userId];
            }
            const [rows] = await pool.execute(query, params);
            const baseStats = rows[0];
            // Compute New Users (30d) from contacts table, org-scoped when applicable
            let hasOrgColumn = false;
            try {
                const [colRows] = await pool.execute(`SELECT COUNT(*) as cnt 
           FROM INFORMATION_SCHEMA.COLUMNS 
           WHERE TABLE_SCHEMA = DATABASE() 
             AND TABLE_NAME = 'contacts' 
             AND COLUMN_NAME = 'organization_id'`);
                hasOrgColumn = (colRows[0]?.cnt || 0) > 0;
            }
            catch (_) { }
            const cutoff30d = new Date();
            cutoff30d.setDate(cutoff30d.getDate() - 30);
            const cutoffStr30d = cutoff30d.toISOString().slice(0, 10); // YYYY-MM-DD
            let contactsQuery = `
        SELECT COUNT(*) as new_users_30d
        FROM contacts c
        WHERE DATE(c.created_at) >= ?
      `;
            const contactsParams = [cutoffStr30d];
            if (organizationId && hasOrgColumn) {
                contactsQuery += ' AND c.organization_id = ?';
                contactsParams.push(organizationId);
            }
            try {
                const [contactRows] = await pool.execute(contactsQuery, contactsParams);
                baseStats.new_users_30d = contactRows[0]?.new_users_30d || 0;
            }
            catch (_) {
                // Fallback: if contacts table not available, keep existing or set 0
                baseStats.new_users_30d = baseStats.new_users_30d || 0;
            }
            return baseStats;
        }
        catch (error) {
            throw new Error(`Error getting user stats: ${error.message}`);
        }
    }
    // Get detailed dashboard data for charts and analytics
    static async getDashboardAnalytics(req, res, next) {
        try {
            const userId = req.user.id;
            const userRole = req.user.role;
            const { period = '7d' } = req.query; // 7d, 30d, 90d
            const [userActivityChart, conversationChart, messageChart, securityChart] = await Promise.all([
                DashboardController.getUserActivityChart(period, userRole, userId),
                DashboardController.getConversationChart(period, userRole, userId),
                DashboardController.getMessageChart(period, userRole, userId),
                DashboardController.getSecurityChart(period, userRole, userId)
            ]);
            res.status(200).json({
                status: 'success',
                data: {
                    userActivityChart,
                    conversationChart,
                    messageChart,
                    securityChart,
                    period,
                    timestamp: new Date().toISOString()
                }
            });
        }
        catch (error) {
            next(error);
        }
    }
    // Get user activity chart data
    static async getUserActivityChart(period, userRole, userId = null) {
        try {
            const days = period === '7d' ? 7 : period === '30d' ? 30 : 90;
            let query, params;
            if (userRole === 'Super_admin' || userRole === 'Admin') {
                query = `
          SELECT 
            DATE(created_at) as date,
            COUNT(*) as new_users,
            COUNT(CASE WHEN status = 'online' THEN 1 END) as online_users
          FROM users
          WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
          GROUP BY DATE(created_at)
          ORDER BY date DESC
        `;
                params = [days];
            }
            else {
                query = `
          SELECT 
            DATE(created_at) as date,
            COUNT(*) as new_users,
            COUNT(CASE WHEN status = 'online' THEN 1 END) as online_users
          FROM users
          WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY) AND id != ?
          GROUP BY DATE(created_at)
          ORDER BY date DESC
        `;
                params = [days, userId];
            }
            const [rows] = await pool.execute(query, params);
            return rows;
        }
        catch (error) {
            throw new Error(`Error getting user activity chart: ${error.message}`);
        }
    }
    // Get conversation chart data
    static async getConversationChart(period, userRole, userId = null) {
        try {
            const days = period === '7d' ? 7 : period === '30d' ? 30 : 90;
            let query, params;
            if (userRole === 'Super_admin' || userRole === 'Admin') {
                query = `
          SELECT 
            DATE(created_at) as date,
            COUNT(*) as new_conversations,
            COUNT(CASE WHEN type = 'direct' THEN 1 END) as direct_conversations,
            COUNT(CASE WHEN type = 'group' THEN 1 END) as group_conversations
          FROM conversations
          WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
          GROUP BY DATE(created_at)
          ORDER BY date DESC
        `;
                params = [days];
            }
            else {
                query = `
          SELECT 
            DATE(c.created_at) as date,
            COUNT(DISTINCT c.id) as new_conversations,
            COUNT(DISTINCT CASE WHEN c.type = 'direct' THEN c.id END) as direct_conversations,
            COUNT(DISTINCT CASE WHEN c.type = 'group' THEN c.id END) as group_conversations
          FROM conversations c
          JOIN conversation_participants cp ON c.id = cp.conversation_id
          WHERE c.created_at >= DATE_SUB(NOW(), INTERVAL ? DAY) AND cp.user_id = ?
          GROUP BY DATE(c.created_at)
          ORDER BY date DESC
        `;
                params = [days, userId];
            }
            const [rows] = await pool.execute(query, params);
            return rows;
        }
        catch (error) {
            throw new Error(`Error getting conversation chart: ${error.message}`);
        }
    }
    // Get message chart data
    static async getMessageChart(period, userRole, userId = null) {
        try {
            const days = period === '7d' ? 7 : period === '30d' ? 30 : 90;
            let query, params;
            if (userRole === 'Super_admin' || userRole === 'Admin') {
                query = `
          SELECT 
            DATE(created_at) as date,
            COUNT(*) as total_messages,
            COUNT(CASE WHEN type = 'text' THEN 1 END) as text_messages,
            COUNT(CASE WHEN type = 'system' THEN 1 END) as system_messages,
            COUNT(DISTINCT sender_id) as unique_senders
          FROM messages
          WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
          GROUP BY DATE(created_at)
          ORDER BY date DESC
        `;
                params = [days];
            }
            else {
                query = `
          SELECT 
            DATE(m.created_at) as date,
            COUNT(m.id) as total_messages,
            COUNT(CASE WHEN m.type = 'text' THEN 1 END) as text_messages,
            COUNT(CASE WHEN m.type = 'system' THEN 1 END) as system_messages,
            COUNT(DISTINCT m.sender_id) as unique_senders
          FROM messages m
          JOIN conversation_participants cp ON m.conversation_id = cp.conversation_id
          WHERE m.created_at >= DATE_SUB(NOW(), INTERVAL ? DAY) AND cp.user_id = ?
          GROUP BY DATE(m.created_at)
          ORDER BY date DESC
        `;
                params = [days, userId];
            }
            const [rows] = await pool.execute(query, params);
            return rows;
        }
        catch (error) {
            throw new Error(`Error getting message chart: ${error.message}`);
        }
    }
    // Get security chart data
    static async getSecurityChart(period, userRole, userId = null) {
        try {
            const days = period === '7d' ? 7 : period === '30d' ? 30 : 90;
            let query, params;
            if (userRole === 'Super_admin' || userRole === 'Admin') {
                query = `
          SELECT 
            DATE(created_at) as date,
            COUNT(*) as total_activities,
            COUNT(CASE WHEN action LIKE '%LOGIN%' THEN 1 END) as login_activities,
            COUNT(CASE WHEN action LIKE '%PASSWORD%' THEN 1 END) as password_activities,
            COUNT(CASE WHEN action LIKE '%DELETE%' THEN 1 END) as delete_activities
          FROM audit_logs
          WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
          GROUP BY DATE(created_at)
          ORDER BY date DESC
        `;
                params = [days];
            }
            else {
                query = `
          SELECT 
            DATE(created_at) as date,
            COUNT(*) as total_activities,
            COUNT(CASE WHEN action LIKE '%LOGIN%' THEN 1 END) as login_activities,
            COUNT(CASE WHEN action LIKE '%PASSWORD%' THEN 1 END) as password_activities,
            COUNT(CASE WHEN action LIKE '%DELETE%' THEN 1 END) as delete_activities
          FROM audit_logs
          WHERE user_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
          GROUP BY DATE(created_at)
          ORDER BY date DESC
        `;
                params = [userId, days];
            }
            const [rows] = await pool.execute(query, params);
            return rows;
        }
        catch (error) {
            throw new Error(`Error getting security chart: ${error.message}`);
        }
    }
}
module.exports = DashboardController;
//# sourceMappingURL=dashboardController.js.map