import db from '../config/database.js';
import { distributeLevelIncome }          from '../helpers/Levelincomehelper.js';
import { processStarClubOnNewEntry }      from '../helpers/Starclubhelper.js';
import { incrementDownlineForAllUplines } from '../helpers/downlinehelper.js';  // ← NEW
import {
  checkAndGrantRoyaltyQualification,
  distributeRoyaltyIncome,
}                                            from '../helpers/royaltyHelper.js';

export const approveMember = async (req, res) => {
  try {
    const { id } = req.params;
 
    // ── Fetch new member ──────────────────────────────────────────────────────
    const [members] = await db.query(
      `SELECT id, member_id, sponsor_id FROM members WHERE id = ?`,
      [id]
    );
    if (!members.length)
      return res.status(404).json({ success: false, message: 'Member not found' });
 
    const newMember = members[0];
 
    // ── Activate member ───────────────────────────────────────────────────────
    await db.query(
      `UPDATE members SET status = 'Active', updated_at = NOW() WHERE id = ?`,
      [id]
    );
 
    if (newMember.sponsor_id) {
      // ── Increment sponsor's total_direct ──────────────────────────────────
      await db.query(
        `UPDATE members
            SET total_direct = total_direct + 1,
                updated_at   = NOW()
          WHERE member_id = ?`,
        [newMember.sponsor_id]
      );
 
      // ── Increment total_downline for entire upline chain (non-blocking) ───
      incrementDownlineForAllUplines(newMember.sponsor_id).catch((err) => {
        console.error(`❌ [APPROVE] incrementDownlineForAllUplines error:`, err.message);
      });
 
      // ── Check sponsor's royalty qualification (non-blocking) ─────────────
      // Sponsor ka total_direct badh gaya — check karo kya wo qualify karta hai
      checkAndGrantRoyaltyQualification(newMember.sponsor_id).catch((err) => {
        console.error(`❌ [APPROVE] checkAndGrantRoyaltyQualification error:`, err.message);
      });
 
      // ── Star Club: check if sponsor just hit 5 directs ────────────────────
      const [sponsorRows] = await db.query(
        `SELECT id, member_id, total_direct FROM members WHERE member_id = ?`,
        [newMember.sponsor_id]
      );
 
      if (sponsorRows.length) {
        const sponsor = sponsorRows[0];
        if (parseInt(sponsor.total_direct) === 5) {
          processStarClubOnNewEntry(sponsor.id, sponsor.member_id).catch((err) => {
            console.error(`❌ [APPROVE] processStarClubOnNewEntry error:`, err.message);
          });
        }
      }
    }
 
    // ── Distribute 7-level income (non-blocking) ──────────────────────────────
    distributeLevelIncome(newMember.id).catch((err) => {
      console.error(`❌ [APPROVE] distributeLevelIncome error:`, err.message);
    });
 
    // ── Distribute royalty income to all qualified members (non-blocking) ─────
    // Naya member join hua → saare royalty-qualified members ko 1% milega
    distributeRoyaltyIncome(newMember.id).catch((err) => {
      console.error(`❌ [APPROVE] distributeRoyaltyIncome error:`, err.message);
    });
 
    res.json({ success: true, message: 'Member approved successfully' });
 
  } catch (error) {
    console.error('❌ approveMember:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};




export const getAllMembers = async (req, res) => {
  try {
    const {
      search = '',
      status = '',
      stage  = '',
      from   = '',
      to     = '',
      page   = 1,
      limit  = 10,
    } = req.query;

    const offset     = (parseInt(page) - 1) * parseInt(limit);
    const conditions = [];
    const params     = [];

    if (search.trim()) {
      const q = `%${search.trim()}%`;
      conditions.push(`(full_name LIKE ? OR member_id LIKE ? OR email LIKE ? OR mobile LIKE ? OR sponsor_id LIKE ?)`);
      params.push(q, q, q, q, q);
    }
    if (status && ['Active', 'Pending', 'Rejected'].includes(status)) {
      conditions.push('status = ?');
      params.push(status);
    }
    if (stage !== '' && stage !== 'ALL') {
      conditions.push('level_income_stage = ?');
      params.push(parseInt(stage));
    }
    if (from) { conditions.push('DATE(created_at) >= ?'); params.push(from); }
    if (to)   { conditions.push('DATE(created_at) <= ?'); params.push(to);   }

    const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';

    const [[{ total }]] = await db.query(
      `SELECT COUNT(*) AS total FROM members ${where}`, params
    );

const [members] = await db.query(
  `SELECT * 
   FROM members ${where}
   ORDER BY created_at DESC
   LIMIT ? OFFSET ?`,
  [...params, parseInt(limit), offset]
);

    res.json({
      success: true,
      data: members,
      pagination: {
        total:      parseInt(total),
        page:       parseInt(page),
        limit:      parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit)),
      },
    });
  } catch (error) {
    console.error('❌ getAllMembers error:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

// ─────────────────────────────────────────────
//  GET /admin/members/:memberId/detail
// ─────────────────────────────────────────────
export const getMemberDetail = async (req, res) => {
  try {
    const { memberId } = req.params;
    const {
      txPage  = 1, txLimit  = 10,
      ordPage = 1, ordLimit = 10,
    } = req.query;

    const [memberRows] = await db.query(
      `SELECT * 
      FROM members 
      WHERE member_id = ?`,
      [memberId]
    );

    if (!memberRows.length)
      return res.status(404).json({ success: false, message: 'Member not found' });

    const member    = memberRows[0];
    const txOffset  = (parseInt(txPage)  - 1) * parseInt(txLimit);
    const ordOffset = (parseInt(ordPage) - 1) * parseInt(ordLimit);

    const [[{ txTotal }]] = await db.query(
      'SELECT COUNT(*) AS txTotal FROM transactions WHERE user_member_id = ?', [memberId]
    );
    const [transactions] = await db.query(
      `SELECT id, transaction_type, amount, description, order_id, created_at
         FROM transactions WHERE user_member_id = ?
         ORDER BY created_at DESC LIMIT ? OFFSET ?`,
      [memberId, parseInt(txLimit), txOffset]
    );

    const [[{ ordTotal }]] = await db.query(
      'SELECT COUNT(*) AS ordTotal FROM orders WHERE user_id = ?', [member.id]
    );
    const [orders] = await db.query(
      `SELECT id, order_id, total_amount, payment_status, order_status,
              payment_type, transaction_id, payment_screenshot, created_at
         FROM orders WHERE user_id = ?
         ORDER BY created_at DESC LIMIT ? OFFSET ?`,
      [member.id, parseInt(ordLimit), ordOffset]
    );
    for (const order of orders) {
      const [items] = await db.query(
        'SELECT product_name, quantity, price, subtotal FROM order_items WHERE order_id = ?',
        [order.id]
      );
      order.order_items = items;
    }

    res.json({
      success: true,
      member,
      transactions: {
        data: transactions,
        pagination: { total: parseInt(txTotal), page: parseInt(txPage), limit: parseInt(txLimit), totalPages: Math.ceil(txTotal / parseInt(txLimit)) },
      },
      orders: {
        data: orders,
        pagination: { total: parseInt(ordTotal), page: parseInt(ordPage), limit: parseInt(ordLimit), totalPages: Math.ceil(ordTotal / parseInt(ordLimit)) },
      },
    });
  } catch (error) {
    console.error('❌ getMemberDetail error:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

// ─────────────────────────────────────────────
//  GET /admin/members/:id
// ─────────────────────────────────────────────
export const getMemberById = async (req, res) => {
  try {
    const { id } = req.params;
    const [members] = await db.query('SELECT * FROM members WHERE id = ?', [id]);
    if (!members.length)
      return res.status(404).json({ success: false, message: 'Member not found' });
    const member = members[0];
    delete member.password_hash;
    res.json({ success: true, data: member });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

// ─────────────────────────────────────────────
//  PUT /admin/members/:id/approve
// ─────────────────────────────────────────────

export const rejectMember = async (req, res) => {
  try {
    const { id } = req.params;
    const { remark } = req.body;
    await db.query(
      `UPDATE members SET status = 'Rejected', remark = ?, updated_at = NOW() WHERE id = ?`,
      [remark?.trim() || null, id]
    );
    res.json({ success: true, message: 'Member rejected' });
  } catch (error) {
    console.error('❌ rejectMember:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

// ─────────────────────────────────────────────
//  PUT /admin/members/:id/remark
// ─────────────────────────────────────────────
export const addRemark = async (req, res) => {
  try {
    const { id } = req.params;
    const { remark } = req.body;
    if (!remark?.trim())
      return res.status(400).json({ success: false, message: 'Remark cannot be empty' });
    await db.query('UPDATE members SET remark = ?, updated_at = NOW() WHERE id = ?', [remark.trim(), id]);
    res.json({ success: true, message: 'Remark saved' });
  } catch (error) {
    console.error('❌ addRemark:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

// ─────────────────────────────────────────────
//  PUT /admin/members/:id/verify-payment
// ─────────────────────────────────────────────
export const verifyRegistrationPayment = async (req, res) => {
  try {
    const { id } = req.params;
    const { action, note } = req.body;
    if (!['Verified', 'Rejected'].includes(action))
      return res.status(400).json({ success: false, message: 'action must be Verified or Rejected' });
    await db.query(
      `UPDATE members SET reg_payment_status = ?, remark = COALESCE(?, remark), updated_at = NOW() WHERE id = ?`,
      [action, note?.trim() || null, id]
    );
    res.json({ success: true, message: `Payment ${action.toLowerCase()}` });
  } catch (error) {
    console.error('❌ verifyRegistrationPayment:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};


export const addCustomerRemark = async (req, res) => {
  try {
    const { id } = req.params;
    const { remark } = req.body;
    if (!remark?.trim())
      return res.status(400).json({ success: false, message: 'Remark cannot be empty' });
    await db.query('UPDATE customers SET remark = ?, updated_at = NOW() WHERE id = ?', [remark.trim(), id]);
    res.json({ success: true, message: 'Remark saved' });
  } catch (error) {
    console.error('❌ addCustomerRemark:', error.message);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};


export const getDashboardStats = async (req, res) => {
  try {
    const [[activeMembers]]  = await db.query("SELECT COUNT(*) as count FROM members WHERE status = 'Active'");
    const [[pendingMembers]] = await db.query("SELECT COUNT(*) as count FROM members WHERE status = 'Pending'");
    const [[customers]]      = await db.query('SELECT COUNT(*) as count FROM customers');
    const [[products]]       = await db.query('SELECT COUNT(*) as count FROM products WHERE is_active = 1');
    const [[orders]]         = await db.query(
      "SELECT COUNT(*) as total_orders, SUM(CASE WHEN payment_status = 'Approved' THEN total_amount ELSE 0 END) as total_revenue FROM orders"
    );
    const [[pendingOrders]] = await db.query("SELECT COUNT(*) as count FROM orders WHERE payment_status = 'Pending'");

    res.json({
      success: true,
      data: {
        totalMembers:   activeMembers.count  || 0,
        pendingMembers: pendingMembers.count || 0,
        totalCustomers: customers.count      || 0,
        totalProducts:  products.count       || 0,
        totalOrders:    orders.total_orders  || 0,
        pendingOrders:  pendingOrders.count  || 0,
        totalRevenue:   parseFloat(orders.total_revenue || 0),
      },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const getAllTransactions = async (req, res) => {
  try {
    const [transactions] = await db.query(
      'SELECT * FROM transactions ORDER BY created_at DESC LIMIT 100'
    );
    res.json({ success: true, data: transactions });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const getAllWithdrawals = async (req, res) => {
  try {
    const { status } = req.query;
    let query = 'SELECT * FROM withdrawals';
    const params = [];
    if (status) { query += ' WHERE status = ?'; params.push(status); }
    query += ' ORDER BY created_at DESC';
    const [withdrawals] = await db.query(query, params);
    res.json({ success: true, data: withdrawals });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const searchMember = async (req, res) => {
  try {
    const { searchType, searchValue } = req.params;
    const fieldMap = { member_id: 'member_id', mobile: 'mobile' };
    if (!fieldMap[searchType])
      return res.status(400).json({ success: false, message: 'Invalid search type' });

    const [members] = await db.query(
      `SELECT * FROM members WHERE ${fieldMap[searchType]} = ?`, [searchValue]
    );
    if (!members.length)
      return res.status(404).json({ success: false, message: 'Member not found' });

    const member = members[0];
    delete member.password_hash;
    res.json({ success: true, data: member });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const updateMember = async (req, res) => {
  try {
    const { id }  = req.params;
    const updates = { ...req.body };
    ['id','member_id','password_hash','wallet_balance','total_income','sponsor_id'].forEach(f => delete updates[f]);

    const fields = Object.keys(updates);
    if (!fields.length)
      return res.status(400).json({ success: false, message: 'No valid fields to update' });

    const setClause = fields.map(f => `${f} = ?`).join(', ');
    await db.query(
      `UPDATE members SET ${setClause} WHERE id = ?`,
      [...Object.values(updates), id]
    );

    const [members] = await db.query('SELECT * FROM members WHERE id = ?', [id]);
    if (!members.length)
      return res.status(404).json({ success: false, message: 'Member not found' });
    const member = members[0];
    delete member.password_hash;
    res.json({ success: true, message: 'Member updated successfully', data: member });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};