import db from '../config/database.js';

export const getAllSalesmen = async (req, res) => {
  try {
    const [salesmen] = await db.query(
      'SELECT id, role, full_name, contact_number, email, designation, photo_url, created_at FROM profiles WHERE role = ?',
      ['salesman']
    );
    res.json(salesmen);
  } catch (error) {
    console.error('Get salesmen error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};

export const getSalesmanStats = async (req, res) => {
  try {
    const { id } = req.params;

    const [totalCustomers] = await db.query(
      'SELECT COUNT(*) as count FROM customers WHERE assigned_to = ?',
      [id]
    );

    const [contacted] = await db.query(
      'SELECT COUNT(*) as count FROM customers WHERE assigned_to = ? AND status = ?',
      [id, 'contacted']
    );

    const [converted] = await db.query(
      'SELECT COUNT(*) as count FROM customers WHERE assigned_to = ? AND status = ?',
      [id, 'converted']
    );

    const [pendingFollowUps] = await db.query(
      'SELECT COUNT(*) as count FROM follow_ups WHERE salesman_id = ? AND completed = FALSE',
      [id]
    );

    res.json({
      totalCustomers: totalCustomers[0].count,
      contacted: contacted[0].count,
      converted: converted[0].count,
      pendingFollowUps: pendingFollowUps[0].count
    });
  } catch (error) {
    console.error('Get salesman stats error:', error);
    res.status(500).json({ error: 'Server error' });
  }
};
