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

import { previewPPPIncome, distributePPPIncome } from '../../helpers/pppHelper.js';
// ─────────────────────────────────────────────────────────────────────────────
export const getPPPIncomePreview = async (req, res) => {
  try {
    const { plan, amount } = req.query;
    if (!plan || !amount)
      return res.status(400).json({ success: false, message: 'plan and amount are required' });
 
    const preview = await previewPPPIncome(parseFloat(plan), parseFloat(amount));
    res.json({ success: true, data: preview });
  } catch (error) {
    console.error('❌ getPPPIncomePreview:', error.message);
    res.status(400).json({ success: false, message: error.message });
  }
};
 
// ─────────────────────────────────────────────
//  POST /admin/ppp-income/distribute
//  Body: { plan, amount, note }
// ─────────────────────────────────────────────
export const distributePPPIncomeController = async (req, res) => {
  try {
    const { plan, amount, note = '' } = req.body;
    if (!plan || !amount)
      return res.status(400).json({ success: false, message: 'plan and amount are required' });
 
    const result = await distributePPPIncome(
      parseFloat(plan),
      parseFloat(amount),
      note.trim()
    );
 
    if (!result.success)
      return res.status(400).json({ success: false, message: result.message, data: result });
 
    res.json({ success: true, message: result.message, data: result });
  } catch (error) {
    console.error('❌ distributePPPIncomeController:', error.message);
    res.status(500).json({ success: false, message: error.message });
  }
};
 
// ─────────────────────────────────────────────
//  GET /admin/ppp-income/history
//  Query: page, limit, plan, from, to, search
//  Returns: paginated rows + aggregate stats
// ─────────────────────────────────────────────
export const getPPPIncomeHistory = async (req, res) => {
  try {
    const {
      page   = 1,
      limit  = 50,
      plan   = '',
      from   = '',
      to     = '',
      search = '',
    } = req.query;
 
    const offset = (parseInt(page) - 1) * parseInt(limit);
 
    // Build WHERE
    const conditions = [`t.transaction_type = 'PPP_INCOME'`];
    const params     = [];
 
    if (plan) {
      conditions.push('m.plan = ?');
      params.push(parseFloat(plan));
    }
    if (from) {
      conditions.push('DATE(t.created_at) >= ?');
      params.push(from);
    }
    if (to) {
      conditions.push('DATE(t.created_at) <= ?');
      params.push(to);
    }
    if (search.trim()) {
      const q = `%${search.trim()}%`;
      conditions.push('(t.user_member_id LIKE ? OR m.full_name LIKE ?)');
      params.push(q, q);
    }
 
    const where = conditions.join(' AND ');
 
    // Total count (filtered)
    const [[{ total }]] = await db.query(
      `SELECT COUNT(*) AS total
         FROM transactions t
         LEFT JOIN members m ON m.id = t.user_id
        WHERE ${where}`,
      params
    );
 
    // Paginated rows
    const [rows] = await db.query(
      `SELECT t.id, t.user_member_id, m.full_name, m.plan,
              t.amount, t.description, t.created_at
         FROM transactions t
         LEFT JOIN members m ON m.id = t.user_id
        WHERE ${where}
        ORDER BY t.created_at DESC
        LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), offset]
    );
 
    // Overall aggregate stats (unfiltered)
    const [[stats]] = await db.query(
      `SELECT
         COALESCE(SUM(t.amount), 0)       AS totalDistributed,
         COUNT(*)                          AS totalTransactions,
         COUNT(DISTINCT t.user_member_id) AS uniqueMembers,
         MAX(t.created_at)                AS lastDate,
         (SELECT amount FROM transactions
           WHERE transaction_type = 'PPP_INCOME'
           ORDER BY created_at DESC LIMIT 1) AS lastAmount
       FROM transactions t
       WHERE t.transaction_type = 'PPP_INCOME'`
    );
 
    // Count distinct batches (grouped by minute)
    const [[{ totalBatches }]] = await db.query(
      `SELECT COUNT(DISTINCT DATE_FORMAT(created_at, '%Y-%m-%d %H:%i')) AS totalBatches
         FROM transactions
        WHERE transaction_type = 'PPP_INCOME'`
    );
 
    res.json({
      success: true,
      data:    rows,
      stats: {
        totalDistributed: parseFloat(stats.totalDistributed),
        totalBatches:     parseInt(totalBatches),
        uniqueMembers:    parseInt(stats.uniqueMembers),
        lastDate: stats.lastDate
          ? new Date(stats.lastDate).toLocaleDateString('en-IN', {
              day: '2-digit', month: 'short', year: 'numeric',
            })
          : null,
        lastAmount: stats.lastAmount ? parseFloat(stats.lastAmount) : null,
      },
      pagination: {
        total:      parseInt(total),
        page:       parseInt(page),
        limit:      parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit)),
      },
    });
  } catch (error) {
    console.error('❌ getPPPIncomeHistory:', error.message);
    res.status(500).json({ success: false, message: error.message });
  }
};