// controllers/paymentController.js
const axios       = require('axios');
const crypto      = require('crypto');
const dbConnect   = require('../configs/dbConnection');
const bookTicketModel = require('../model/bookTicketModel');
const smsModel    = require('../../smsapi/model/smsModel');
// const { sendConfirmationEmail } = require('../../emailapi/model/mailModel');
const { sendConfirmationEmail  } = require('../../emailapi/model/mailModel');
const { printticketEmailModel  } = require('../../emailapi/model/printTicketEmailModel');



function getCurrentTimestamp() {
  const pad = n => n.toString().padStart(2, '0');
  const d = new Date();
  const YYYY = d.getFullYear();
  const MM   = pad(d.getMonth() + 1);
  const DD   = pad(d.getDate());
  const hh   = pad(d.getHours());
  const mm   = pad(d.getMinutes());
  const ss   = pad(d.getSeconds());
  return `${YYYY}-${MM}-${DD} ${hh}:${mm}:${ss}`;
}

exports.bookTicket = async (req, res) => {
    const {uId:payeeid, ubal} = req.session.user;
  
    const {fare, name, blockedTicketId, email } = req.session.bus_booking;
     //let  { fare, payeeid, name, blockedTicketId, paymentfor ,email } = req.body;
    fare = parseFloat(fare).toFixed(2);
    console.log(fare, payeeid, name, blockedTicketId, paymentfor ,email);
    if (!fare || !payeeid || !blockedTicketId) {
    return res.status(400).json({ error: "Missing required fields" });
  }
  
  
  try {
   
        // const [userRows] = await dbConnect.query(
        //   `SELECT 
        //       did,
        //       ubal
        //   FROM ulogin
        //   WHERE uid = ?
        //   `,
        //   [payeeid]
        // );
        // if (!userRows.length) {
        //   console.warn(`No ulogin record found for uid ${payeeid}`);
        //   return;
        // }
        // let { did, ubal } = userRows[0];
        // // console.log(did, ubal);
       
        // ubal = parseFloat(ubal);
        // // console.log(userRows[0]);
     
        if(ubal >=  fare){
            
            
            //now insert the new row into ipgbdmirror
      const ts = getCurrentTimestamp();
      
      
            //DEBIT OPERATION -1
      //Insert the debit transaction into t_account
      const newbal1 = +(ubal - fare).toFixed(2);
      await dbConnect.query(
        `INSERT INTO t_account
           (id, treference, bal, tamount_dr, tamount_cr, newbal, datetime)
         VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [
          payeeid,              // id
          blockedTicketId,   // treference (“FINAL BUS BOOKINGID”)
          ubal,    // bal (the balance before this debit)
          fare,          // tamount_dr (we’re debiting the full interim balance)
          0,                // tamount_cr (credit is zero for this leg)
          newbal1 ,          // newbal (0)
          ts
        ]
      );
      //Update the user’s balance to 0 in ulogin
      await dbConnect.query(
        `UPDATE ulogin
            SET ubal = ?
          WHERE uid = ?`,
        [
          newbal1,  // 0
          payeeid
        ]
      );
      
      req.session.user.ubal = newbal1;
      
      
        // 4) Book the ticket
        
      const bookedTicketId = await bookTicketModel.bookTicketRequest(blockedTicketId);
      console.log (bookedTicketId);
     //const bookedTicketId = 
      // const bookedTicketId = '   8A58756E'
      
      const newbalinterim = parseFloat(newbal1);
      
       if (!bookedTicketId) {
         console.log('bookedTicketId block')
         
       //CREDIT OPERARTION -1 (insert t_account) 
      const newbalinterim = parseFloat(newbal1) + parseFloat(fare);
      
      await dbConnect.query(
        `INSERT INTO t_account
           (id, treference, bal, tamount_dr, tamount_cr, newbal, datetime)
         VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [
          payeeid,         // id (uid)
          blockedTicketId,   // treference (ORDERID/IPGID)
          newbal1,            // previous balance
          0,               // tamount_dr (debit from user; here zero)
          fare,          // tamount_cr (credit to user)
          newbalinterim,    // newbal
          ts
        ]
      );

      //  Update ulogin with the new balance
      await dbConnect.query(
        `UPDATE ulogin
            SET ubal = ?
          WHERE uid = ?`,
        [
          newbalinterim,   // new balance
          payeeid          // uid
        ]
      );
      req.session.user.ubal = newbalinterim;

return res.status(500).json({ 
  success: false, 
  message: `Ticket booking failed. However, your Reward Points have been added back to your reward balance. Your current reward balance is ${newbalinterim}.` 
});
      }

      // 5) Update uticket entry
      await dbConnect.query(
        'UPDATE uticket SET tin_ticket = ? WHERE blk_ticket = ?',
        [bookedTicketId, blockedTicketId]
      );
      
await dbConnect.query(
  'UPDATE t_account SET treference = ? WHERE id = ? AND treference = ?',
  [bookedTicketId, payeeid, blockedTicketId]
);


            // 6) Fetch passenger mobile
      const [[{ pmobile, pemail }]] = await dbConnect.query(
        `SELECT pmobile, pemail
           FROM uticket
          WHERE blk_ticket = ?`,
        [blockedTicketId]
      );
  
      if (!pmobile && !pemail) {
        // no contact info—treat as error or just warn
        console.warn(`No contact details found for blk_ticket=${blockedTicketId}`);
      }
      
      // 7) Send confirmation email
    let emailResult = null;
    let ptemailResult = null;
    if (pemail) {
      emailResult = await sendConfirmationEmail(pemail, bookedTicketId);
      ptemailResult = await printticketEmailModel(bookedTicketId);
    }

      // 6) Send SMS
    let smsResult = null;
    if (pmobile) {
      smsResult = await smsModel.sendSms(pmobile, bookedTicketId ,bookedTicketId, "BobrosMticketv2" , 'MTCKET');
    }
    
    req.session.bus_booking = null;
    
    
    //QUERY OFFERUSE FOR A MATCH COUNT blk_ticket if count = 0   (perform CREDIT OPERATION 2 then ) 
    const [[offerUseRow]] = await dbConnect.query(
      `SELECT COUNT(*) AS cnt
         FROM offeruse
        WHERE blk_ticket = ?`,
      [ blockedTicketId ]
    );
    
    if (offerUseRow.cnt === 0) {
      // 2) No prior record found—perform “credit operation‑2” (4% reward)
      //const bookingRwd = fare * 0.04;
      const bookingRwd = parseFloat((fare * 0.04).toFixed(2));
      const newBalAfterReward = newbalinterim + bookingRwd;   
      
      await dbConnect.query(
        `INSERT INTO offeruse
           (uid, umob, umail, offercode, discount, blk_ticket)
         VALUES (?, ?, ?, ?, ?, ?)`,
        [
          payeeid,           // payeeid
          pmobile,          // pmobile
          pemail,         // pemail
          'RewardPoints',     // RewardPoints
          bookingRwd,      // bookingRwd
          blockedTicketId     // blockedTicketId
        ]
      );
    
      await dbConnect.query(
        `INSERT INTO t_account
           (id, treference, bal, tamount_dr, tamount_cr, newbal, datetime)
         VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [
          payeeid,               // user id
          bookedTicketId,     // original IPG/ORDER ID
          newbalinterim,                 // balance before reward
          0,                 // tamount_dr
          bookingRwd,        // tamount_cr
          newBalAfterReward , // newbal
          ts
        ]
      );
    
      await dbConnect.query(
        `UPDATE ulogin
            SET ubal = ?
          WHERE uid = ?`,
        [
          newBalAfterReward,
          payeeid
        ]
      );
      
      req.session.user.ubal = newBalAfterReward;
    
      console.log(`Reward credited: ₹${bookingRwd.toFixed(2)}; new ubal = ₹${newBalAfterReward.toFixed(2)}`);
    }
    else{
      return res.status(200).json({
        success: true,
        message: 'Payment confirmed, ticket booked.',
        orderId :"Reward Points" ,
        bookedTicketId,
        smsResult,
        emailResult,
        rewardpoints : newbalinterim
      });
    }
    
   

    
    // 8) Respond with success
    return res.status(200).json({
      success: true,
      message: 'Payment confirmed, ticket booked.',
      orderId : "Reward Points",
      bookedTicketId,
      smsResult,
      emailResult
    });
    
    }
        
    else{
        console.log("your balance", ubal, "is insufficient to book ticket price", fare);
         return res.status(400).json({ success: false, message: 'Insufficient Reward Balance. Booking failed.' });
    }
        

  
      
  } catch (err) {
    console.error('RP booking flow error:', err);
    // Ensure DB reflects booking failure
    
    return res.status(500).json({ success: false, message: err.message });
  }
};
