const dbConnect = require('../configs/dbConnection.js');
const { sendOtp, verifyOtp } = require('../../smsapi/model/smsModel');
const { verifyCaptcha } = require('../utils/verifyCaptcha.js');
const bcrypt = require('bcryptjs');
const { sendSignupEmail } = require('../../emailapi/model/mailModel');  

exports.CheckUser = async (req, res) => {
  try {
    const { user, email, mobile, password /*, recaptcha: token */ } = req.body;
    console.log('CheckUser payload:', user, email, mobile);

    // Basic field check
    if (!user || !mobile || !email || !password) {
      // Send “error” email notifying failure
      try {
        await sendSignupEmail(email, user, mobile, null, 'error');
      } catch (mailErr) {
        console.error('Mail error (error case):', mailErr);
      }
      return res.status(400).json({ error: 'All fields are mandatory' });
    }

    // Check existing user
    const [existingRows] = await dbConnect.query(
      `SELECT umob, umail FROM ulogin WHERE umob=? OR umail=?`,
      [mobile, email]
    );
    if (existingRows.length > 0) {
      // Send “exists” email
      try {
        await sendSignupEmail(email, user, mobile, null, 'exists');
      } catch (mailErr) {
        console.error('Mail error (exists case):', mailErr);
      }
      return res.status(409).json({ error: 'Already registered' });
    }

    // Send OTP
    const formattedMobile = '+91' + String(mobile).replace(/\D/g, '').replace(/^0|^91/, '');
    const sendSmsResponse = await sendOtp(formattedMobile, 'BOBROSOTP');
    if (!sendSmsResponse) {
      return res.status(500).json({ error: 'Failed to send OTP' });
    }

    return res.status(200).json({ sendSmsResponse });
  } catch (error) {
    console.error('Error in CheckUser:', error);
    return res.status(500).json({ error: error.message });
  }
};

console.log('🚨 registerUser called:', new Date().toISOString());

exports.registerUser = async (req, res) => {
  let newUserId = null;

  try {
    const { user, email, mobile, password, otp } = req.body;
    console.log('registerUser payload:', user, email, mobile, otp);
    
     // 1️⃣ Validate mandatory fields
    if (!user || !email || !mobile || !password || !otp) {
      return res.status(400).json({
        error: 'All fields (user, email, mobile, password, otp) are required.',
      });
    }


    // 1) Verify OTP
    const isOtpValid = await verifyOtp(mobile, otp);
    if (isOtpValid.Details === "OTP Mismatch"){
        return res.status(400).json({ error: 'OTP verification failed' });
    }
    
    // const [existing] = await dbConnect.query(
    //     `SELECT uid FROM ulogin WHERE umob=? OR umail=?`,
    //     [mobile, email]);
        
    // if (existing.length > 0) {
    //     console.log("USER EXISTS!!!!")
    //     return res.status(409).json({ error: 'User already exists' });
        
    // }
    // if (!isOtpValid) {
    //   try {
    //     await sendSignupEmail(email, user, mobile, null, 'error');
    //   } catch (mailErr) {
    //     console.error('Mail error (OTP failure):', mailErr);
    //   }
    //   return res.status(400).json({ error: 'OTP verification failed' });
    // }

    // 2) Hash password
    const hashedPassword = await bcrypt.hash(password, 10);

    // 3) Insert into DB (user)
    const insertQuery = `
      INSERT INTO ulogin (
        uuser, upass, umob, uname,
        ubal, ucred, umail, uadd,
        ucity, ustate, upin, ucrate,
        did, uflag, pwdchangedate
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
    `;
    const insertValues = [
      mobile,
      hashedPassword,
      mobile,
      user,
      0,    // ubal
      0,    // ucred
      email,
      'Nil', // uadd
      'Nil', // ucity
      'Nil', // ustate
      'Nil', // upin
      0,     // ucrate
      'Admin',
      'Active'
    ];

    const conn = await dbConnect.getConnection();
    try {
      await conn.beginTransaction();

      const [result] = await conn.query(insertQuery, insertValues);
      newUserId = result.insertId;

      // PHP variable names
      const uid = newUserId;
      const value2 = `Sign Up Bonus ${uid}`;
      const tamount = 0;
      const amount = 100;
      const newbal = 100;
      const did = 'Admin';
      const ubal = 0;

      // Fetch admin balance
      const [rows] = await conn.query(
        'SELECT dbal FROM dlogin WHERE did = ?',
        [did]
      );
      if (rows.length === 0) throw new Error('Admin record not found');
      const dbal = parseFloat(rows[0].dbal);

      // Calculate new admin balance
      const newadminbal = dbal - amount;

      // Admin debit transaction
      await conn.query(
        `INSERT INTO t_account (id, treference, bal, tamount_dr, tamount_cr, newbal, datetime)
         VALUES (?, ?, ?, ?, ?, ?, NOW())`,
        [did, value2, dbal, amount, tamount, newadminbal]
      );

      // Update admin balance
      await conn.query(
        'UPDATE dlogin SET dbal = ? WHERE did = ?',
        [newadminbal, did]
      );

      // User credit transaction
      await conn.query(
        `INSERT INTO t_account (id, treference, bal, tamount_dr, tamount_cr, newbal, datetime)
         VALUES (?, ?, ?, ?, ?, ?, NOW())`,
        [uid, value2, ubal, tamount, amount, newbal]
      );

      // Update user balance
      await conn.query(
        'UPDATE ulogin SET ubal = ? WHERE uid = ?',
        [newbal, uid]
      );

      await conn.commit();
    } catch (txErr) {
      await conn.rollback();
      throw txErr;
    } finally {
      conn.release();
    }

    console.log('New user ID:', newUserId);

    // 4) On success → send “success” email
    try {
      await sendSignupEmail(email, user, mobile, newUserId, 'success');
    } catch (mailErr) {
      console.error('Mail error (success case):', mailErr);
    }

    return res.status(201).json({
      msg: 'User registered successfully',
      userId: newUserId
    });
  } catch (error) {
    console.error('Error in registerUser:', error);

    if (error.code === 'ER_DUP_ENTRY') {
      try {
        await sendSignupEmail(req.body.email, req.body.user, req.body.mobile, null, 'exists');
      } catch (mailErr) {
        console.error('Mail error (exists fallback):', mailErr);
      }
      return res.status(409).json({ error: 'User already exists' });
    }

    try {
      await sendSignupEmail(req.body.email, req.body.user, req.body.mobile, null, 'error');
    } catch (mailErr) {
      console.error('Mail error (generic failure):', mailErr);
    }

    return res.status(500).json({ error: error.message });
  }
};
