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 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
import SimpleLinearRegression from '../utils/SimpleLinearRegression.js';
import Invoice from '../models/InvoiceModel.js';
import Product from '../models/ProductModel.js';
import Service from '../models/ServiceModel.js';
import CatalogItem from '../models/CatalogItemModel.js';
import Supplier from '../models/SupplierModel.js';
import Customer from '../models/CustomerModel.js';
import { resolveScopedBranch } from '../utils/branchContext.js';
import aiCache from '../utils/aiCache.js';

// AI Analytics Controller
export const getSalesAnalytics = async (req, res) => {
   try {
      const tenantId = req.user.tenant._id;
      const { branchFilter } = await resolveScopedBranch(req);
      const { period = '30' } = req.query; // days

      // Check cache first
      const branchId = branchFilter.branch?._id || 'all';
      const cacheKey = { period };
      
      const cachedData = aiCache.get('sales', tenantId, branchId, cacheKey);
      // Temporarily bypass cache to ensure fresh data calculation after bugfix
      // if (cachedData) {
      //    return res.json(cachedData);
      // }

      // Get historical sales data
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - parseInt(period));

      const invoices = await Invoice.find({
         tenant: tenantId,
         ...branchFilter,
         createdAt: { $gte: startDate }
      }).populate('customer items.productId');

      // Process data for ML analysis
      const salesData = [];
      const productPerformance = {};
      const customerBehavior = {};
      const dailySales = {};

      invoices.forEach(invoice => {
         const date = invoice.createdAt.toISOString().split('T')[0];
         dailySales[date] = (dailySales[date] || 0) + invoice.totalAmount;

         invoice.items.forEach(item => {
            const rawId = item.productId?._id || item.productId;
            if (rawId) {
               const productId = rawId.toString();
               if (!productPerformance[productId]) {
                  productPerformance[productId] = {
                     name: item.name,
                     totalSales: 0,
                     quantity: 0,
                     revenue: 0,
                     frequency: 0
                  };
               }
               productPerformance[productId].totalSales += Number(item.total || 0);
               productPerformance[productId].quantity += Number(item.quantity || 1);
               productPerformance[productId].revenue += Number(item.total || 0);
               productPerformance[productId].frequency += 1;
            }
         });

         // Customer behavior analysis
         const customerId = invoice.customer._id;
         if (!customerBehavior[customerId]) {
            customerBehavior[customerId] = {
               totalSpent: 0,
               invoiceCount: 0,
               avgInvoiceValue: 0
            };
         }
         customerBehavior[customerId].totalSpent += invoice.totalAmount;
         customerBehavior[customerId].invoiceCount += 1;
      });

      // Calculate average invoice value
      Object.keys(customerBehavior).forEach(customerId => {
         const behavior = customerBehavior[customerId];
         behavior.avgInvoiceValue = behavior.totalSpent / behavior.invoiceCount;
      });

      // Popular products identification
      const popularProducts = Object.entries(productPerformance)
         .sort(([,a], [,b]) => b.quantity - a.quantity)
         .slice(0, 10)
         .map(([id, data]) => ({ id, ...data }));

      // Sales trend analysis using simple linear regression
      const dates = Object.keys(dailySales).sort();
      const salesValues = dates.map(date => dailySales[date]);
      
      let salesTrend = { slope: 0, r2: 0, prediction: [] };
      if (salesValues.length > 2) {
         const regression = new SimpleLinearRegression(salesValues.map((_, i) => [i]), salesValues);
         salesTrend = {
            slope: regression.coefficients[0] || 0,
            r2: regression.r2 || 0,
            prediction: dates.map((_, i) => regression.predict([i]))
         };
      }

      // Customer segmentation (basic clustering)
      const customers = await Customer.find({ tenant: tenantId, ...branchFilter });
      const customerSegments = performCustomerSegmentation(customers, customerBehavior);

      const result = {
         period: `${period} days`,
         summary: {
            totalRevenue: invoices.reduce((sum, inv) => sum + inv.totalAmount, 0),
            totalInvoices: invoices.length,
            totalCustomers: customers.length,
            avgInvoiceValue: invoices.reduce((sum, inv) => sum + inv.totalAmount, 0) / invoices.length
         },
         popularProducts,
         salesTrend,
         customerSegments,
         dailySales: Object.entries(dailySales).map(([date, sales]) => ({ date, sales })),
         productPerformance: Object.entries(productPerformance).map(([id, data]) => ({ id, ...data }))
      };

      // Store in cache
      aiCache.set('sales', tenantId, branchId, result, cacheKey);
      
      res.json(result);

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

export const getInventoryAnalytics = async (req, res) => {
   try {
      const tenantId = req.user.tenant._id;
      const { branchFilter } = await resolveScopedBranch(req);

      const products = await Product.find({
         tenant: tenantId,
         ...branchFilter
      });

      const inventoryAnalytics = {
         totalProducts: products.length,
         totalStockValue: products.reduce((sum, p) => sum + (p.stock * p.price), 0),
         lowStockItems: products.filter(p => p.stock <= (p.lowStockThreshold || 5) && p.stock > 0).length,
         outOfStockItems: products.filter(p => p.stock <= 0).length,
         stockTurnover: calculateStockTurnover(products),
         categoryDistribution: calculateCategoryDistribution(products)
      };

      // Predict stock depletion for critical items
      const stockPredictions = predictStockDepletion(products);

      res.json({
         ...inventoryAnalytics,
         stockPredictions,
         recommendations: generateInventoryRecommendations(products)
      });

   } catch (error) {
      console.error('Inventory Analytics Error:', error);
      res.status(500).json({ message: 'Failed to generate inventory analytics' });
   }
};

export const getSupplierAnalytics = async (req, res) => {
   try {
      const tenantId = req.user.tenant._id;
      const { branchFilter } = await resolveScopedBranch(req);

      const suppliers = await Supplier.find({
         tenant: tenantId,
         ...branchFilter
      });

      // Analyze supplier performance
      const supplierPerformance = await analyzeSupplierPerformance(suppliers, tenantId, branchFilter);

      res.json({
         totalSuppliers: suppliers.length,
         activeSuppliers: suppliers.filter(s => s.isActive).length,
         supplierPerformance,
         topSuppliers: supplierPerformance.sort((a, b) => b.totalValue - a.totalValue).slice(0, 10)
      });

   } catch (error) {
      console.error('Supplier Analytics Error:', error);
      res.status(500).json({ message: 'Failed to generate supplier analytics' });
   }
};

export const getServiceAnalytics = async (req, res) => {
   try {
      const tenantId = req.user.tenant._id;
      const { branchFilter } = await resolveScopedBranch(req);

      const services = await Service.find({
         tenant: tenantId,
         ...branchFilter
      });

      const serviceAnalytics = {
         totalServices: services.length,
         avgServicePrice: services.reduce((sum, s) => sum + s.price, 0) / services.length,
         serviceCategories: categorizeServices(services),
         revenueDistribution: calculateServiceRevenueDistribution(services, tenantId, branchFilter)
      };

      res.json(serviceAnalytics);

   } catch (error) {
      console.error('Service Analytics Error:', error);
      res.status(500).json({ message: 'Failed to generate service analytics' });
   }
};

export const getPredictiveInsights = async (req, res) => {
   try {
      const tenantId = req.user.tenant._id;
      const { branchFilter } = await resolveScopedBranch(req);
      const { period = '90' } = req.query;

      // Get comprehensive data for predictions
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - parseInt(period));

      const invoices = await Invoice.find({
         tenant: tenantId,
         ...branchFilter,
         createdAt: { $gte: startDate }
      });

      // Generate predictions
      const predictions = {
         nextMonthRevenue: predictNextMonthRevenue(invoices),
         popularProductsNextMonth: predictPopularProducts(invoices),
         customerChurnRisk: predictCustomerChurn(invoices),
         optimalStockLevels: predictOptimalStockLevels(invoices)
      };

      res.json(predictions);

   } catch (error) {
      console.error('Predictive Insights Error:', error);
      res.status(500).json({ message: 'Failed to generate predictive insights' });
   }
};

// Helper functions
function performCustomerSegmentation(customers, behavior) {
   // Simple segmentation based on spending patterns
   const segments = {
      highValue: [],
      regular: [],
      occasional: [],
      new: []
   };

   Object.entries(behavior).forEach(([customerId, data]) => {
      if (data.totalSpent > 10000) {
         segments.highValue.push({ customerId, ...data });
      } else if (data.invoiceCount > 5) {
         segments.regular.push({ customerId, ...data });
      } else if (data.invoiceCount > 1) {
         segments.occasional.push({ customerId, ...data });
      } else {
         segments.new.push({ customerId, ...data });
      }
   });

   return segments;
}

function calculateStockTurnover(products) {
   const totalValue = products.reduce((sum, p) => sum + (p.stock * p.price), 0);
   const avgStockValue = totalValue / products.length;
   return avgStockValue > 0 ? (totalValue / avgStockValue) : 0;
}

function calculateCategoryDistribution(products) {
   const categories = {};
   products.forEach(product => {
      const category = product.category || 'Uncategorized';
      categories[category] = (categories[category] || 0) + 1;
   });
   return categories;
}

function predictStockDepletion(products) {
   return products
      .filter(p => p.stock > 0 && p.stock <= (p.lowStockThreshold || 5) * 2)
      .map(product => ({
         id: product._id,
         name: product.name,
         currentStock: product.stock,
         reorderPoint: product.lowStockThreshold || 5,
         estimatedDaysUntilDepletion: Math.ceil(product.stock / Math.max(1, product.stock / 30)), // Simple estimation
         urgency: product.stock <= (product.lowStockThreshold || 5) ? 'high' : 'medium'
      }));
}

function generateInventoryRecommendations(products) {
   const recommendations = [];
   
   // Low stock recommendations
   const lowStock = products.filter(p => p.stock <= (p.lowStockThreshold || 5));
   if (lowStock.length > 0) {
      recommendations.push({
         type: 'restock',
         priority: 'high',
         message: `${lowStock.length} products need immediate restocking`,
         items: lowStock.slice(0, 5).map(p => ({ id: p._id, name: p.name, stock: p.stock }))
      });
   }

   // Overstock recommendations
   const overstock = products.filter(p => p.stock > (p.lowStockThreshold || 5) * 5);
   if (overstock.length > 0) {
      recommendations.push({
         type: 'promotion',
         priority: 'medium',
         message: `${overstock.length} products have excess inventory`,
         items: overstock.slice(0, 5).map(p => ({ id: p._id, name: p.name, stock: p.stock }))
      });
   }

   return recommendations;
}

async function analyzeSupplierPerformance(suppliers, tenantId, branchFilter) {
   // This would analyze supplier invoices, delivery times, quality metrics
   // For now, returning basic performance metrics
   return suppliers.map(supplier => ({
      id: supplier._id,
      name: supplier.name,
      totalValue: 0, // Would calculate from supplier invoices
      orderCount: 0, // Would count supplier orders
      avgDeliveryTime: 0, // Would calculate from order history
      qualityScore: 4.5 // Would calculate from quality metrics
   }));
}

function categorizeServices(services) {
   const categories = {};
   services.forEach(service => {
      const category = service.category || 'General';
      categories[category] = (categories[category] || 0) + 1;
   });
   return categories;
}

async function calculateServiceRevenueDistribution(services, tenantId, branchFilter) {
   // Calculate revenue distribution by service type
   const distribution = {};
   
   // Get invoices with service items
   const invoices = await Invoice.find({
      tenant: tenantId,
      ...branchFilter,
      'items.type': 'service'
   });

   invoices.forEach(invoice => {
      invoice.items.forEach(item => {
         if (item.type === 'service') {
            const serviceType = item.name || 'Unknown';
            distribution[serviceType] = (distribution[serviceType] || 0) + item.total;
         }
      });
   });

   return distribution;
}

function predictNextMonthRevenue(invoices) {
   if (invoices.length < 2) return { prediction: 0, confidence: 0 };
   
   // Simple linear regression on monthly revenue
   const monthlyData = {};
   invoices.forEach(invoice => {
      const month = invoice.createdAt.toISOString().substring(0, 7);
      monthlyData[month] = (monthlyData[month] || 0) + invoice.totalAmount;
   });

   const months = Object.keys(monthlyData).sort();
   const revenues = months.map(month => monthlyData[month]);
   
   if (revenues.length < 2) return { prediction: revenues[0] || 0, confidence: 0.5 };
   
   const regression = new SimpleLinearRegression(revenues.map((_, i) => [i]), revenues);
   const nextMonthPrediction = regression.predict([revenues.length]);
   
   return {
      prediction: Math.max(0, nextMonthPrediction),
      confidence: Math.min(0.9, Math.max(0.1, regression.r2 || 0.5)),
      trend: regression.coefficients[0] > 0 ? 'increasing' : 'decreasing'
   };
}

function predictPopularProducts(invoices) {
   const productFrequency = {};
   
   invoices.forEach(invoice => {
      invoice.items.forEach(item => {
            const rawId = item.productId?._id || item.productId;
            if (rawId) {
               const productId = rawId.toString();
               if (!productFrequency[productId]) {
                  productFrequency[productId] = {
                     name: item.name,
                     count: 0,
                     quantity: 0,
                     revenue: 0
                  };
               }
               productFrequency[productId].count += 1;
               productFrequency[productId].quantity += Number(item.quantity || 1);
               productFrequency[productId].revenue += Number(item.total || 0);
            }
      });
   });

   return Object.entries(productFrequency)
      .sort(([,a], [,b]) => b.count - a.count)
      .slice(0, 10)
      .map(([id, data]) => ({ productId: id, ...data }));
}

function predictCustomerChurn(invoices) {
   const customerActivity = {};
   
   invoices.forEach(invoice => {
      const customerId = invoice.customer.toString();
      if (!customerActivity[customerId]) {
         customerActivity[customerId] = {
           lastPurchase: invoice.createdAt,
           purchaseCount: 0,
           totalSpent: 0
         };
      }
      
      const activity = customerActivity[customerId];
      if (invoice.createdAt > activity.lastPurchase) {
         activity.lastPurchase = invoice.createdAt;
       }
       activity.purchaseCount += 1;
       activity.totalSpent += invoice.totalAmount;
   });

   // Identify at-risk customers (no purchase in last 30 days)
   const thirtyDaysAgo = new Date();
   thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
   
   const atRiskCustomers = Object.entries(customerActivity)
      .filter(([_, activity]) => activity.lastPurchase < thirtyDaysAgo)
      .map(([customerId, activity]) => ({
         customerId,
         lastPurchase: activity.lastPurchase,
         daysSinceLastPurchase: Math.floor((thirtyDaysAgo - activity.lastPurchase) / (1000 * 60 * 60 * 24)),
         riskLevel: activity.daysSinceLastPurchase > 60 ? 'high' : 'medium'
      }));

   return atRiskCustomers;
}

function predictOptimalStockLevels(invoices) {
   const productDemand = {};
   
   invoices.forEach(invoice => {
      invoice.items.forEach(item => {
         if (item.productId) {
            const productId = item.productId.toString();
            if (!productDemand[productId]) {
               productDemand[productId] = {
                  name: item.name,
                  monthlyDemand: [],
                  totalQuantity: 0
               };
            }
            
            const month = invoice.createdAt.toISOString().substring(0, 7);
            if (!productDemand[productId].monthlyDemand[month]) {
               productDemand[productId].monthlyDemand[month] = 0;
            }
            productDemand[productId].monthlyDemand[month] += item.quantity;
            productDemand[productId].totalQuantity += item.quantity;
         }
      });
   });

   return Object.entries(productDemand).map(([productId, data]) => {
      const demandValues = Object.values(data.monthlyDemand);
      const avgMonthlyDemand = demandValues.length > 0 
         ? demandValues.reduce((sum, val) => sum + val, 0) / demandValues.length 
         : 0;
      
      return {
         productId,
         name: data.name,
         currentMonthlyDemand: avgMonthlyDemand,
         recommendedStock: Math.ceil(avgMonthlyDemand * 1.5), // 1.5 months buffer
         reorderPoint: Math.ceil(avgMonthlyDemand * 0.5) // 2 weeks buffer
      };
   });
}