// const axios = require('axios');
// const jwt = require('jsonwebtoken');

// exports.enquirePayment = async (req, res, next) => {
//   console.log("==== Enquire Payment API Called ====");

//   const { orderid, transactionid } = req.body;

//   const mercid = 'HYDBOBROS';
//   const clientid = 'hydbobros';
//   const secretKey = 'niHCVRKWasUbe2MWR41DI3xtG3dKLWgR';
//   const billdeskURL = 'https://api.billdesk.com/payments/ve1_2/transactions/get';//https://uat1.billdesk.com/u2/payments/ve1_2/transactions/get // change to UAT/PROD accordingly

//   try {
//     console.log("Step 1: Preparing timestamp...");
//     const now = new Date();
//     const servertimeYYYYMMddHHmmss =
//       now.getFullYear().toString() +
//       String(now.getMonth() + 1).padStart(2, '0') +
//       String(now.getDate()).padStart(2, '0') +
//       String(now.getHours()).padStart(2, '0') +
//       String(now.getMinutes()).padStart(2, '0') +
//       String(now.getSeconds()).padStart(2, '0');
//     //console.log("Timestamp:", servertimeYYYYMMddHHmmss);

//     console.log("Step 2: Building payload...");
//     const payload = {
//       mercid,
//       orderid, // mandatory
//       //transactionid: transactionid || undefined // optional
//     };
//     console.log("Payload:", payload);

//     console.log("Step 3: Signing payload with JWT...");
//     const jwsHeader = { alg: 'HS256', clientid, kid: 'HMAC' };
//     const encodedPayload = jwt.sign(payload, secretKey, {
//       algorithm: 'HS256',
//       header: jwsHeader,
//     });
//     //console.log("Encoded Payload (JWT):", encodedPayload);

//     console.log("Step 4: Preparing headers...");
//     const headers = {
//       'Content-Type': 'application/jose',
//       'Accept': 'application/jose',
//       'BD-Traceid': orderid,
//       'BD-Timestamp': servertimeYYYYMMddHHmmss
//     };
//     //console.log("Headers:", headers);

//     console.log("Step 5: Sending request to BillDesk...");
//     const resp = await axios.post(billdeskURL, encodedPayload, { headers });
//     //console.log("Raw Response from BillDesk:", resp.data);

//     console.log("Step 6: Decoding BillDesk response...");
//     const decodedResp = jwt.verify(resp.data, secretKey, { algorithms: ['HS256'] });
//     //console.log("Decoded Enquiry Response:", decodedResp);

//     console.log("==== Enquire Payment API Success ====");
//     res.json({
//       decodedData: decodedResp,
      
//     });
    
//   } catch (err) {
//     console.log("==== Enquire Payment API Error ====");
//     if (err.response) {
//       console.log("Error Response from BillDesk:", err.response.data);
//       try {
//         const decodedError = jwt.verify(err.response.data, secretKey, { algorithms: ['HS256'] });
//         console.log("Decoded Error Response:", decodedError);
//         return res.status(err.response.status).send(decodedError);
//       } catch (verifyErr) {
//         console.log("Error decoding BillDesk error response:", verifyErr.message);
//         return res.status(err.response.status).send(err.response.data);
//       }
//     }
//     console.log("Unhandled Error:", err.message);
//     next(new Error('Invalid response signature or server error'));
//   }
// };








const { processEnquirePayment } = require('../model/enquirePaymentModel');
require("dotenv").config();

exports.enquirePayment = async (req, res, next) => {
  console.log("==== Enquire Payment Controller Called ====");

  const { orderid } = req.body;
  const mercid = process.env.BD_MERCHANT_ID_PROD;
  console.log("mercid: ", mercid);

  if (!orderid) {
    return res.status(400).json({ error: "Missing required fields: mercid or orderid" });
  }

  try {
    const result = await processEnquirePayment(mercid, orderid);
    
     const sql = `
        INSERT INTO bd_enquire_payment_response (
            order_id, trans_id, transaction_date, amount, surcharge, discount, 
            charge_amount, bank_id, bank_ref_no, auth_status, transaction_error_desc, 
            transaction_error_type, payment_method, payment_category
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
        amount = VALUES(amount),
        surcharge = VALUES(surcharge), 
        discount = VALUES(discount), 
        charge_amount = VALUES(charge_amount),
        bank_id = VALUES(bank_id),
        bank_ref_no = VALUES(bank_ref_no), 
        auth_status = VALUES(auth_status),
        transaction_error_desc = VALUES(transaction_error_desc), 
        transaction_error_type = VALUES(transaction_error_type),
        payment_method = VALUES(payment_method), 
        payment_category = VALUES(payment_category)
    `;
    
    
    const values = [
    result.orderid ?? null,
    result.transactionid ?? null,
    result.transaction_date ? new Date(res.transaction_date) : null,
    result.amount ?? null,
    result.surcharge ?? null,
    result.discount ?? null,
    result.charge_amount ?? null,
    result.bankid ?? null,
    result.bank_ref_no ?? null,
    result.auth_status ?? null, 
    result.transaction_error_desc ?? null,
    result.transaction_error_type ?? null,
    result.payment_method_type ?? null,
    result.payment_category ?? null
  ];

  try {
    await dbConnect.execute(sql, values);
    console.log("✅ Enquire Payment Data Inserted Successfully");
  } catch (err) {
    console.error("❌ DB Insert Error:", err);
    throw err;
  }
  
  // update online pay table
  const order_id = result.orderid;
  const authStatus = result.auth_status;
  
  const status =
        authStatus === "0300" ? "Transaction Successful" :
        authStatus === "0399" ? "Transaction Failed" :
        "Transaction Pending";
        
        
  await dbConnect.query(
      "UPDATE onlinepay SET status = ? WHERE ipgid = ?",
      [status, order_id]
    );

    if (result.success) {
      console.log("✅ Enquire Payment Completed Successfully");
      return res.status(200).json({
        success: true,
        message: "Enquiry payment processed successfully",
        decodedData: result.data
      });
    } else {
      console.error("❌ Enquire Payment Failed:", result.error || result.message);
      return res.status(400).json({
        success: false,
        message: "Failed to process enquiry payment",
        error: result.error || result.message
      });
    }
  } catch (error) {
    console.error("🔥 Controller Fatal Error:", error);
    return res.status(500).json({
      message: "Internal Server Error",
      error: error.message
    });
  }
};
