const BaseModel = require('./BaseModel');

class DeliveryBoyCash extends BaseModel {
  constructor() {
    super('delivery_boy_cash');
  }

  async create(cashData) {
    const {
      delivery_boy_id,
      order_id = null,
      final_total = null,
      amount,
      type = 'collection',
      bonus_id = null,
      message = null
    } = cashData;
    
    const query = `
      INSERT INTO delivery_boy_cash 
      (delivery_boy_id, order_id, final_total, amount, type, bonus_id, message)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `;
    
    const [result] = await this.db.query(query, [
      delivery_boy_id, order_id, final_total, amount, type, bonus_id, message
    ]);
    
    return result.insertId;
  }

  async getByDeliveryBoy(deliveryBoyId, filters = {}) {
    let query = `
      SELECT dbc.*, 
             o.order_number,
             b.name as bonus_name
      FROM delivery_boy_cash dbc
      LEFT JOIN orders o ON dbc.order_id = o.id
      LEFT JOIN bonuses b ON dbc.bonus_id = b.id
      WHERE dbc.delivery_boy_id = ?
    `;
    
    const params = [deliveryBoyId];
    
    if (filters.type) {
      query += ' AND dbc.type = ?';
      params.push(filters.type);
    }
    
    if (filters.startDate) {
      query += ' AND DATE(dbc.collected_at) >= ?';
      params.push(filters.startDate);
    }
    
    if (filters.endDate) {
      query += ' AND DATE(dbc.collected_at) <= ?';
      params.push(filters.endDate);
    }
    
    query += ' ORDER BY dbc.collected_at DESC';
    
    if (filters.limit) {
      query += ' LIMIT ?';
      params.push(parseInt(filters.limit));
    }
    
    const [rows] = await this.db.query(query, params);
    return rows;
  }

  async getSummary(deliveryBoyId, startDate = null, endDate = null) {
    let query = `
      SELECT 
        SUM(CASE WHEN type = 'collection' THEN amount ELSE 0 END) as total_collections,
        SUM(CASE WHEN type = 'adjustment' THEN amount ELSE 0 END) as total_adjustments,
        COUNT(DISTINCT order_id) as total_orders
      FROM delivery_boy_cash
      WHERE delivery_boy_id = ?
    `;
    
    const params = [deliveryBoyId];
    
    if (startDate) {
      query += ' AND DATE(collected_at) >= ?';
      params.push(startDate);
    }
    
    if (endDate) {
      query += ' AND DATE(collected_at) <= ?';
      params.push(endDate);
    }
    
    const [rows] = await this.db.query(query, params);
    return rows[0] || {
      total_collections: 0,
      total_adjustments: 0,
      total_orders: 0
    };
  }
}

module.exports = new DeliveryBoyCash();
