const db = require('../config/db');

// Get store order activity summary and orders
const getStoreOrderActivity = async (req, res) => {
  try {
    const { store_id, from_date, to_date } = req.query;
    
    // console.log('Store order activity request:', { store_id, from_date, to_date });
    
    if (!store_id) {
      return res.status(400).json({ success: false, msg: 'Store ID is required' });
    }

    // Set default dates to today if not provided
    const fromDate = from_date || new Date().toISOString().split('T')[0];
    const toDate = to_date || new Date().toISOString().split('T')[0];

    // Get order summary counts
    const [summaryRows] = await db.query(`
      SELECT 
        SUM(CASE WHEN order_status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
        SUM(CASE WHEN order_status = 'delivered' THEN 1 ELSE 0 END) as delivered_orders,
        SUM(CASE WHEN order_status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_orders
      FROM orders 
      WHERE store_id = ? AND DATE(created_at) BETWEEN ? AND ?
    `, [store_id, fromDate, toDate]);

    // Get detailed orders with user and item information
    const [orderRows] = await db.query(`
      SELECT 
        o.id,
        o.order_number,
        o.total_amount,
        o.final_total,
        o.order_status,
        o.created_at as order_date,
        u.name as customer_name,
        u.email as customer_email,
        u.phone as customer_phone
      FROM orders o
      LEFT JOIN users u ON o.user_id = u.id
      WHERE o.store_id = ? AND DATE(o.created_at) BETWEEN ? AND ?
      ORDER BY o.created_at DESC
    `, [store_id, fromDate, toDate]);

    // Get items for each order
    const ordersWithItems = await Promise.all(
      orderRows.map(async (order) => {
        const [itemRows] = await db.query(`
          SELECT 
            oi.quantity,
            oi.price,
            oi.total_price,
            i.name as item_name,
            i.description as item_description
          FROM order_items oi
          LEFT JOIN items i ON oi.item_id = i.id
          WHERE oi.order_id = ?
        `, [order.id]);

        return {
          ...order,
          items: itemRows
        };
      })
    );

    const summary = summaryRows[0] || {
      pending_orders: 0,
      delivered_orders: 0,
      cancelled_orders: 0
    };

    res.json({
      success: true,
      data: {
        summary,
        orders: ordersWithItems,
        filters: {
          store_id: parseInt(store_id),
          from_date: fromDate,
          to_date: toDate
        }
      }
    });
  } catch (error) {
    console.error('Error fetching store order activity:', error);
    res.status(500).json({ success: false, msg: 'Error fetching store order activity' });
  }
};

// Get all stores for dropdown
const getAllStoresForDropdown = async (req, res) => {
  try {
    // console.log('Fetching stores for dropdown...');
    const [rows] = await db.query(
      'SELECT id, name FROM stores WHERE status = 1 ORDER BY name ASC'
    );
    // console.log('Stores found:', rows);
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('Error fetching stores:', error);
    res.status(500).json({ success: false, msg: 'Error fetching stores' });
  }
};

module.exports = {
  getStoreOrderActivity,
  getAllStoresForDropdown
};
