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
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import bcrypt from 'bcryptjs';
import User from '../models/UserModel.js';
import Tenant from '../models/TenantModel.js';
import Invoice from '../models/InvoiceModel.js';
import Customer from '../models/CustomerModel.js';
import Product from '../models/ProductModel.js';
import pkg from 'ml.js';
const { MLRegression, MLClustering } = pkg;

// Reset tenant user password
export const resetTenantPassword = async (req, res) => {
  try {
    const { tenantId, userId } = req.params;
    const { newPassword, notifyUser } = req.body;

    // Validate super admin access
    if (req.user.role !== 'super_admin') {
      return res.status(403).json({ message: 'Access denied. Super admin required.' });
    }

    // Find the user and verify they belong to the tenant
    const user = await User.findOne({ _id: userId, tenant: tenantId });
    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }

    // Validate new password
    if (!newPassword || newPassword.length < 6) {
      return res.status(400).json({ message: 'Password must be at least 6 characters long' });
    }

    // Hash the new password
    const hashedPassword = await bcrypt.hash(newPassword, 12);

    // Update user password
    await User.findByIdAndUpdate(userId, { 
      password: hashedPassword,
      passwordResetAt: new Date(),
      passwordResetBy: req.user._id
    });

    // Log the password reset action
    console.log(`Password reset for user ${user.username} (tenant: ${tenantId}) by super admin ${req.user.username}`);

    res.status(200).json({ 
      message: 'Password reset successfully',
      user: {
        id: user._id,
        username: user.username,
        fullName: user.fullName,
        role: user.role
      }
    });

  } catch (error) {
    console.error('Password reset error:', error);
    res.status(500).json({ message: 'Failed to reset password' });
  }
};

// Get comprehensive tenant analytics for Super Admin
export const getTenantAnalytics = async (req, res) => {
  try {
    // Validate super admin access
    if (req.user.role !== 'super_admin') {
      return res.status(403).json({ message: 'Access denied. Super admin required.' });
    }

    const { period = '30', tenantId } = req.query;
    const daysAgo = new Date();
    daysAgo.setDate(daysAgo.getDate() - parseInt(period));

    // Get all tenants with their statistics
    const tenants = await Tenant.aggregate([
      {
        $lookup: {
          from: 'users',
          localField: '_id',
          foreignField: 'tenant',
          as: 'users'
        }
      },
      {
        $lookup: {
          from: 'invoices',
          localField: '_id',
          foreignField: 'tenant',
          as: 'invoices'
        }
      },
      {
        $lookup: {
          from: 'customers',
          localField: '_id',
          foreignField: 'tenant',
          as: 'customers'
        }
      },
      {
        $lookup: {
          from: 'products',
          localField: '_id',
          foreignField: 'tenant',
          as: 'products'
        }
      }
    ]);

    // Calculate analytics for each tenant
    const tenantAnalytics = tenants.map(tenant => {
      const activeUsers = tenant.users.filter(user => user.isActive).length;
      const totalUsers = tenant.users.length;
      const recentInvoices = tenant.invoices.filter(inv => 
        new Date(inv.createdAt) >= daysAgo
      );
      const recentCustomers = tenant.customers.filter(customer => 
        new Date(customer.createdAt) >= daysAgo
      );
      
      // Calculate growth metrics
      const previousPeriodStart = new Date(daysAgo);
      previousPeriodStart.setDate(previousPeriodStart.getDate() - parseInt(period));
      
      const previousInvoices = tenant.invoices.filter(inv => 
        new Date(inv.createdAt) >= previousPeriodStart && new Date(inv.createdAt) < daysAgo
      );

      const currentRevenue = recentInvoices.reduce((sum, inv) => sum + (inv.totalAmount || 0), 0);
      const previousRevenue = previousInvoices.reduce((sum, inv) => sum + (inv.totalAmount || 0), 0);
      const revenueGrowth = previousRevenue > 0 ? ((currentRevenue - previousRevenue) / previousRevenue) * 100 : 0;

      // Calculate feature adoption
      const featuresUsed = {
        invoices: recentInvoices.length > 0,
        customers: recentCustomers.length > 0,
        products: tenant.products.length > 0,
        multipleUsers: totalUsers > 1
      };

      const adoptionScore = Object.values(featuresUsed).filter(Boolean).length / Object.keys(featuresUsed).length * 100;

      return {
        tenantId: tenant._id,
        tenantName: tenant.name,
        tenantSlug: tenant.slug,
        status: tenant.status,
        subscriptionPackage: tenant.subscriptionPackage,
        metrics: {
          totalUsers,
          activeUsers,
          totalCustomers: tenant.customers.length,
          newCustomers: recentCustomers.length,
          totalProducts: tenant.products.length,
          totalInvoices: tenant.invoices.length,
          recentInvoices: recentInvoices.length,
          currentRevenue,
          previousRevenue,
          revenueGrowth: Math.round(revenueGrowth * 100) / 100,
          adoptionScore: Math.round(adoptionScore),
          featuresUsed
        },
        createdAt: tenant.createdAt
      };
    });

    // Aggregate global analytics
    const globalMetrics = {
      totalTenants: tenants.length,
      activeTenants: tenants.filter(t => t.status === 'active').length,
      totalUsers: tenants.reduce((sum, t) => sum + t.users.length, 0),
      totalCustomers: tenants.reduce((sum, t) => sum + t.customers.length, 0),
      totalProducts: tenants.reduce((sum, t) => sum + t.products.length, 0),
      totalInvoices: tenants.reduce((sum, t) => sum + t.invoices.length, 0),
      totalRevenue: tenants.reduce((sum, t) => sum + t.invoices.reduce((invSum, inv) => invSum + (inv.totalAmount || 0), 0), 0)
    };

    // AI-powered insights and recommendations
    const insights = await generateAIInsights(tenantAnalytics, globalMetrics);

    res.status(200).json({
      period: `${period} days`,
      globalMetrics,
      tenantAnalytics,
      insights,
      generatedAt: new Date()
    });

  } catch (error) {
    console.error('Tenant analytics error:', error);
    res.status(500).json({ message: 'Failed to generate tenant analytics' });
  }
};

// Generate AI-powered insights and recommendations
const generateAIInsights = async (tenantAnalytics, globalMetrics) => {
  const insights = {
    performance: [],
    growth: [],
    recommendations: [],
    alerts: []
  };

  // Performance insights
  const highPerformers = tenantAnalytics
    .filter(t => t.metrics.revenueGrowth > 20)
    .sort((a, b) => b.metrics.revenueGrowth - a.metrics.revenueGrowth)
    .slice(0, 5);

  if (highPerformers.length > 0) {
    insights.performance.push({
      type: 'top_performers',
      title: 'أفضل الأداء',
      description: 'العملاء الذين حققوا أعلى نمو في الإيرادات',
      data: highPerformers.map(t => ({
        tenantName: t.tenantName,
        growth: t.metrics.revenueGrowth,
        revenue: t.metrics.currentRevenue
      }))
    });
  }

  // Growth insights
  const averageGrowth = tenantAnalytics.reduce((sum, t) => sum + t.metrics.revenueGrowth, 0) / tenantAnalytics.length;
  
  if (averageGrowth > 0) {
    insights.growth.push({
      type: 'positive_growth',
      title: 'نمو إيجابي',
      description: `متوسط نمو الإيرادات: ${averageGrowth.toFixed(1)}%`,
      level: averageGrowth > 10 ? 'high' : averageGrowth > 5 ? 'medium' : 'low'
    });
  }

  // Feature adoption insights
  const averageAdoption = tenantAnalytics.reduce((sum, t) => sum + t.metrics.adoptionScore, 0) / tenantAnalytics.length;
  
  if (averageAdoption < 60) {
    insights.recommendations.push({
      type: 'feature_adoption',
      title: 'تحسين تبني الميزات',
      description: 'بعض العملاء لا يستخدمون جميع الميزات المتاحة',
      priority: 'medium',
      action: 'إرسال دليل استخدام الميزات للعملاء'
    });
  }

  // Low usage alerts
  const lowUsageTenants = tenantAnalytics.filter(t => 
    t.metrics.recentInvoices === 0 && t.status === 'active'
  );

  if (lowUsageTenants.length > 0) {
    insights.alerts.push({
      type: 'low_usage',
      title: 'انخفاض الاستخدام',
      description: `${lowUsageTenants.length} عملاء نشطين لم يقوموا بأي فواتير مؤخراً`,
      priority: 'high',
      data: lowUsageTenants.map(t => t.tenantName)
    });
  }

  // Package upgrade recommendations
  const nearLimitTenants = tenantAnalytics.filter(t => {
    const packageKey = t.subscriptionPackage?.key || 'basic';
    const limit = t.subscriptionPackage?.cashierLimit || 1;
    const usage = t.metrics.activeUsers;
    return usage >= limit * 0.8;
  });

  if (nearLimitTenants.length > 0) {
    insights.recommendations.push({
      type: 'package_upgrade',
      title: 'ترقية الباقة',
      description: `${nearLimitTenants.length} عملاء يقتربون من حدود باقتهم`,
      priority: 'medium',
      action: 'اقتراح ترقية الباقة لهؤلاء العملاء'
    });
  }

  // System optimization suggestions
  if (globalMetrics.totalTenants > 50) {
    insights.recommendations.push({
      type: 'system_optimization',
      title: 'تحسين النظام',
      description: 'عدد كبير من العملاء قد يتطلب تحسينات في الأداء',
      priority: 'low',
      action: 'مراجعة تحسينات قاعدة البيانات وذاكرة التخزين المؤقت'
    });
  }

  // New feature suggestions based on usage patterns
  const invoiceFrequency = tenantAnalytics.reduce((sum, t) => sum + t.metrics.recentInvoices, 0) / tenantAnalytics.length;
  
  if (invoiceFrequency > 50) {
    insights.recommendations.push({
      type: 'feature_suggestion',
      title: 'اقتراح ميزة جديدة',
      description: 'العملاء النشطون قد يستفيدون من ميزات الفوترة المتقدمة',
      priority: 'low',
      features: ['الفواتير المتكررة', 'الجدولة التلقائية', 'التقارير المتقدمة']
    });
  }

  return insights;
};

// Get system-wide usage trends
export const getUsageTrends = async (req, res) => {
  try {
    // Validate super admin access
    if (req.user.role !== 'super_admin') {
      return res.status(403).json({ message: 'Access denied. Super admin required.' });
    }

    const { period = '90' } = req.query;
    const daysAgo = new Date();
    daysAgo.setDate(daysAgo.getDate() - parseInt(period));

    // Get daily usage data
    const dailyData = await Invoice.aggregate([
      {
        $match: {
          createdAt: { $gte: daysAgo }
        }
      },
      {
        $group: {
          _id: {
            $dateToString: {
              format: "%Y-%m-%d",
              date: "$createdAt"
            }
          },
          invoiceCount: { $sum: 1 },
          totalRevenue: { $sum: "$totalAmount" },
          uniqueTenants: { $addToSet: "$tenant" }
        }
      },
      {
        $addFields: {
          tenantCount: { $size: "$uniqueTenants" }
        }
      },
      {
        $sort: { _id: 1 }
      }
    ]);

    // Get tenant registration trends
    const registrationData = await Tenant.aggregate([
      {
        $match: {
          createdAt: { $gte: daysAgo }
        }
      },
      {
        $group: {
          _id: {
            $dateToString: {
              format: "%Y-%m-%d",
              date: "$createdAt"
            }
          },
          newTenants: { $sum: 1 }
        }
      },
      {
        $sort: { _id: 1 }
      }
    ]);

    res.status(200).json({
      period: `${period} days`,
      dailyData,
      registrationData,
      generatedAt: new Date()
    });

  } catch (error) {
    console.error('Usage trends error:', error);
    res.status(500).json({ message: 'Failed to generate usage trends' });
  }
};

// Update tenant business types (multi-select: restaurant, cafe, sales)
export const updateTenantType = async (req, res) => {
  try {
    // Validate super admin access
    if (req.user.role !== 'super_admin') {
      return res.status(403).json({
        status: 'error',
        message: 'رفع الوصول. مدير النظام فقط'
      });
    }

    const { tenantId } = req.params;
    const { tenantTypes } = req.body;

    // Validate tenant types (must be array)
    if (!tenantTypes || !Array.isArray(tenantTypes) || tenantTypes.length === 0) {
      return res.status(400).json({
        status: 'error',
        message: 'يجب تحديد نوع عمل واحد على الأقل. أرسل مصفوفة: ["restaurant", "cafe", "sales"]'
      });
    }

    // Validate each type
    const validTypes = ['restaurant', 'cafe', 'sales'];
    for (const type of tenantTypes) {
      if (!validTypes.includes(type)) {
        return res.status(400).json({
          status: 'error',
          message: `نوع عمل غير صحيح: ${type}. الأنواع الصحيحة: restaurant أو cafe أو sales`
        });
      }
    }

    // Remove duplicates
    const uniqueTypes = [...new Set(tenantTypes)];

    // Check if tenant exists
    const tenant = await Tenant.findById(tenantId);
    if (!tenant) {
      return res.status(404).json({
        status: 'error',
        message: 'لم يتم العثور على حساب العمل'
      });
    }

    // Update tenant types
    const updatedTenant = await Tenant.findByIdAndUpdate(
      tenantId,
      { tenantTypes: uniqueTypes },
      { new: true, runValidators: true }
    );

    res.status(200).json({
      status: 'success',
      message: 'تم تحديث أنواع العمل بنجاح',
      data: {
        tenantId: updatedTenant._id,
        tenantName: updatedTenant.name,
        tenantTypes: updatedTenant.tenantTypes,
        updatedAt: updatedTenant.updatedAt
      }
    });

  } catch (error) {
    console.error('Update tenant types error:', error);
    res.status(500).json({
      status: 'error',
      message: 'فشل تحديث أنواع العمل'
    });
  }
};

// Get all tenants with features
export const getAllTenants = async (req, res) => {
  try {
    // Validate super admin access
    if (req.user.role !== 'super_admin') {
      return res.status(403).json({
        status: 'error',
        message: 'رفع الوصول. مدير النظام فقط'
      });
    }

    const { status, type } = req.query;
    const filter = {};

    if (status) filter.status = status;
    if (type) filter.tenantType = type;

    const tenants = await Tenant.find(filter)
      .select('_id name slug tenantTypes status subscriptionPackage createdAt monthlyFee ownerName ownerEmail')
      .sort({ createdAt: -1 });

    res.status(200).json({
      status: 'success',
      data: tenants,
      total: tenants.length
    });

  } catch (error) {
    console.error('Get tenants error:', error);
    res.status(500).json({
      status: 'error',
      message: 'فشل جلب قائمة العملاء'
    });
  }
};