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

// Get all delivery boy cash collections
const getAllDeliveryBoyCash = async (req, res) => {
  try {
    const [rows] = await db.query(`
      SELECT dc.*, db.name as delivery_boy_name, db.phone as delivery_boy_phone, 
             b.name as bonus_name, o.order_number
      FROM delivery_boy_cash dc 
      LEFT JOIN delivery_boys db ON dc.delivery_boy_id = db.id 
      LEFT JOIN bonuses b ON dc.bonus_id = b.id
      LEFT JOIN orders o ON dc.order_id = o.id
      ORDER BY dc.collected_at DESC
    `);
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('Error fetching delivery boy cash collections:', error);
    res.status(500).json({ success: false, msg: 'Error fetching delivery boy cash collections' });
  }
};

// Get delivery boy cash collection by ID
const getDeliveryBoyCashById = async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await db.query(`
      SELECT dc.*, db.name as delivery_boy_name, db.phone as delivery_boy_phone, 
             b.name as bonus_name, o.order_number
      FROM delivery_boy_cash dc 
      LEFT JOIN delivery_boys db ON dc.delivery_boy_id = db.id 
      LEFT JOIN bonuses b ON dc.bonus_id = b.id
      LEFT JOIN orders o ON dc.order_id = o.id
      WHERE dc.id = ?
    `, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({ success: false, msg: 'Cash collection record not found' });
    }
    
    res.json({ success: true, data: rows[0] });
  } catch (error) {
    console.error('Error fetching cash collection record:', error);
    res.status(500).json({ success: false, msg: 'Error fetching cash collection record' });
  }
};

// Create new delivery boy cash collection
const createDeliveryBoyCash = async (req, res) => {
  try {
    const { delivery_boy_id, order_id, final_total, amount, type, bonus_id, message, collected_at } = req.body;
    
    if (!delivery_boy_id || !amount || !type) {
      return res.status(400).json({ success: false, msg: 'Delivery boy ID, amount and type are required' });
    }
    
    const [result] = await db.query(
      'INSERT INTO delivery_boy_cash (delivery_boy_id, order_id, final_total, amount, type, bonus_id, message, collected_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [delivery_boy_id, order_id, final_total, amount, type, bonus_id, message, collected_at || new Date()]
    );
    
    const [newCashRecord] = await db.query(`
      SELECT dc.*, db.name as delivery_boy_name, db.phone as delivery_boy_phone, 
             b.name as bonus_name, o.order_number
      FROM delivery_boy_cash dc 
      LEFT JOIN delivery_boys db ON dc.delivery_boy_id = db.id 
      LEFT JOIN bonuses b ON dc.bonus_id = b.id
      LEFT JOIN orders o ON dc.order_id = o.id
      WHERE dc.id = ?
    `, [result.insertId]);
    
    res.status(201).json({ success: true, data: newCashRecord[0], msg: 'Cash collection record created successfully' });
  } catch (error) {
    console.error('Error creating cash collection record:', error);
    res.status(500).json({ success: false, msg: 'Error creating cash collection record' });
  }
};

// Update delivery boy cash collection
const updateDeliveryBoyCash = async (req, res) => {
  try {
    const { id } = req.params;
    const { delivery_boy_id, order_id, final_total, amount, type, bonus_id, message, collected_at } = req.body;
    
    if (!delivery_boy_id || !amount || !type) {
      return res.status(400).json({ success: false, msg: 'Delivery boy ID, amount and type are required' });
    }
    
    const [result] = await db.query(
      'UPDATE delivery_boy_cash SET delivery_boy_id = ?, order_id = ?, final_total = ?, amount = ?, type = ?, bonus_id = ?, message = ?, collected_at = ? WHERE id = ?',
      [delivery_boy_id, order_id, final_total, amount, type, bonus_id, message, collected_at, id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, msg: 'Cash collection record not found' });
    }
    
    const [updatedCashRecord] = await db.query(`
      SELECT dc.*, db.name as delivery_boy_name, db.phone as delivery_boy_phone, 
             b.name as bonus_name, o.order_number
      FROM delivery_boy_cash dc 
      LEFT JOIN delivery_boys db ON dc.delivery_boy_id = db.id 
      LEFT JOIN bonuses b ON dc.bonus_id = b.id
      LEFT JOIN orders o ON dc.order_id = o.id
      WHERE dc.id = ?
    `, [id]);
    
    res.json({ success: true, data: updatedCashRecord[0], msg: 'Cash collection record updated successfully' });
  } catch (error) {
    console.error('Error updating cash collection record:', error);
    res.status(500).json({ success: false, msg: 'Error updating cash collection record' });
  }
};

// Delete delivery boy cash collection
const deleteDeliveryBoyCash = async (req, res) => {
  try {
    const { id } = req.params;
    
    const [result] = await db.query('DELETE FROM delivery_boy_cash WHERE id = ?', [id]);
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, msg: 'Cash collection record not found' });
    }
    
    res.json({ success: true, msg: 'Cash collection record deleted successfully' });
  } catch (error) {
    console.error('Error deleting cash collection record:', error);
    res.status(500).json({ success: false, msg: 'Error deleting cash collection record' });
  }
};

module.exports = {
  getAllDeliveryBoyCash,
  getDeliveryBoyCashById,
  createDeliveryBoyCash,
  updateDeliveryBoyCash,
  deleteDeliveryBoyCash
};
