
const cors    = require('cors');
const axios   = require('axios');
const jwt     = require('jsonwebtoken');
const mysql = require("mysql2/promise");
const dbConnect = require('../configs/dbConnection');

//const { fetchOnlinePay } = require('../configs/dbConnection');


exports.generatePaymentOrder = async (req, res) => {

  const {
    //fare,
    //orderDate,
    //uid,
     name,
    //ticketId,
    paymentfor,
    userIp,
    
  } = req.body;
  
  const {fare, blockedTicketId : ticketId } = req.session.bus_booking;
  const {uid} = req.session.user;
  
  
  
  
   // 1) INSERT
    const insertQuery = `
      INSERT INTO onlinepay
        (tranamount, payeename, serviceref_id, ipgid, payeeid, servicetype, status)
      VALUES (?, ?, ?, 0, ?, ?, 'initiated')
    `;
    const [result] = await dbConnect.query(insertQuery, [
      fare, name, ticketId, uid, paymentfor
    ]);





const mercid      = 'HYDBOBROS';
const clientid    = 'hydbobros';
const secretKey   = 'niHCVRKWasUbe2MWR41DI3xtG3dKLWgR';
const billdeskURL = 'https://api.billdesk.com/payments/ve1_2/orders/create';
const responseURL = 'http://api.bobros.co.in/';



//const orderid   ='CKN2304';

                       
const now = new Date();

  // toISOString gives format: 'YYYY-MM-DDTHH:mm:ss.sssZ'
  // We strip milliseconds and replace 'Z' with timezone offset
  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}`;


console.log(atomDateTime)

const currentTimestamp = Date.now(); // or any specific timestamp in milliseconds
const date = new Date(currentTimestamp);

const servertimeYYYYMMddHHmmss = 
    date.getFullYear().toString() +
    String(date.getMonth() + 1).padStart(2, '0') +
    String(date.getDate()).padStart(2, '0') +
    String(date.getHours()).padStart(2, '0') +
    String(date.getMinutes()).padStart(2, '0') +
    String(date.getSeconds()).padStart(2, '0');

console.log(servertimeYYYYMMddHHmmss);

//console.log(orderDate);
 //console.log(bdTs);
    const payload = {
      orderid : ticketId, //block ticket id
      mercid  :'HYDBOBROS',
      amount  :fare,
      order_date: atomDateTime,
      currency:     '356',
      ru:           'http://api.bobros.co.in/',
      additional_info: {
        additional_info1: uid,
        additional_info2: name,
        additional_info3: ticketId,
        additional_info4: paymentfor,
        additional_info5: 'NA',
        additional_info6: 'NA',
        additional_info7: 'NA'
      },
      itemcode: 'DIRECT',
      device: {
        init_channel:'internet',
        ip:           userIp,
        mac:          'B4:7C:9C:3E:45:A1',
        imei:         '356938035643809',
        user_agent:   "Mozilla/5.0(WindowsNT10.0;WOW64;rv: 51.0)Gecko/20100101Firefox/51.0",
        accept_header: 'application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
      }
    };
    
    // Sign with HS256 HMAC
    const jwsHeader = { alg: 'HS256', clientid, kid: "HMAC"};

    // const encodedPayload = jwt.sign(payload, secretKey, options )
    
    const encodedPayload  = jwt.sign(payload, secretKey, {
      algorithm: 'HS256',
      header: jwsHeader,
    });

    console.log("encodedPayload:", encodedPayload)
 
    const headers = {
      'Content-Type': 'application/jose',
      'Accept'      : 'application/jose',
      'BD-Traceid':   ticketId,
      'BD-Timestamp': servertimeYYYYMMddHHmmss
    };
    console.log("headers", headers);


  try {

    const resp = await axios.post(billdeskURL, encodedPayload, { headers });
    console.log("resp", resp);

    const decodedResp = jwt.verify(resp.data, secretKey, { algorithms: ['HS256'] });
    console.log("decodedResp", decodedResp);
    
    req.session.bus_booking.paymentGateway = "billdesk";
    req.session.bus_booking.bdorderid = bdorderid;
    
    // 3) UPDATE the same row
    const updateQuery = `
      UPDATE onlinepay
         SET ipgid = ?
       WHERE utranid     = ?
    `;
    await dbConnect.query(updateQuery, [
    decodedResp.bdorderid,
     result.insertId
    ]);
    res.json({
  decodedData: {
    merchantOrderId: decodedResp.orderid,
    bdOrderId:       decodedResp.bdorderid,
    authToken:       decodedResp.authToken
  },
  originalResponse: resp.data // or just `resp` if you want everything, but usually `resp.data` is enough
});
    // res.status(200).send(decoded);
  }
  catch (err) {
    // Distinguish HTTP errors from signature errors
    if (err.response) {
      // BillDesk returned a non‑2xx status: forward their payload & status
     const decodedResp = jwt.verify(err.response.data, secretKey, { algorithms: ['HS256'] });
    console.log("decodedResp", decodedResp);
      return res.status(err.response.status).send(decodedResp);
    }
    // Signature verification or other server error
    next(new Error('Invalid response signature or server error'));
  }
};