const express = require("express");
const router = express.Router();
const db = require("../db");

// GET /api/withdraws?start=YYYY-MM-DD&end=YYYY-MM-DD
router.get("/", async (req, res) => {
  try {
    const { start, end } = req.query;

    // Base SQL query: join withdraw_request with kyc_details
    let sql = `
      SELECT 
        w.id AS withdraw_id,
        w.user_id,
        w.amount,
        w.status AS withdraw_status,
        w.created_at AS withdraw_date,
        k.full_name,
        k.email,
        k.phone,
        k.bank_name,
        k.account_number,
        k.ifsc_code,
        k.upi_id,
        k.bank_proof,
        k.status AS kyc_status
      FROM transactions w
      INNER JOIN kyc_details k ON k.user_id = w.user_id
      WHERE w.type='debit'
    `;

    const params = [];

    // Optional date filter
    if (start && end) {
      sql += " AND DATE(w.created_at) BETWEEN ? AND ?";
      params.push(start, end);
    }

    sql += " ORDER BY w.created_at DESC";

    const [rows] = await db.promise().query(sql, params);

    // Optional: convert bank_proof to a full URL
    const formattedRows = rows.map((row) => ({
      ...row,
      bank_proof: row.bank_proof
       
    }));

    res.json({
      success: true,
      count: formattedRows.length,
      data: formattedRows,
    });
  } catch (error) {
    console.error("❌ Withdraw fetch error:", error);
    res.status(500).json({
      success: false,
      message: "Server error",
      error: error.message,
    });
  }
});

module.exports = router;
