const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const app = express();
const PORT = 8000;
const JWT_SECRET = 'your-secret-key';

// Middleware
app.use(cors());
app.use(express.json());

// Mock data
let users = [
  {
    id: 1,
    name: 'Admin User',
    email: 'admin@mamanjeri.co.ke',
    password: bcrypt.hashSync('password', 10),
    role: 'admin',
    restaurant_id: 1,
    branch_id: 1,
  },
  {
    id: 2,
    name: 'John Cashier',
    email: 'cashier@mamanjeri.co.ke',
    password: bcrypt.hashSync('password', 10),
    role: 'cashier',
    restaurant_id: 1,
    branch_id: 1,
  },
  {
    id: 3,
    name: 'Mary Kitchen',
    email: 'kitchen@mamanjeri.co.ke',
    password: bcrypt.hashSync('password', 10),
    role: 'kitchen',
    restaurant_id: 1,
    branch_id: 1,
  }
];

let categories = [
  { id: 1, name: 'Main Dishes', slug: 'main-dishes', color: '#EF4444', restaurant_id: 1, active_menu_items_count: 4 },
  { id: 2, name: 'Traditional', slug: 'traditional', color: '#10B981', restaurant_id: 1, active_menu_items_count: 4 },
  { id: 3, name: 'Appetizers', slug: 'appetizers', color: '#F59E0B', restaurant_id: 1, active_menu_items_count: 3 },
  { id: 4, name: 'Beverages', slug: 'beverages', color: '#3B82F6', restaurant_id: 1, active_menu_items_count: 4 },
  { id: 5, name: 'Desserts', slug: 'desserts', color: '#8B5CF6', restaurant_id: 1, active_menu_items_count: 2 },
];

let menuItems = [
  // Main Dishes
  { id: 1, name: 'Nyama Choma', category: categories[0], price: 800, description: 'Grilled meat served with ugali', is_available: true, is_in_stock: true, prep_time: 25, prep_time_display: '25 mins', kitchen_stations: ['grill'], kitchen_stations_display: 'Grill', formatted_price: 'KES 800' },
  { id: 2, name: 'Chicken Curry', category: categories[0], price: 650, description: 'Spicy chicken curry with rice', is_available: true, is_in_stock: true, prep_time: 20, prep_time_display: '20 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 650' },
  { id: 3, name: 'Fish Fillet', category: categories[0], price: 750, description: 'Fresh fish fillet with vegetables', is_available: true, is_in_stock: true, prep_time: 15, prep_time_display: '15 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 750' },
  { id: 4, name: 'Beef Stew', category: categories[0], price: 600, description: 'Traditional beef stew', is_available: true, is_in_stock: true, prep_time: 30, prep_time_display: '30 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 600' },
  
  // Traditional
  { id: 5, name: 'Ugali', category: categories[1], price: 100, description: 'Traditional maize meal', is_available: true, is_in_stock: true, prep_time: 10, prep_time_display: '10 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 100' },
  { id: 6, name: 'Sukuma Wiki', category: categories[1], price: 150, description: 'Collard greens', is_available: true, is_in_stock: true, prep_time: 15, prep_time_display: '15 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 150' },
  { id: 7, name: 'Githeri', category: categories[1], price: 200, description: 'Maize and beans', is_available: true, is_in_stock: true, prep_time: 20, prep_time_display: '20 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 200' },
  { id: 8, name: 'Mukimo', category: categories[1], price: 180, description: 'Mashed potatoes with greens', is_available: true, is_in_stock: true, prep_time: 25, prep_time_display: '25 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 180' },
  
  // Appetizers
  { id: 9, name: 'Samosas', category: categories[2], price: 50, description: 'Crispy pastries with filling', is_available: true, is_in_stock: true, prep_time: 5, prep_time_display: '5 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 50' },
  { id: 10, name: 'Spring Rolls', category: categories[2], price: 80, description: 'Vegetable spring rolls', is_available: true, is_in_stock: true, prep_time: 8, prep_time_display: '8 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 80' },
  { id: 11, name: 'Chicken Wings', category: categories[2], price: 300, description: 'Grilled chicken wings', is_available: true, is_in_stock: true, prep_time: 12, prep_time_display: '12 mins', kitchen_stations: ['grill'], kitchen_stations_display: 'Grill', formatted_price: 'KES 300' },
  
  // Beverages
  { id: 12, name: 'Tusker Beer', category: categories[3], price: 250, description: 'Local beer', is_available: true, is_in_stock: true, prep_time: 1, prep_time_display: '1 min', kitchen_stations: ['bar'], kitchen_stations_display: 'Bar', formatted_price: 'KES 250' },
  { id: 13, name: 'Coca Cola', category: categories[3], price: 120, description: 'Soft drink', is_available: true, is_in_stock: true, prep_time: 1, prep_time_display: '1 min', kitchen_stations: ['bar'], kitchen_stations_display: 'Bar', formatted_price: 'KES 120' },
  { id: 14, name: 'Fresh Juice', category: categories[3], price: 200, description: 'Fresh fruit juice', is_available: true, is_in_stock: true, prep_time: 3, prep_time_display: '3 mins', kitchen_stations: ['bar'], kitchen_stations_display: 'Bar', formatted_price: 'KES 200' },
  { id: 15, name: 'Kenyan Tea', category: categories[3], price: 80, description: 'Traditional tea', is_available: true, is_in_stock: true, prep_time: 5, prep_time_display: '5 mins', kitchen_stations: ['bar'], kitchen_stations_display: 'Bar', formatted_price: 'KES 80' },
  
  // Desserts
  { id: 16, name: 'Ice Cream', category: categories[4], price: 150, description: 'Vanilla ice cream', is_available: true, is_in_stock: true, prep_time: 2, prep_time_display: '2 mins', kitchen_stations: ['bar'], kitchen_stations_display: 'Bar', formatted_price: 'KES 150' },
  { id: 17, name: 'Chocolate Cake', category: categories[4], price: 300, description: 'Rich chocolate cake', is_available: true, is_in_stock: true, prep_time: 5, prep_time_display: '5 mins', kitchen_stations: ['main'], kitchen_stations_display: 'Main Kitchen', formatted_price: 'KES 300' },
];

let tables = [
  { id: 1, name: 'Table 1', section: 'dining', section_display: 'Dining Area', capacity: 4, status: 'available', status_display: 'Available', status_color: '#10B981', is_available: true, is_occupied: false, branch_id: 1 },
  { id: 2, name: 'Table 2', section: 'dining', section_display: 'Dining Area', capacity: 6, status: 'available', status_display: 'Available', status_color: '#10B981', is_available: true, is_occupied: false, branch_id: 1 },
  { id: 3, name: 'Table 3', section: 'bar', section_display: 'Bar Area', capacity: 2, status: 'available', status_display: 'Available', status_color: '#10B981', is_available: true, is_occupied: false, branch_id: 1 },
  { id: 4, name: 'Table 4', section: 'outdoor', section_display: 'Outdoor', capacity: 8, status: 'available', status_display: 'Available', status_color: '#10B981', is_available: true, is_occupied: false, branch_id: 1 },
];

let orders = [];
let customers = [];
let kitchenTickets = [
  {
    id: 1,
    order_id: 1,
    order_number: 'ORD001',
    table_name: 'Table 1',
    order_type: 'dine_in',
    status: 'pending',
    priority: 'normal',
    items: [
      { id: 1, name: 'Nyama Choma', quantity: 2, special_instructions: 'Well done', kitchen_station: 'grill' },
      { id: 2, name: 'Ugali', quantity: 2, special_instructions: null, kitchen_station: 'main' }
    ],
    estimated_time: 25,
    elapsed_time: 5,
    created_at: new Date(Date.now() - 5 * 60000).toISOString(),
    acknowledged_at: null,
    started_at: null,
    ready_at: null
  },
  {
    id: 2,
    order_id: 2,
    order_number: 'ORD002',
    table_name: 'Table 3',
    order_type: 'dine_in',
    status: 'preparing',
    priority: 'high',
    items: [
      { id: 3, name: 'Chicken Curry', quantity: 1, special_instructions: 'Extra spicy', kitchen_station: 'main' },
      { id: 4, name: 'Fresh Juice', quantity: 1, special_instructions: 'Mango', kitchen_station: 'bar' }
    ],
    estimated_time: 20,
    elapsed_time: 12,
    created_at: new Date(Date.now() - 12 * 60000).toISOString(),
    acknowledged_at: new Date(Date.now() - 10 * 60000).toISOString(),
    started_at: new Date(Date.now() - 8 * 60000).toISOString(),
    ready_at: null
  }
];

let inventory = [
  {
    id: 1,
    name: 'Beef (Kg)',
    category: 'Meat',
    current_stock: 25,
    minimum_stock: 10,
    maximum_stock: 100,
    unit: 'kg',
    cost_per_unit: 800,
    supplier: 'Nairobi Meat Suppliers',
    expiry_date: '2025-02-15',
    last_updated: new Date().toISOString(),
    status: 'in_stock'
  },
  {
    id: 2,
    name: 'Chicken (Kg)',
    category: 'Meat',
    current_stock: 8,
    minimum_stock: 15,
    maximum_stock: 80,
    unit: 'kg',
    cost_per_unit: 600,
    supplier: 'Fresh Poultry Ltd',
    expiry_date: '2025-01-25',
    last_updated: new Date().toISOString(),
    status: 'low_stock'
  },
  {
    id: 3,
    name: 'Maize Flour (Kg)',
    category: 'Grains',
    current_stock: 50,
    minimum_stock: 20,
    maximum_stock: 200,
    unit: 'kg',
    cost_per_unit: 120,
    supplier: 'Unga Limited',
    expiry_date: '2025-06-30',
    last_updated: new Date().toISOString(),
    status: 'in_stock'
  },
  {
    id: 4,
    name: 'Cooking Oil (L)',
    category: 'Oils',
    current_stock: 0,
    minimum_stock: 5,
    maximum_stock: 30,
    unit: 'liters',
    cost_per_unit: 350,
    supplier: 'Bidco Africa',
    expiry_date: '2025-08-15',
    last_updated: new Date().toISOString(),
    status: 'out_of_stock'
  },
  {
    id: 5,
    name: 'Tomatoes (Kg)',
    category: 'Vegetables',
    current_stock: 12,
    minimum_stock: 10,
    maximum_stock: 50,
    unit: 'kg',
    cost_per_unit: 80,
    supplier: 'Wakulima Market',
    expiry_date: '2025-01-20',
    last_updated: new Date().toISOString(),
    status: 'expiring_soon'
  }
];

// Auth middleware
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: 'Access token required' });
  }

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ error: 'Invalid token' });
    }
    req.user = user;
    next();
  });
};

// Routes
app.get('/', (req, res) => {
  res.json({
    message: 'Kenyan Restaurant POS API',
    version: '1.0.0',
    status: 'running',
    framework: 'Express + Node.js',
    endpoints: {
      'auth': '/api/auth/*',
      'menu': '/api/menu/*',
      'orders': '/api/orders/*',
      'kitchen': '/api/kitchen/*',
      'inventory': '/api/inventory/*',
      'reports': '/api/reports/*'
    }
  });
});

app.get('/api', (req, res) => {
  res.json({
    message: 'Kenyan Restaurant POS API',
    version: '1.0.0',
    status: 'running',
    framework: 'Express + Node.js',
    endpoints: {
      'auth': '/api/auth/*',
      'menu': '/api/menu/*',
      'orders': '/api/orders/*',
      'kitchen': '/api/kitchen/*',
      'inventory': '/api/inventory/*',
      'reports': '/api/reports/*'
    }
  });
});

app.post('/api/auth/login', async (req, res) => {
  const { email, password } = req.body;
  
  const user = users.find(u => u.email === email);
  if (!user || !bcrypt.compareSync(password, user.password)) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  const token = jwt.sign({ 
    id: user.id, 
    email: user.email, 
    role: user.role,
    restaurant_id: user.restaurant_id,
    branch_id: user.branch_id
  }, JWT_SECRET);

  res.json({
    user: {
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
      role_display: user.role.charAt(0).toUpperCase() + user.role.slice(1),
      restaurant_id: user.restaurant_id,
      branch_id: user.branch_id,
      restaurant: { name: "Mama Njeri's Kitchen" },
      branch: { name: "Main Branch" }
    },
    token
  });
});

app.post('/api/auth/logout', authenticateToken, (req, res) => {
  res.json({ message: 'Logged out successfully' });
});

app.get('/api/auth/user', authenticateToken, (req, res) => {
  const user = users.find(u => u.id === req.user.id);
  res.json({
    id: user.id,
    name: user.name,
    email: user.email,
    role: user.role,
    role_display: user.role.charAt(0).toUpperCase() + user.role.slice(1),
    restaurant_id: user.restaurant_id,
    branch_id: user.branch_id,
    restaurant: { name: "Mama Njeri's Kitchen" },
    branch: { name: "Main Branch" }
  });
});

app.get('/api/menu/categories', authenticateToken, (req, res) => {
  res.json(categories);
});

app.get('/api/menu/items', authenticateToken, (req, res) => {
  let filteredItems = menuItems;
  
  if (req.query.category_id) {
    filteredItems = filteredItems.filter(item => item.category.id == req.query.category_id);
  }
  
  res.json(filteredItems);
});

app.get('/api/tables', authenticateToken, (req, res) => {
  res.json(tables);
});

app.get('/api/orders', authenticateToken, (req, res) => {
  res.json({ orders: orders });
});

app.post('/api/orders', authenticateToken, (req, res) => {
  const order = {
    id: orders.length + 1,
    order_number: `ORD${String(orders.length + 1).padStart(3, '0')}`,
    ...req.body,
    user_id: req.user.id,
    restaurant_id: req.user.restaurant_id,
    branch_id: req.user.branch_id,
    status: 'pending',
    created_at: new Date().toISOString(),
    subtotal: 0,
    tax_amount: 0,
    total_amount: 0
  };
  
  // Calculate totals
  let subtotal = 0;
  const orderItems = [];
  
  if (req.body.items) {
    req.body.items.forEach(item => {
      const menuItem = menuItems.find(m => m.id === item.menu_item_id);
      if (menuItem) {
        subtotal += menuItem.price * item.quantity;
        orderItems.push({
          id: menuItem.id,
          name: menuItem.name,
          quantity: item.quantity,
          special_instructions: item.special_instructions,
          kitchen_station: menuItem.kitchen_stations[0] || 'main'
        });
      }
    });
  }
  
  const taxAmount = subtotal * 0.16;
  const totalAmount = subtotal + taxAmount;
  
  order.subtotal = subtotal;
  order.tax_amount = taxAmount;
  order.total_amount = totalAmount;
  
  orders.push(order);
  
  // Create kitchen ticket
  const kitchenTicket = {
    id: kitchenTickets.length + 1,
    order_id: order.id,
    order_number: order.order_number,
    table_name: order.table_id ? tables.find(t => t.id == order.table_id)?.name || 'Unknown' : 'Takeaway',
    order_type: order.type,
    status: 'pending',
    priority: 'normal',
    items: orderItems,
    estimated_time: Math.max(...orderItems.map(item => {
      const menuItem = menuItems.find(m => m.id === item.id);
      return menuItem ? menuItem.prep_time : 15;
    })),
    elapsed_time: 0,
    created_at: new Date().toISOString(),
    acknowledged_at: null,
    started_at: null,
    ready_at: null
  };
  
  kitchenTickets.push(kitchenTicket);
  
  res.status(201).json({
    message: 'Order created successfully',
    order,
    kitchen_ticket: kitchenTicket
  });
});

app.get('/api/customers/search/:phone', authenticateToken, (req, res) => {
  const customer = customers.find(c => c.phone.includes(req.params.phone));
  res.json({ customer: customer || null });
});

app.post('/api/customers', authenticateToken, (req, res) => {
  const customer = {
    id: customers.length + 1,
    ...req.body,
    restaurant_id: req.user.restaurant_id,
    total_orders: 0,
    total_spent: 0,
    customer_type: 'New',
    formatted_phone: req.body.phone,
    created_at: new Date().toISOString()
  };
  
  customers.push(customer);
  
  res.status(201).json({
    message: 'Customer created successfully',
    customer
  });
});

// Kitchen routes
app.get('/api/kitchen/tickets', authenticateToken, (req, res) => {
  const enhancedTickets = kitchenTickets.map(ticket => ({
    ...ticket,
    status_display: ticket.status.charAt(0).toUpperCase() + ticket.status.slice(1),
    priority_display: ticket.priority.charAt(0).toUpperCase() + ticket.priority.slice(1),
    priority_color: {
      urgent: '#EF4444',
      high: '#F59E0B', 
      normal: '#10B981',
      low: '#6B7280'
    }[ticket.priority],
    status_color: {
      pending: '#F59E0B',
      acknowledged: '#3B82F6',
      preparing: '#8B5CF6',
      ready: '#10B981',
      served: '#6B7280'
    }[ticket.status],
    formatted_time: `${Math.floor(ticket.elapsed_time / 60)}:${(ticket.elapsed_time % 60).toString().padStart(2, '0')}`,
    is_overdue: ticket.elapsed_time > ticket.estimated_time,
    time_remaining: Math.max(0, ticket.estimated_time - ticket.elapsed_time)
  }));
  
  res.json({ tickets: enhancedTickets });
});

app.put('/api/kitchen/tickets/:id/acknowledge', authenticateToken, (req, res) => {
  const ticketId = parseInt(req.params.id);
  const ticket = kitchenTickets.find(t => t.id === ticketId);
  
  if (!ticket) {
    return res.status(404).json({ error: 'Ticket not found' });
  }
  
  ticket.status = 'acknowledged';
  ticket.acknowledged_at = new Date().toISOString();
  
  res.json({ message: 'Ticket acknowledged', ticket });
});

app.put('/api/kitchen/tickets/:id/start', authenticateToken, (req, res) => {
  const ticketId = parseInt(req.params.id);
  const ticket = kitchenTickets.find(t => t.id === ticketId);
  
  if (!ticket) {
    return res.status(404).json({ error: 'Ticket not found' });
  }
  
  ticket.status = 'preparing';
  ticket.started_at = new Date().toISOString();
  
  res.json({ message: 'Ticket started', ticket });
});

app.put('/api/kitchen/tickets/:id/ready', authenticateToken, (req, res) => {
  const ticketId = parseInt(req.params.id);
  const ticket = kitchenTickets.find(t => t.id === ticketId);
  
  if (!ticket) {
    return res.status(404).json({ error: 'Ticket not found' });
  }
  
  ticket.status = 'ready';
  ticket.ready_at = new Date().toISOString();
  
  res.json({ message: 'Ticket ready', ticket });
});

app.put('/api/kitchen/tickets/:id/priority', authenticateToken, (req, res) => {
  const ticketId = parseInt(req.params.id);
  const { priority } = req.body;
  const ticket = kitchenTickets.find(t => t.id === ticketId);
  
  if (!ticket) {
    return res.status(404).json({ error: 'Ticket not found' });
  }
  
  ticket.priority = priority;
  
  res.json({ message: 'Priority updated', ticket });
});

app.get('/api/kitchen/stats', authenticateToken, (req, res) => {
  const stats = {
    pending: kitchenTickets.filter(t => t.status === 'pending').length,
    preparing: kitchenTickets.filter(t => t.status === 'preparing').length,
    ready: kitchenTickets.filter(t => t.status === 'ready').length,
    completed_today: 15, // Mock data
    average_prep_time: kitchenTickets.length > 0 
      ? Math.round(kitchenTickets.reduce((sum, t) => sum + t.elapsed_time, 0) / kitchenTickets.length)
      : 0,
    overdue_tickets: kitchenTickets.filter(t => t.elapsed_time > t.estimated_time).length
  };
  
  res.json(stats);
});

// Inventory routes
app.get('/api/inventory', authenticateToken, (req, res) => {
  const enhancedInventory = inventory.map(item => ({
    ...item,
    formatted_cost: `KES ${item.cost_per_unit.toLocaleString()}`,
    total_value: item.current_stock * item.cost_per_unit,
    formatted_total_value: `KES ${(item.current_stock * item.cost_per_unit).toLocaleString()}`,
    stock_percentage: Math.round((item.current_stock / item.maximum_stock) * 100),
    days_until_expiry: item.expiry_date ? Math.ceil((new Date(item.expiry_date) - new Date()) / (1000 * 60 * 60 * 24)) : null,
    status_color: {
      in_stock: '#10B981',
      low_stock: '#F59E0B',
      out_of_stock: '#EF4444',
      expiring_soon: '#F97316'
    }[item.status],
    status_display: item.status.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())
  }));
  
  res.json({ items: enhancedInventory });
});

app.post('/api/inventory', authenticateToken, (req, res) => {
  const newItem = {
    id: inventory.length + 1,
    ...req.body,
    last_updated: new Date().toISOString(),
    status: req.body.current_stock <= 0 ? 'out_of_stock' 
           : req.body.current_stock <= req.body.minimum_stock ? 'low_stock' 
           : 'in_stock'
  };
  
  inventory.push(newItem);
  
  res.status(201).json({
    message: 'Inventory item created successfully',
    item: newItem
  });
});

app.put('/api/inventory/:id/adjust', authenticateToken, (req, res) => {
  const itemId = parseInt(req.params.id);
  const { adjustment_type, quantity, reason } = req.body;
  const item = inventory.find(i => i.id === itemId);
  
  if (!item) {
    return res.status(404).json({ error: 'Item not found' });
  }
  
  const oldStock = item.current_stock;
  
  switch (adjustment_type) {
    case 'increase':
      item.current_stock += quantity;
      break;
    case 'decrease':
      item.current_stock = Math.max(0, item.current_stock - quantity);
      break;
    case 'set':
      item.current_stock = quantity;
      break;
  }
  
  // Update status
  item.status = item.current_stock <= 0 ? 'out_of_stock' 
               : item.current_stock <= item.minimum_stock ? 'low_stock' 
               : 'in_stock';
  
  item.last_updated = new Date().toISOString();
  
  res.json({
    message: 'Stock adjusted successfully',
    item,
    old_stock: oldStock,
    new_stock: item.current_stock,
    adjustment: item.current_stock - oldStock
  });
});

app.get('/api/inventory/summary/stats', authenticateToken, (req, res) => {
  const stats = {
    total_items: inventory.length,
    low_stock_items: inventory.filter(i => i.status === 'low_stock').length,
    out_of_stock_items: inventory.filter(i => i.status === 'out_of_stock').length,
    expiring_items: inventory.filter(i => i.status === 'expiring_soon').length,
    total_value: inventory.reduce((sum, item) => sum + (item.current_stock * item.cost_per_unit), 0),
    formatted_total_value: `KES ${inventory.reduce((sum, item) => sum + (item.current_stock * item.cost_per_unit), 0).toLocaleString()}`
  };
  
  res.json(stats);
});

app.get('/api/inventory/alerts/all', authenticateToken, (req, res) => {
  const alerts = {
    low_stock: inventory.filter(i => i.status === 'low_stock').map(item => ({
      ...item,
      alert_type: 'Low Stock',
      message: `${item.name} is running low (${item.current_stock} ${item.unit} remaining)`
    })),
    out_of_stock: inventory.filter(i => i.status === 'out_of_stock').map(item => ({
      ...item,
      alert_type: 'Out of Stock',
      message: `${item.name} is out of stock`
    })),
    expiring_soon: inventory.filter(i => i.status === 'expiring_soon').map(item => ({
      ...item,
      alert_type: 'Expiring Soon',
      message: `${item.name} expires on ${item.expiry_date}`
    })),
    expired: inventory.filter(i => {
      return i.expiry_date && new Date(i.expiry_date) < new Date();
    }).map(item => ({
      ...item,
      alert_type: 'Expired',
      message: `${item.name} expired on ${item.expiry_date}`
    }))
  };
  
  res.json(alerts);
});

// Reports routes
app.get('/api/reports/sales', authenticateToken, (req, res) => {
  // Mock sales data for demonstration
  const salesData = {
    total_orders: 45,
    total_revenue: 125000,
    average_order_value: 2778,
    total_tax: 20000,
    formatted_revenue: 'KES 125,000',
    formatted_average: 'KES 2,778',
    formatted_tax: 'KES 20,000',
    order_types: {
      dine_in: { count: 25, percentage: 55.6, revenue: 75000 },
      takeaway: { count: 15, percentage: 33.3, revenue: 35000 },
      delivery: { count: 5, percentage: 11.1, revenue: 15000 }
    },
    payment_methods: {
      cash: { count: 20, percentage: 44.4, amount: 55000 },
      mpesa: { count: 18, percentage: 40.0, amount: 50000 },
      card: { count: 7, percentage: 15.6, amount: 20000 }
    },
    daily_sales: {
      '2025-01-17': { orders: 45, revenue: 125000 },
      '2025-01-16': { orders: 38, revenue: 98000 },
      '2025-01-15': { orders: 42, revenue: 115000 },
      '2025-01-14': { orders: 35, revenue: 87000 },
      '2025-01-13': { orders: 40, revenue: 105000 }
    }
  };
  
  res.json(salesData);
});

app.get('/api/reports/top-items', authenticateToken, (req, res) => {
  const topItems = [
    { 
      id: 1, 
      name: 'Nyama Choma', 
      category: 'Main Dishes',
      quantity_sold: 25, 
      revenue: 20000,
      formatted_revenue: 'KES 20,000',
      percentage: 16.0
    },
    { 
      id: 2, 
      name: 'Chicken Curry', 
      category: 'Main Dishes',
      quantity_sold: 18, 
      revenue: 11700,
      formatted_revenue: 'KES 11,700',
      percentage: 9.4
    },
    { 
      id: 3, 
      name: 'Ugali', 
      category: 'Traditional',
      quantity_sold: 35, 
      revenue: 3500,
      formatted_revenue: 'KES 3,500',
      percentage: 2.8
    },
    { 
      id: 4, 
      name: 'Tusker Beer', 
      category: 'Beverages',
      quantity_sold: 22, 
      revenue: 5500,
      formatted_revenue: 'KES 5,500',
      percentage: 4.4
    },
    { 
      id: 5, 
      name: 'Fish Fillet', 
      category: 'Main Dishes',
      quantity_sold: 12, 
      revenue: 9000,
      formatted_revenue: 'KES 9,000',
      percentage: 7.2
    }
  ];
  
  res.json(topItems);
});

app.get('/api/reports/staff', authenticateToken, (req, res) => {
  const staffPerformance = [
    {
      id: 1,
      name: 'John Cashier',
      role: 'Cashier',
      orders_handled: 25,
      total_sales: 65000,
      formatted_sales: 'KES 65,000',
      average_order_value: 2600,
      formatted_average: 'KES 2,600',
      shift_hours: 8,
      performance_score: 92
    },
    {
      id: 2,
      name: 'Mary Kitchen',
      role: 'Kitchen Staff',
      orders_handled: 45,
      total_sales: 0, // Kitchen staff don't handle sales directly
      formatted_sales: 'N/A',
      average_prep_time: 18,
      formatted_average: '18 mins',
      shift_hours: 8,
      performance_score: 88
    },
    {
      id: 3,
      name: 'Admin User',
      role: 'Admin',
      orders_handled: 20,
      total_sales: 60000,
      formatted_sales: 'KES 60,000',
      average_order_value: 3000,
      formatted_average: 'KES 3,000',
      shift_hours: 10,
      performance_score: 95
    }
  ];
  
  res.json(staffPerformance);
});

app.get('/api/reports/customers', authenticateToken, (req, res) => {
  const customerAnalytics = {
    total_customers: 125,
    new_customers: 15,
    repeat_customers: 110,
    average_customer_value: 2500,
    formatted_average_value: 'KES 2,500',
    customer_types: {
      new: { count: 15, percentage: 12.0 },
      regular: { count: 85, percentage: 68.0 },
      vip: { count: 25, percentage: 20.0 }
    },
    top_customers: [
      { name: 'James Mwangi', orders: 15, total_spent: 45000, formatted_spent: 'KES 45,000' },
      { name: 'Grace Wanjiku', orders: 12, total_spent: 38000, formatted_spent: 'KES 38,000' },
      { name: 'Peter Kamau', orders: 10, total_spent: 32000, formatted_spent: 'KES 32,000' }
    ]
  };
  
  res.json(customerAnalytics);
});

app.get('/api/reports/inventory', authenticateToken, (req, res) => {
  const inventoryReport = {
    summary: {
      total_items: inventory.length,
      total_value: inventory.reduce((sum, item) => sum + (item.current_stock * item.cost_per_unit), 0),
      formatted_total_value: `KES ${inventory.reduce((sum, item) => sum + (item.current_stock * item.cost_per_unit), 0).toLocaleString()}`,
      low_stock_items: inventory.filter(i => i.status === 'low_stock').length,
      out_of_stock_items: inventory.filter(i => i.status === 'out_of_stock').length,
      expiring_items: inventory.filter(i => i.status === 'expiring_soon').length
    },
    by_category: {
      'Meat': {
        items: inventory.filter(i => i.category === 'Meat').length,
        value: inventory.filter(i => i.category === 'Meat').reduce((sum, item) => sum + (item.current_stock * item.cost_per_unit), 0)
      },
      'Vegetables': {
        items: inventory.filter(i => i.category === 'Vegetables').length,
        value: inventory.filter(i => i.category === 'Vegetables').reduce((sum, item) => sum + (item.current_stock * item.cost_per_unit), 0)
      },
      'Grains': {
        items: inventory.filter(i => i.category === 'Grains').length,
        value: inventory.filter(i => i.category === 'Grains').reduce((sum, item) => sum + (item.current_stock * item.cost_per_unit), 0)
      }
    }
  };
  
  res.json(inventoryReport);
});

app.get('/api/reports/financial', authenticateToken, (req, res) => {
  const financialSummary = {
    revenue: {
      gross_sales: 125000,
      tax_collected: 20000,
      discounts_given: 5000,
      net_sales: 100000,
      formatted_gross: 'KES 125,000',
      formatted_tax: 'KES 20,000',
      formatted_discounts: 'KES 5,000',
      formatted_net: 'KES 100,000'
    },
    orders: {
      total_orders: 45,
      completed_orders: 42,
      cancelled_orders: 3,
      pending_orders: 0,
      completion_rate: 93.3
    },
    payments: {
      cash: { amount: 55000, percentage: 44.0, formatted: 'KES 55,000' },
      mpesa: { amount: 50000, percentage: 40.0, formatted: 'KES 50,000' },
      card: { amount: 20000, percentage: 16.0, formatted: 'KES 20,000' }
    },
    costs: {
      food_cost: 35000,
      labor_cost: 25000,
      overhead: 15000,
      total_costs: 75000,
      formatted_food: 'KES 35,000',
      formatted_labor: 'KES 25,000',
      formatted_overhead: 'KES 15,000',
      formatted_total: 'KES 75,000'
    },
    profit: {
      gross_profit: 90000,
      net_profit: 25000,
      profit_margin: 25.0,
      formatted_gross: 'KES 90,000',
      formatted_net: 'KES 25,000'
    }
  };
  
  res.json(financialSummary);
});

app.listen(PORT, () => {
  console.log(`🚀 Kenyan POS Backend running on http://localhost:${PORT}`);
  console.log(`📊 API endpoints available at http://localhost:${PORT}/api`);
  console.log(`\n👤 Test Users:`);
  console.log(`   Admin: admin@mamanjeri.co.ke / password`);
  console.log(`   Cashier: cashier@mamanjeri.co.ke / password`);
  console.log(`   Kitchen: kitchen@mamanjeri.co.ke / password`);
});