const { authenticate, initiateTransaction, checkStatus } = require("../services/dollarbazar.service");
const { getProtonPayConfig, initiateProtonPayTransaction } = require("../services/protonpay.service");
const add_funds_module = require("../model/add_funds_module");
const user_module = require("../model/user_module");
const wallet_trans_history_module = require("../model/wallet_trans_history_module");
const DollarBazarSettings = require("../model/DollarBazarSettings");

function makeOrderId(prefix = "ORD") {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000);
  return `${prefix}${timestamp}${random}`;
}

async function getAvailableGatewaysForAmount(amount) {
  const availableGateways = [];

  // Check Dollar Bazar
  const dollarBazarConfig = await DollarBazarSettings.findOne({ gatewayId: 'dollar_bazar' });
  if (dollarBazarConfig && dollarBazarConfig.status === true) {
    if (amount >= dollarBazarConfig.minAmount && amount <= dollarBazarConfig.maxAmount) {
      const processingFee = dollarBazarConfig.processingFee || 0;
      const finalAmount = amount + (amount * processingFee / 100);

      availableGateways.push({
        gatewayId: 'dollar_bazar',
        name: 'Dollar Bazar',
        displayName: 'Dollar Bazar',
        minAmount: dollarBazarConfig.minAmount,
        maxAmount: dollarBazarConfig.maxAmount,
        processingFee: processingFee,
        finalAmount: finalAmount,
        description: 'Fast and reliable payments'
      });
    }
  }

  // Check Proton Pay
  const protonPayConfig = await getProtonPayConfig();
  if (protonPayConfig && protonPayConfig.status === true) {
    if (amount >= protonPayConfig.minPayin && amount <= protonPayConfig.maxPayin) {
      // Proton Pay doesn't charge processing fee on merchant side
      availableGateways.push({
        gatewayId: 'proton_pay',
        name: 'Proton Pay',
        displayName: 'Proton Pay',
        minAmount: protonPayConfig.minPayin,
        maxAmount: protonPayConfig.maxPayin,
        processingFee: 0,
        finalAmount: amount,
        description: 'Secure payment gateway'
      });
    }
  }

  return availableGateways;
}

async function selectGateway(amount, preferredGateway = null) {
  const availableGateways = await getAvailableGatewaysForAmount(amount);

  if (availableGateways.length === 0) {
    return {
      success: false,
      msg: `No payment gateway available for amount ₹${amount}`
    };
  }

  // If user specified a gateway, try to use it
  if (preferredGateway) {
    const preferred = availableGateways.find(g => g.gatewayId === preferredGateway);
    if (preferred) {
      return {
        success: true,
        gateway: preferred
      };
    } else {
      return {
        success: false,
        msg: `Selected gateway "${preferredGateway}" is not available for amount ₹${amount}`,
        availableGateways: availableGateways
      };
    }
  }

  // Auto-select logic (you can customize this)
  // Option 1: Select first available
  // Option 2: Select based on lower processing fee
  // Option 3: Round-robin or load balancing

  // For now, select the first available gateway
  return {
    success: true,
    gateway: availableGateways[0]
  };
}

// async function addMoneyViaGateway(req, res) {
//     try {
//         console.log("🚀 Initiating payment gateway transaction...");
//         const { 
//             amount, 
//             customerEmail, 
//             customerMobile, 
//             transactionRemark, 
//             payerVpa, 
//             user_id,
//             gateway, // Optional: 'dollar_bazar' or 'proton_pay'
//             userName,
//             phoneNumber,
//             email
//         } = req.body;

//         const userId = user_id || req.user;

//         if (!amount || Number(amount) <= 0) {
//             return res.status(400).json({ success: false, msg: "Invalid amount" });
//         }

//         const user = await user_module.findById(userId);
//         if (!user) return res.status(404).json({ success: false, msg: "User not found" });

//         // Select appropriate gateway
//         const gatewaySelection = await selectGateway(Number(amount), gateway);
//         if (!gatewaySelection.success) {
//             return res.status(400).json({
//                 success: false,
//                 msg: gatewaySelection.msg,
//                 availableGateways: gatewaySelection.availableGateways
//             });
//         }

//         const selectedGateway = gatewaySelection.gateway;
//         const orderId = makeOrderId(selectedGateway.gatewayId === 'dollar_bazar' ? 'DBZ' : 'PPY');

//         let paymentResult;
//         let gatewayType;

//         // Handle based on selected gateway
//         if (selectedGateway.gatewayId === 'dollar_bazar') {
//             // Dollar Bazar flow
//             gatewayType = 'DOLLARBAZAR';

//             // Step 1: authenticate
//             const authResp = await authenticate(amount, orderId);
//             if (!authResp || !authResp.api_token || !authResp.id_token) {
//                 console.error("❌ Dollar Bazar Auth failed:", authResp);
//                 return res.status(500).json({ 
//                     success: false, 
//                     msg: "Dollar Bazar authentication failed",
//                     gateway: 'dollar_bazar'
//                 });
//             }

//             const { api_token, id_token } = authResp;

//             // Step 2: initiate transaction
//             const txPayload = {
//                 amount: String(amount),
//                 orderId,
//                 customerEmail: customerEmail || user.email || "user@example.com",
//                 customerMobile: customerMobile || user.mobile || "9999999999",
//                 transactionRemark: transactionRemark || "Wallet Deposit",
//                 payerVpa: payerVpa || ""
//             };

//             const initResp = await initiateTransaction(api_token, id_token, txPayload);

//             if (!initResp.success) {
//                 return res.status(400).json({
//                     success: false,
//                     msg: initResp.msg || "Dollar Bazar payment initiation failed",
//                     gatewayResponse: initResp,
//                     gateway: 'dollar_bazar'
//                 });
//             }

//             paymentResult = {
//                 success: true,
//                 data: {
//                     transactionId: initResp.data?.transactionId || "",
//                     intentUrl: initResp.data?.intentUrl,
//                     orderId: orderId,
//                     amount: amount,
//                     gateway: 'DOLLARBAZAR'
//                 },
//                 rawResponse: initResp
//             };

//         } else if (selectedGateway.gatewayId === 'proton_pay') {
//             // Proton Pay flow
//             gatewayType = 'PROTONPAY';

//             const payload = {
//                 amount: Number(amount),
//                 orderId: orderId,
//                 userId: userId,
//                 userName: userName || user.username || `User${userId}`,
//                 customerName: userName || user.username,
//                 customerEmail: customerEmail || user.email || "",
//                 customerMobile: customerMobile || user.mobile || "",
//                 transactionRemark: transactionRemark || "Wallet Deposit",
//                 phoneNumber: phoneNumber || user.mobile || "",
//                 email: email || user.email || ""
//             };

//             const initResp = await initiateProtonPayTransaction(payload);

//             if (!initResp.success) {
//                 return res.status(400).json({
//                     success: false,
//                     msg: initResp.msg || "Proton Pay payment initiation failed",
//                     gatewayResponse: initResp,
//                     gateway: 'proton_pay'
//                 });
//             }

//             paymentResult = initResp;
//         } else {
//             return res.status(400).json({
//                 success: false,
//                 msg: "Unsupported payment gateway"
//             });
//         }

//         // Save pending transaction
//         const transactionData = {
//             userDB_id: user._id,
//             amount: Number(amount),
//             tx_request_number: orderId,
//             txn_ref: paymentResult.data?.transactionId || "",
//             payment_method: gatewayType,
//             fund_status: 0, // pending
//             deposit_type: 1, // auto PG
//             gateway_raw_response: paymentResult.rawResponse || paymentResult.data,
//             gateway: selectedGateway.gatewayId,
//             processing_fee: selectedGateway.processingFee || 0,
//             final_amount: selectedGateway.finalAmount || Number(amount)
//         };

//         // Add UTR for Proton Pay if available
//         if (selectedGateway.gatewayId === 'proton_pay' && paymentResult.data?.paymentId) {
//             transactionData.utr_no = paymentResult.data.paymentId;
//         }

//         await add_funds_module.create(transactionData);

//         return res.json({
//             success: true,
//             msg: "Payment initiated successfully",
//             gateway: selectedGateway.gatewayId,
//             gatewayName: selectedGateway.name,
//             orderId: orderId,
//             intentUrl: paymentResult.data?.intentUrl,
//             amount: Number(amount),
//             processingFee: selectedGateway.processingFee || 0,
//             finalAmount: selectedGateway.finalAmount || Number(amount),
//             data: {
//                 gateway: selectedGateway.gatewayId,
//                 orderId: orderId,
//                 intentUrl: paymentResult.data?.intentUrl,
//                 transactionId: paymentResult.data?.transactionId
//             }
//         });

//     } catch (err) {
//         console.error("❌ addMoneyViaGateway error:", err?.response?.data || err);
//         return res.status(500).json({
//             success: false,
//             msg: "Server error during payment initiation",
//             error: err.message
//         });
//     }
// }

// New API to get available gateways for frontend





async function addMoneyViaGateway(req, res) {
  try {
    console.log("🚀 Initiating payment gateway transaction...");
    console.log("Request Body:", req.body);

    const {
      amount,
      customerEmail,
      customerMobile,
      transactionRemark,
      payerVpa,
      user_id,
      gateway
    } = req.body;

    const userId = user_id || req?.user?._id;
    // console.log("User ID:", userId);

    if (!userId) {
      return res.status(400).json({ success: false, msg: "User ID is required" });
    }

    if (!amount || Number(amount) <= 0) {
      return res.status(400).json({ success: false, msg: "Invalid amount" });
    }

    const user = await user_module.findById(userId);
    if (!user) {
      console.log("User not found for ID:", userId);
      return res.status(404).json({ success: false, msg: "User not found" });
    }

    console.log("User found:", user._id);
    console.log("User name found:", user.user_name);

    // Select appropriate gateway
    const gatewaySelection = await selectGateway(Number(amount), gateway);
    if (!gatewaySelection.success) {
      return res.status(400).json({
        success: false,
        msg: gatewaySelection.msg,
        availableGateways: gatewaySelection.availableGateways
      });
    }

    const selectedGateway = gatewaySelection.gateway;
    console.log("Selected Gateway:", selectedGateway.gatewayId);

    const orderId = makeOrderId(selectedGateway.gatewayId === 'dollar_bazar' ? 'DBZ' : 'PPY');
    console.log("Generated Order ID:", orderId);

    let paymentResult;
    let gatewayType;

    // Handle based on selected gateway
    if (selectedGateway.gatewayId === 'dollar_bazar') {
      // Dollar Bazar flow (keep existing)
      gatewayType = 'DOLLARBAZAR';

      const authResp = await authenticate(amount, orderId);
      if (!authResp || !authResp.api_token || !authResp.id_token) {
        console.error("❌ Dollar Bazar Auth failed:", authResp);
        return res.status(500).json({
          success: false,
          msg: "Dollar Bazar authentication failed",
          gateway: 'dollar_bazar'
        });
      }

      const { api_token, id_token } = authResp;

      const txPayload = {
        amount: String(amount),
        orderId,
        customerEmail: customerEmail || user.email || "user@example.com",
        customerMobile: customerMobile || user.mobile || "9999999999",
        transactionRemark: transactionRemark || "Wallet Deposit",
        payerVpa: payerVpa || ""
      };

      console.log("Initiating Dollar Bazar transaction...");
      const initResp = await initiateTransaction(api_token, id_token, txPayload);

      if (!initResp.success) {
        return res.status(400).json({
          success: false,
          msg: initResp.msg || "Dollar Bazar payment initiation failed",
          gatewayResponse: initResp,
          gateway: 'dollar_bazar'
        });
      }

      paymentResult = {
        success: true,
        data: {
          transactionId: initResp.data?.transactionId || "",
          intentUrl: initResp.data?.intentUrl,
          orderId: orderId,
          amount: amount,
          gateway: 'DOLLARBAZAR'
        },
        rawResponse: initResp
      };

    } else if (selectedGateway.gatewayId === 'proton_pay') {
      // Proton Pay flow - Updated with proper data mapping
      gatewayType = 'PROTONPAY';

      // Generate random email/name if not provided (similar to PHP)
      const { generateRandomEmail, generateRandomName } = require("../services/protonpay.service");

      const payload = {
        amount: Number(amount),
        orderId: orderId,
        userId: userId,
        userName: user?.user_name || generateRandomName(),
        customerName: user?.user_name || generateRandomName(),
        customerEmail: customerEmail || user.email || generateRandomEmail(),
        customerMobile: customerMobile || user.mobile || "9999999999",
        transactionRemark: transactionRemark || "Wallet Deposit",
        phoneNumber: customerMobile || user.mobile || "",
        email: customerEmail || user.email || generateRandomEmail()
      };

      console.log("Initiating Proton Pay transaction with payload:", payload);
      const initResp = await initiateProtonPayTransaction(payload);

      if (!initResp.success) {
        console.error("Proton Pay initiation failed:", initResp);
        return res.status(400).json({
          success: false,
          msg: initResp.msg || "Proton Pay payment initiation failed",
          gatewayResponse: initResp,
          gateway: 'proton_pay',
          code: initResp.code
        });
      }

      paymentResult = initResp;
      console.log("Proton Pay initiation successful:", {
        transactionId: initResp.data?.transactionId,
        intentUrl: initResp.data?.intentUrl ? "Yes" : "No",
        upiLink: initResp.data?.upiLink ? "Yes" : "No"
      });
    } else {
      return res.status(400).json({
        success: false,
        msg: "Unsupported payment gateway"
      });
    }

    console.log("Payment result:", paymentResult.success ? "Success" : "Failed");

    // Save pending transaction
    const transactionData = {
      userDB_id: user._id,
      amount: Number(amount),
      tx_request_number: orderId,
      txn_ref: paymentResult.data?.transactionId || paymentResult.data?.payinId || "",
      payment_method: gatewayType,
      fund_status: 0, // pending
      deposit_type: 1, // auto PG
      gateway_raw_response: paymentResult.rawResponse || paymentResult.data,
      gateway: selectedGateway.gatewayId,
      processing_fee: selectedGateway.processingFee || 0,
      final_amount: selectedGateway.finalAmount || Number(amount),
      merchant_order_id: orderId,
      payin_id: paymentResult.data?.payinId || null
    };

    console.log("Saving transaction to database...");
    const savedTransaction = await add_funds_module.create(transactionData);
    console.log("Transaction saved with ID:", savedTransaction._id);

    // Prepare response - similar to PHP response format
    const responseData = {
      success: true,
      msg: "Payment initiated successfully",
      gateway: selectedGateway.gatewayId,
      gatewayName: selectedGateway.name,
      orderId: orderId,
      paymentId: orderId, // For compatibility with mobile app
      merchantOrderId: orderId, // For Proton Pay
      intentUrl: paymentResult.data?.intentUrl,
      payment_url: paymentResult.data?.intentUrl, // For compatibility
      intent: true, // For compatibility with mobile app
      amount: Number(amount),
      processingFee: selectedGateway.processingFee || 0,
      finalAmount: selectedGateway.finalAmount || Number(amount),
      data: {
        gateway: selectedGateway.gatewayId,
        orderId: orderId,
        merchantOrderId: orderId,
        intentUrl: paymentResult.data?.intentUrl,
        transactionId: paymentResult.data?.transactionId,
        payinId: paymentResult.data?.payinId,
        payinUrl: paymentResult.data?.payinUrl,
        upiLink: paymentResult.data?.upiLink
      }
    };

    console.log("Sending response:", {
      success: true,
      gateway: selectedGateway.gatewayId,
      orderId: orderId,
      hasIntentUrl: !!paymentResult.data?.intentUrl
    });

    return res.json(responseData);

  } catch (err) {
    console.error("❌ addMoneyViaGateway error:", err);
    console.error("Error stack:", err.stack);
    return res.status(500).json({
      success: false,
      msg: "Server error during payment initiation",
      error: err.message
    });
  }
}











async function getAvailablePaymentGateways(req, res) {
  try {
    const { amount } = req.body;

    if (!amount || Number(amount) <= 0) {
      return res.status(400).json({
        success: false,
        msg: "Valid amount is required"
      });
    }

    const availableGateways = await getAvailableGatewaysForAmount(Number(amount));

    return res.json({
      success: true,
      data: availableGateways,
      count: availableGateways.length
    });
  } catch (error) {
    console.error("❌ getAvailablePaymentGateways error:", error);
    return res.status(500).json({
      success: false,
      msg: "Error fetching available gateways",
      error: error.message
    });
  }
}

// Update refreshPGTransactionStatus to handle both gateways
const refreshPGTransactionStatus = async (req, res) => {
  try {
    const { transactionId } = req.body;

    if (!transactionId) {
      return res.status(400).json({ success: false, msg: "Transaction ID is required" });
    }

    const transaction = await add_funds_module.findById(transactionId);
    if (!transaction) {
      return res.status(404).json({ success: false, msg: "Transaction not found" });
    }

    // Only allow refresh for auto PG transactions
    if (transaction.deposit_type !== 1) {
      return res.status(400).json({
        success: false,
        msg: "Only auto PG transactions can be refreshed"
      });
    }

    const orderId = transaction.tx_request_number;
    if (!orderId) {
      return res.status(400).json({
        success: false,
        msg: "Transaction reference not found"
      });
    }

    let statusResp;

    // Check status based on gateway
    if (transaction.payment_method === 'DOLLARBAZAR' || transaction.gateway === 'dollar_bazar') {
      // Dollar Bazar status check
      const authResp = await authenticate(transaction.amount, orderId);
      if (!authResp || !authResp.api_token || !authResp.id_token) {
        return res.status(500).json({
          success: false,
          msg: "Dollar Bazar authentication failed"
        });
      }
      statusResp = await checkStatus(authResp.api_token, authResp.id_token, orderId);

    } else if (transaction.payment_method === 'PROTONPAY' || transaction.gateway === 'proton_pay') {
      // Proton Pay status check
      const { checkProtonPayStatus } = require("../services/protonpay.service");
      statusResp = await checkProtonPayStatus(orderId, transaction.txn_ref);
    } else {
      return res.status(400).json({
        success: false,
        msg: "Unsupported payment gateway"
      });
    }

    console.log("🔍 Status check response:", statusResp);

    if (statusResp && statusResp.success) {
      let newFundStatus = transaction.fund_status;
      let updateData = {
        gateway_response: statusResp.data || statusResp,
        updated_at: new Date()
      };

      // Process status based on gateway
      if (transaction.payment_method === 'DOLLARBAZAR') {
        const dbData = statusResp.data;
        if (dbData.orderStatus === "PAID" && dbData.bankReference) {
          newFundStatus = 1;
          updateData.fund_status = 1;
          updateData.utr_no = dbData.bankReference;
        } else if (dbData.status === "FAIL" || dbData.orderStatus === "FAIL") {
          newFundStatus = 2;
          updateData.fund_status = 2;
        }
      } else if (transaction.payment_method === 'PROTONPAY') {
        const ppData = statusResp.data;
        if (ppData.status === 'success' || ppData.status === 'SUCCESS') {
          newFundStatus = 1;
          updateData.fund_status = 1;
          updateData.txn_ref = ppData.payinId;
          updateData.utr_no = ppData.paymentId;
        } else if (ppData.status === 'failed' || ppData.status === 'FAILED') {
          newFundStatus = 2;
          updateData.fund_status = 2;
        }
      }

      // If status changed to approved, credit user wallet
      if (newFundStatus === 1 && transaction.fund_status !== 1) {
        await creditUserWallet(transaction.userDB_id, transaction.amount, transaction._id);
      }

      await add_funds_module.findByIdAndUpdate(transactionId, updateData);

      return res.json({
        success: true,
        msg: "Transaction status updated successfully",
        data: {
          newStatus: newFundStatus,
          gateway: transaction.payment_method,
          orderId: orderId
        }
      });
    } else {
      return res.json({
        success: false,
        msg: statusResp?.msg || "Unable to fetch status from payment gateway",
        gatewayResponse: statusResp
      });
    }

  } catch (error) {
    console.error("❌ Error refreshing PG transaction:", error);
    return res.status(500).json({
      success: false,
      msg: "Error refreshing transaction status",
      error: error.message
    });
  }
};

// Helper function to credit user wallet
async function creditUserWallet(userId, amount, transactionId) {
  try {
    const user = await user_module.findById(userId);
    if (!user) return;

    user.wallet_balance += amount;
    await user.save();

    await wallet_trans_history_module.create({
      userDB_id: userId,
      amount: amount,
      transaction_type: 1,
      transaction_note: `Deposit via PG Transaction ${transactionId}`,
      amount_status: 19,
      tx_request_number: `WTH${Date.now()}`,
      txn_ref: transactionId.toString()
    });

    console.log(`Wallet credited for user ${userId}: ₹${amount}`);
  } catch (error) {
    console.error("Error crediting user wallet:", error);
  }
}

module.exports = {
  addMoneyViaGateway,
  getAvailablePaymentGateways,
  refreshPGTransactionStatus
};

























// // controllers/payment.controller.js
// const { authenticate, initiateTransaction, checkStatus } = require("../services/dollarbazar.service");
// const add_funds_module = require("../model/add_funds_module");
// const user_module = require("../model/user_module");
// const wallet_trans_history_module = require("../model/wallet_trans_history_module");



// const paymentGatewayManager = require("../services/paymentGatewayManager");


// // function makeOrderId(prefix = "PG") {
// //   const timestamp = Date.now();
// //   const random = Math.floor(Math.random() * 1000);
// //   return `${prefix}${timestamp}${random}`;
// // }




// function makeOrderId(prefix = "ORD") {
//   return `${prefix}${Date.now()}`;
// }

// async function addMoneyViaGateway(req, res) {
//   try {
//     console.log("🚀 Initiating DollarBazar payment...");
//     const { amount, customerEmail, customerMobile, transactionRemark, payerVpa, user_id } = req.body;
//     const userId = user_id || req.user;

//     if (!amount || Number(amount) <= 0) {
//       return res.status(400).json({ success: false, msg: "Invalid amount" });
//     }

//     const user = await user_module.findById(userId);
//     if (!user) return res.status(404).json({ success: false, msg: "User not found" });

//     const orderId = makeOrderId("DBZ");

//     // Step 1: authenticate
//     const authResp = await authenticate(amount, orderId);
//     if (!authResp || !authResp.api_token || !authResp.id_token) {
//       console.error("❌ Auth failed:", authResp);
//       return res.status(500).json({ success: false, msg: "Authentication failed with gateway" });
//     }

//     const { api_token, id_token } = authResp;

//     // Step 2: initiate transaction
//     const txPayload = {
//       amount: String(amount),
//       orderId,
//       customerEmail: customerEmail || user.email || "user@example.com",
//       customerMobile: customerMobile || user.mobile || "9999999999",
//       transactionRemark: transactionRemark || "Wallet Deposit",
//       payerVpa: payerVpa || ""
//     };

//     const initResp = await initiateTransaction(api_token, id_token, txPayload);

//     if (!initResp.success) {
//       return res.status(400).json({
//         success: false,
//         msg: initResp.msg || "Payment initiation failed",
//         gatewayResponse: initResp
//       });
//     }

//     // Save pending transaction
//     await add_funds_module.create({
//       userDB_id: user._id,
//       amount: Number(amount),
//       tx_request_number: orderId,
//       txn_ref: initResp.data?.transactionId || "",
//       payment_method: "DOLLARBAZAR",
//       fund_status: 0, // pending
//       deposit_type: 1, // auto PG
//       gateway_raw_response: initResp
//     });

//     return res.json({
//       success: true,
//       msg: "Payment initiated successfully",
//       orderId,
//       intentUrl: initResp.data?.intentUrl,
//       gatewayResponse: initResp
//     });

//   } catch (err) {
//     console.error("❌ addMoneyViaGateway error:", err?.response?.data || err);
//     return res.status(500).json({
//       success: false,
//       msg: "Server error during payment initiation",
//       error: err.message
//     });
//   }
// }


// const refreshPGTransactionStatus = async (req, res) => {
//   try {
//     const { transactionId } = req.body;
//     // console.log("🚀 ~ refreshPGTransactionStatus ~ req.body:", req.body)

//     if (!transactionId) {
//       return res.status(400).json({ success: false, msg: "Transaction ID is required" });
//     }

//     // Find the transaction
//     const transaction = await add_funds_module.findById(transactionId);
//     console.log("🚀 ~ refreshPGTransactionStatus ~ transaction:", transaction)
//     if (!transaction) {
//       return res.status(404).json({ success: false, msg: "Transaction not found" });
//     }

//     // Only allow refresh for DollarBazar PG transactions
//     if (transaction.deposit_type !== 1 || transaction.payment_method !== "DOLLARBAZAR") {
//       return res.status(400).json({
//         success: false,
//         msg: "Only auto DollarBazar PG transactions can be refreshed"
//       });
//     }

//     // Get orderId from transaction
//     const orderId = transaction.tx_request_number;
//     if (!orderId) {
//       return res.status(400).json({
//         success: false,
//         msg: "Transaction reference not found"
//       });
//     }

//     // Step 1: Authenticate with DollarBazar
//     const authResp = await authenticate(transaction.amount, orderId);
//     if (!authResp || !authResp.api_token || !authResp.id_token) {
//       return res.status(500).json({
//         success: false,
//         msg: "Authentication failed with payment gateway"
//       });
//     }

//     // Step 2: Check status with DollarBazar
//     const statusResp = await checkStatus(authResp.api_token, authResp.id_token, orderId);

//     console.log("🔍 Status check response:", statusResp);

//     if (statusResp && statusResp.success) {
//       let newFundStatus = transaction.fund_status;
//       let updateData = {
//         gateway_response: statusResp,
//         updated_at: new Date()
//       };

//       // Map DollarBazar status to your fund_status
//       if (statusResp.data) {
//         const dbData = statusResp.data;

//         // Check if transaction is successful based on documentation
//         if (dbData.orderStatus === "PAID" && dbData.bankReference) {
//           newFundStatus = 1; // Approved
//           updateData.fund_status = 1;
//           updateData.utr_no = dbData.bankReference; // Store UTR

//           // If status changed to approved, credit user wallet
//           if (transaction.fund_status !== 1) {
//             await creditUserWallet(transaction.userDB_id, transaction.amount, transaction._id);
//           }
//         }
//         else if (dbData.status === "FAIL" || dbData.orderStatus === "FAIL") {
//           newFundStatus = 2; // Failed
//           updateData.fund_status = 2;
//         }
//         // If INPROCESS/PENDING/ACTIVE, keep as pending (0)
//       }

//       // Update transaction in database
//       await add_funds_module.findByIdAndUpdate(transactionId, updateData);

//       return res.json({
//         success: true,
//         msg: "Transaction status updated successfully",
//         data: {
//           newStatus: newFundStatus,
//           orderStatus: statusResp.data?.orderStatus,
//           bankReference: statusResp.data?.bankReference,
//           gatewayStatus: statusResp.data?.status
//         }
//       });
//     } else {
//       return res.json({
//         success: false,
//         msg: statusResp?.msg || "Unable to fetch status from payment gateway",
//         gatewayResponse: statusResp
//       });
//     }

//   } catch (error) {
//     console.error("❌ Error refreshing PG transaction:", error);
//     return res.status(500).json({
//       success: false,
//       msg: "Error refreshing transaction status",
//       error: error.message
//     });
//   }
// };


// // Helper function to credit user wallet
// async function creditUserWallet(userId, amount, transactionId) {
//   try {
//     const user = await user_module.findById(userId);
//     if (!user) return;

//     // Update user wallet balance
//     user.wallet_balance += amount;
//     await user.save();

//     // Create wallet transaction history
//     await wallet_trans_history_module.create({
//       userDB_id: userId,
//       amount: amount,
//       transaction_type: 1, // Deposit
//       transaction_note: `Deposit via PG Transaction ${transactionId}`,
//       amount_status: 19, // Success
//       tx_request_number: `WTH${Date.now()}`,
//       txn_ref: transactionId.toString()
//     });

//     console.log(`Wallet credited for user ${userId}: ₹${amount}`);
//   } catch (error) {
//     console.error("Error crediting user wallet:", error);
//   }
// }







// module.exports = {
//   addMoneyViaGateway,
//   refreshPGTransactionStatus
// };























// // controllers/payment.controller.js
// const { authenticate, initiateTransaction, checkStatus } = require("../services/dollarbazar.service");
// const add_funds_module = require("../model/add_funds_module");
// const user_module = require("../model/user_module");
// const wallet_history = require("../model/wallet_trans_history_module"); // adjust actual model path

// // Generic helper to create merchant orderId
// function makeOrderId(prefix = "ORD") {
//   return `${prefix}${Date.now()}`;
// }

// /**
//  * POST /api/add-money/payment-gateway
//  * Body: { amount, customerEmail?, customerMobile?, transactionRemark?, payerVpa?, user_id }
//  * This endpoint authenticates with DollarBazar, initiates UPI collect, stores pending add_funds, and returns intentUrl.
//  */
// async function addMoneyViaGateway(req, res) {
//   try {

//     console.log("0000000000000000000000000000000000");
//     const { amount, customerEmail, customerMobile, transactionRemark, payerVpa, user_id } = req.body;
//     const userId = user_id || req.user; // support both

//     if (!amount || Number(amount) <= 0) return res.status(400).json({ success: false, msg: "Invalid amount" });

//     const user = await user_module.findById(userId);
//     if (!user) return res.status(404).json({ success: false, msg: "User not found" });

//     const orderId = makeOrderId();

//     // Step 1: authenticate
//     const authResp = await authenticate(amount, orderId);
//     if (!authResp || !authResp.api_token || !authResp.id_token) {
//       console.error("Auth failed:", authResp);
//       return res.status(500).json({ success: false, msg: "Authentication failed with gateway" });
//     }

//     const api_token = authResp.api_token;
//     const id_token = authResp.id_token;

//     // Step 2: initiate transaction
//     const txPayload = {
//       amount: String(amount),
//       orderId,
//       customerEmail: customerEmail || user.email || "test@example.com",
//       customerMobile: customerMobile || user.mobile || user.phone || "9999999999",
//       transactionRemark: transactionRemark || "Wallet Deposit",
//       payerVpa: payerVpa || "" // optional, if you want to pre-fill
//     };

//     const initResp = await initiateTransaction(api_token, id_token, txPayload);

//     // initResp expected shape: { success, data: { intentUrl, transactionId, paymentMethod... } }
//     if (!initResp) {
//       return res.status(500).json({ success: false, msg: "Initiate transaction failed" });
//     }

//     // Save a pending add_funds
//     await add_funds_module.create({
//       userDB_id: user._id,
//       amount: Number(amount),
//       tx_request_number: orderId,
//       // store gateway txn id if provided:
//       txn_ref: (initResp.data && (initResp.data.transactionId || initResp.data.transactionId)) || "",
//       payment_method: "DOLLARBAZAR",
//       fund_status: 0, // pending
//       deposit_type: 1,
//       gateway_raw_response: initResp
//     });

//     return res.json({
//       success: true,
//       msg: "Payment initiated",
//       orderId,
//       gateway_response: initResp,
//       upi_intent_url: initResp.data && initResp.data.intentUrl
//     });
//   } catch (err) {
//     console.error("addMoneyViaGateway error:", err?.response?.data || err);
//     return res.status(500).json({ success: false, msg: "Server Error" });
//   }
// }


// /**
//  * GET /api/deposit/status/:orderId
//  * Authenticates and calls status check
//  */
// async function getDepositStatus(req, res) {
//   try {
//     const { orderId } = req.params;
//     const deposit = await add_funds_module.findOne({ tx_request_number: orderId });
//     if (!deposit) return res.status(404).json({ success: false, msg: "Order not found" });

//     const authResp = await authenticate(deposit.amount, orderId);
//     if (!authResp || !authResp.api_token || !authResp.id_token) return res.status(500).json({ success: false, msg: "Auth failed" });

//     const statusResp = await checkStatus(authResp.api_token, authResp.id_token, orderId);

//     return res.json({ success: true, status: statusResp });
//   } catch (err) {
//     console.error("getDepositStatus error:", err);
//     return res.status(500).json({ success: false, msg: "Server Error" });
//   }
// }

// module.exports = {
//   addMoneyViaGateway,
//   getDepositStatus
// };