// // billdeskpg/services/billdeskService.js
// // const { v4: uuidv4 } = require("uuid");
// // const model = require("../models/billdeskmodel.js");
// const billdeskClient = require("../utils/billdeskClient");
// require("dotenv").config();
// const dbConnect = require('../../busapi/configs/dbConnection');

// //  const { fare, uid, name, ticketId, paymentfor ,email } = req.body;
// //   if (!fare || !uid || !ticketId) {
// //     return res.status(400).json({ error: "Missing required fields" });
// //   }
  
// async function createOrder(body) {
//     console.log("create order req received");
//   if (!body || !body.amount || !body.customer || !body.customer.first_name || !body.customer.last_name) {
//     const err = new Error("Missing required fields: amount and customer (first_name,last_name)");
//     err.statusCode = 400;
//     throw err;
//   }
  
//   const {amount, ticket_id, paymentfor, user_id, customer} = body

//   const orderid = `BDPG_${Date.now()}`;
//   console.log("orderid: ", orderid)
  
//   //code added for order_date calculation
//   const now = new Date();
//   const isoString = now.toISOString().split('.')[0]; // Remove milliseconds
//   const timezoneOffsetMinutes = now.getTimezoneOffset();
  
//   const offsetHours = String(Math.floor(Math.abs(timezoneOffsetMinutes) / 60)).padStart(2, '0');
//   const offsetMinutes = String(Math.abs(timezoneOffsetMinutes) % 60).padStart(2, '0');
//   const offsetSign = timezoneOffsetMinutes <= 0 ? '+' : '-';

//   const timezone = `${offsetSign}${offsetHours}:${offsetMinutes}`;
//   const atomDateTime = `${isoString}${timezone}`;
//   //end

//   const payload = {
//     orderid,
//     mercid: process.env.BD_MERCHANT_ID,
//     // order_date: new Date().toISOString(),
//     order_date: atomDateTime,
//     amount: Number(body.amount).toFixed(2),
//     currency: body.currency || "356",
//     ru: process.env.BD_RETURN_URL,
//     itemcode: body.itemcode || "DIRECT",
//     mandate_required: body.mandate_required || "N",
//     customer: body.customer,
//     device: body.device || {
//       init_channel: "internet",
//       ip: body.ip || "192.168.0.1", // ip hardcoded
//       user_agent: body.user_agent || "Mozilla/5.0(WindowsNT10.0;WOW64;rv: 51.0)Gecko/20100101Firefox/51.0",
//       accept_header: body.accept_header || "application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
//     }
//   };

//   // insert order
// //   await model.insertOrder({
// //     orderid,
// //     amount: payload.amount,
// //     customer: JSON.stringify(payload.customer),
// //     payload: payload,
// //     status: "INITIATED",
// //     traceid: null,
// //     created_at: new Date()
// //   });
// const insertQuery = `
//       INSERT INTO onlinepay
//         (tranamount, payeename, serviceref_id, ipgid, payeeid, servicetype, status)
//       VALUES (?, ?, ?, 0, ?, ?, 'initiated')
//     `;
    
// const [result] = await dbConnect.query(insertQuery, [
//       amount, customer.first_name + " " + customer.last_name, ticketId, uid, paymentfor
//     ]);




//   // call billdesk
//   const clientId = process.env.BD_CLIENT_ID || process.env.BD_MERCHANT_ID;
//   const encKey = process.env.BD_ENC_KEY;
//   const sigKey = process.env.BD_SIGN_KEY;
  
//   console.log("clientId: ", clientId, "encKey: ", encKey, "sigKey: ",sigKey );

//   const order = await billdeskClient.callBilldesk({
//     path: 'orders/create',
//     payload,
//     clientId,
//     encKey,
//     sigKey
//   });
//   console.log("order: ", order);

// //   await model.updateOrderByOrderId(orderid, {
// //     status: result.status || 'ACTIVE',
// //     bdorderid: result.bdorderid || null,
// //     raw_response: JSON.stringify(result),
// //     updated_at: new Date()
// //   });

// // 3) UPDATE the same row
//     const updateQuery = `
//       UPDATE onlinepay
//          SET ipgid = ?
//       WHERE utranid     = ?
//     `;
//     await dbConnect.query(updateQuery, [
//       order.bdorderid,
//       result.insertId
//     ]);


//   return {
//     orderid,
//     bdorderid: result.bdorderid || null,
//     next_step: result.next_step || null,
//     links: result.links || [],
//     raw: result
//   };
// }

// module.exports = { createOrder };




// billdeskpg/services/billdeskService.js

const billdeskClient = require("../utils/billdeskClient");
const dbConnect = require("../../busapi/configs/dbConnection");
require("dotenv").config();

async function createOrder(body) {
  console.log("BillDesk createOrder request received");

  /* =====================================================
     1. BASIC VALIDATION (BillDesk mandatory fields)
     ===================================================== */
  if (
    !body ||
    !body.amount ||
    !body.ticket_id ||
    !body.user_id ||
    !body.paymentfor ||
    !body.customer ||
    !body.customer.first_name ||
    !body.customer.last_name
  ) {
    const err = new Error(
      "Missing required fields: amount, ticket_id, user_id, paymentfor, customer(first_name,last_name)"
    );
    err.statusCode = 400;
    throw err;
  }
  console.log("BillDesk createOrder request received1");

  const {
    amount,
    ticket_id,
    user_id,
    paymentfor,
    customer,
    device,
    additional_info
  } = body;
console.log("BillDesk createOrder request received2");
  /* =====================================================
     2. GENERATE MERCHANT ORDER ID
     ===================================================== */
  const orderid = `BDPG${Date.now()}`;
  console.log("orderid: ", orderid )

  /* =====================================================
     3. ORDER DATE (YYYY-MM-DDThh:mm:ssTZD)
     ===================================================== */
  const now = new Date();
  const isoString = now.toISOString().split(".")[0];
  const offsetMinutes = now.getTimezoneOffset();
  const sign = offsetMinutes <= 0 ? "+" : "-";
  const hours = String(Math.floor(Math.abs(offsetMinutes) / 60)).padStart(2, "0");
  const minutes = String(Math.abs(offsetMinutes) % 60).padStart(2, "0");
  const orderDate = `${isoString}${sign}${hours}:${minutes}`;

  /* =====================================================
     4. DB INSERT — SAME AS RAZORPAY (INITIATED)
     ===================================================== */
  const insertQuery = `
    INSERT INTO onlinepay
      (tranamount, payeename, serviceref_id, ipgid, payeeid, servicetype, status)
    VALUES (?, ?, ?, 0, ?, ?, 'initiated')
  `;

  const [insertResult] = await dbConnect.query(insertQuery, [
    Number(amount).toFixed(2),
    `${customer.first_name} ${customer.last_name}`,
    ticket_id,
    user_id,
    paymentfor
  ]);
  console.log("BillDesk createOrder request received3");

  const utranid = insertResult.insertId;

  /* =====================================================
     5. BUILD BILLDESK PAYLOAD (DOC-COMPLIANT ONLY)
     ===================================================== */
  const payload = {
    orderid,
    mercid: process.env.BD_MERCHANT_ID,
    order_date: orderDate,
    amount: Number(amount).toFixed(2),
    currency: "356",
    ru: process.env.BD_RETURN_URL,
    itemcode: "DIRECT",
    mandate_required: "N",
    device: {
      init_channel: body.init_channel ||"internet",
      ip: body.ip || "192.168.0.1", // ip hardcoded
      user_agent: body.user_agent || "Mozilla/5.0(WindowsNT10.0;WOW64;rv: 51.0)Gecko/20100101Firefox/51.0",
      accept_header: body.accept_header || "application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
    },
    additional_info : {
        "additional_info1": paymentfor,
        "additional_info2": ticket_id,
        "additional_info3": amount,
        "additional_info4": "NA",
        "additional_info5": "NA",
        "additional_info6": "NA",
        "additional_info7": "NA"
        },
    
  };

  // optional fields (only if provided)
//   if (device) payload.device = device;
//   if (additional_info) payload.additional_info = additional_info;

  /* =====================================================
     6. CALL BILLDESK CREATE ORDER API
     ===================================================== */
  const clientId = process.env.BD_CLIENT_ID || process.env.BD_MERCHANT_ID_UAT;
  console.log("Create Order Request: ", payload);
  


  const billdeskResponse = await billdeskClient.callBilldesk({
    orderid,
    path: "orders/create",
    payload,
    clientId,
    keyId: process.env.BD_KEY_ID,
    encKey: process.env.BD_ENC_KEY,
    sigKey: process.env.BD_SIGN_KEY
  });

  /* =====================================================
     7. DB UPDATE — STORE BILLDESK ORDER ID
     ===================================================== */
  const updateQuery = `
    UPDATE onlinepay
       SET ipgid = ?
     WHERE utranid = ?
  `;

  await dbConnect.query(updateQuery, [
    billdeskResponse.orderid || null,
    utranid
  ]);

  /* =====================================================
     8. RETURN RESPONSE TO CONTROLLER
     ===================================================== */
  return {
    utranid,
    orderid,
    bdorderid: billdeskResponse.bdorderid || null,
    next_step: billdeskResponse.next_step || null,
    links: billdeskResponse.links || [],
    raw: billdeskResponse
  };
}

module.exports = { createOrder };

