
const mysql = require("mysql2/promise");
const Razorpay = require('razorpay');

const dbConnect = require('../configs/dbConnection');


exports.generatePaymentOrder = async (req, res) => {
  const { name, paymentfor, email } = req.body;
//   if (!fare || !uid || !ticketId) {
//     return res.status(400).json({ error: "Missing required fields" });
//   }

  const {fare, blockedTicketId : ticketId } = req.session.bus_booking;
  const {uid} = req.session.user;
  
  
  

  const razorpay = new Razorpay({
    key_id:     'rzp_live_wyxyLDS9NPZCPy',
    key_secret: '0mWsjR5ffOGHE4J2tiRKt1hy',
  });

  try {
    // 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
    ]);

    // 2) RAZORPAY ORDER
    const amountInPaise = Math.round(Number(fare) * 100);
    const order = await razorpay.orders.create({
      amount:         amountInPaise,
      currency:       'INR',
      receipt:        result.insertId.toString(),
      payment_capture: 1,
       "notes": {
            "emaild": email,
            "mobileno": uid,
            "tempbookid":ticketId,
            "name" : name
 }
    });

    // 3) UPDATE the same row
    const updateQuery = `
      UPDATE onlinepay
         SET ipgid = ?
       WHERE utranid     = ?
    `;
    await dbConnect.query(updateQuery, [
      order.id,
      result.insertId
    ]);
    
    req.session.bus_booking.paymentGateway = "razorpay";
    req.session.bus_booking.rporderid = order;
    
    
    // 4) RESPONSE
    res.status(200).json({
      insertId: result.insertId,
      order
    });

  } catch (err) {
    console.error("generatePaymentOrder error:", err);
    res.status(500).json({ error: err.message });
  }
};
