const express = require("express");
const router = express.Router();
const db = require("../db"); // Make sure db.js exports your MySQL connection

// ✅ GET all users with their KYC details
router.get("/", (req, res) => {
  const query = `
    SELECT 
      u.id AS user_id,
      u.name AS user_name,
      u.email AS user_email,
      u.phone AS user_phone,
      u.created_at AS user_created_at,
      k.id AS kyc_id,
      k.full_name,
      k.email AS kyc_email,
      k.phone AS kyc_phone,
      k.address,
      k.pan_number,
      k.bank_name,
      k.account_number,
      k.ifsc_code,
      k.upi_id,
      k.profile_photo,
      k.pan_photo,
      k.address_proof,
      k.bank_proof,
      k.status AS kyc_status,
      k.created_at AS kyc_created_at
    FROM users u
    LEFT JOIN kyc_details k ON u.id = k.user_id
    ORDER BY u.name DESC;
  `;

  db.query(query, (err, results) => {
    if (err) {
      console.error("❌ Error fetching user list:", err);
      return res.status(500).json({ error: "Database error", details: err });
    }

    if (results.length === 0) {
      return res.status(404).json({ message: "No users found" });
    }

    res.status(200).json({
      message: "✅ User list fetched successfully",
      count: results.length,
      data: results,
    });
  });
});

module.exports = router;
