/* =========================================================
   ZA-FARM-KH — Telegram Bot Integration (MySQL version)
   ========================================================= */

const TelegramBot = require("node-telegram-bot-api");

const TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const ADMIN_CHAT_ID = process.env.TELEGRAM_ADMIN_CHAT_ID;

let bot = { isActive: false };

if (TOKEN) {
  const telegramBot = new TelegramBot(TOKEN, {
    polling: {
      autoStart: true,
      params: { timeout: 10 },
    },
  });
  bot = telegramBot;
  bot.isActive = true;

  // Suppress repeated polling errors
  let pollingErrorLogged = false;
  telegramBot.on("polling_error", (err) => {
    if (!pollingErrorLogged) {
      console.error("⚠️  Telegram polling error:", err.message || err.code);
      pollingErrorLogged = true;
    }
    if (err.code === "ETELEGRAM" && (err.message?.includes("404") || err.message?.includes("401") || err.message?.includes("409") || err.message?.includes("Conflict"))) {
      telegramBot.stopPolling();
      bot.isActive = false;
      console.error("   → Bot polling stopped (invalid/conflict token).");
    }
  });

  // /start
  telegramBot.onText(/\/start/, (msg) => {
    telegramBot.sendMessage(msg.chat.id,
      `🟢 *ZA-FARM-KH Bot*\n\nសួស្ដី! Bot នេះសម្រាប់ទទួល notification។\n\nYour Chat ID: \`${msg.chat.id}\`\n\nCommands:\n/stock — មើល stock\n/orders — មើល orders ថ្មីៗ\n/balance — មើល total revenue\n/help — បង្ហាញ commands`,
      { parse_mode: "Markdown" }
    );
  });

  // /stock
  telegramBot.onText(/\/stock/, async (msg) => {
    try {
      const { query } = require("./db");
      const services = await query("SELECT * FROM services");
      let text = "📦 *Stock Update*\n\n";
      services.forEach(s => {
        text += `• ${s.title}: *${s.stock}* ($${parseFloat(s.price).toFixed(3)})\n`;
      });
      telegramBot.sendMessage(msg.chat.id, text, { parse_mode: "Markdown" });
    } catch (err) {
      telegramBot.sendMessage(msg.chat.id, "❌ Error: " + err.message);
    }
  });

  // /orders
  telegramBot.onText(/\/orders/, async (msg) => {
    try {
      const { query } = require("./db");
      const orders = await query("SELECT * FROM orders ORDER BY createdAt DESC LIMIT 10");
      if (orders.length === 0) {
        telegramBot.sendMessage(msg.chat.id, "📋 មិនទាន់មាន orders ទេ");
        return;
      }
      let text = "📋 *Recent Orders (last 10)*\n\n";
      orders.forEach(o => {
        text += `• ${o.service} x${o.qty} — $${parseFloat(o.total).toFixed(3)} — ${o.status}\n  👤 ${o.username}\n\n`;
      });
      telegramBot.sendMessage(msg.chat.id, text, { parse_mode: "Markdown" });
    } catch (err) {
      telegramBot.sendMessage(msg.chat.id, "❌ Error: " + err.message);
    }
  });

  // /balance
  telegramBot.onText(/\/balance/, async (msg) => {
    try {
      const { query } = require("./db");
      const result = await query("SELECT COUNT(*) as count, COALESCE(SUM(total), 0) as total FROM orders");
      const { count, total } = result[0];
      telegramBot.sendMessage(msg.chat.id,
        `💰 *Total Revenue*: $${parseFloat(total).toFixed(3)}\n📦 *Total Orders*: ${count}`,
        { parse_mode: "Markdown" }
      );
    } catch (err) {
      telegramBot.sendMessage(msg.chat.id, "❌ Error: " + err.message);
    }
  });

  // ===== ADMIN COMMANDS =====

  // /addbal <username> <amount>
  telegramBot.onText(/\/addbal\s+(\S+)\s+([\d.]+)/, async (msg, match) => {
    if (String(msg.chat.id) !== String(ADMIN_CHAT_ID)) {
      telegramBot.sendMessage(msg.chat.id, "❌ អ្នកមិនមានសិទ្ធិប្រើ command នេះទេ");
      return;
    }
    try {
      const { query, queryOne } = require("./db");
      const targetUsername = match[1];
      const amount = parseFloat(match[2]);
      if (!amount || amount <= 0) {
        telegramBot.sendMessage(msg.chat.id, "❌ Amount មិនត្រឹមត្រូវ");
        return;
      }
      const user = await queryOne(
        "SELECT * FROM users WHERE username = ? OR email = ? OR apiKey = ?",
        [targetUsername, targetUsername, targetUsername]
      );
      if (!user) {
        telegramBot.sendMessage(msg.chat.id, `❌ រកមិនឃើញ user: \`${targetUsername}\``, { parse_mode: "Markdown" });
        return;
      }
      const oldBalance = parseFloat(user.balance);
      const newBalance = parseFloat((oldBalance + amount).toFixed(3));
      await query("UPDATE users SET balance = ? WHERE id = ?", [newBalance, user.id]);
      const text = `✅ *បានដាក់លុយជោគជ័យ!*\n\n👤 User: \`${user.username}\`\n💵 ដាក់បន្ថែម: +$${amount.toFixed(3)}\n💰 Balance ចាស់: $${oldBalance.toFixed(3)}\n💰 Balance ថ្មី: $${newBalance.toFixed(3)}`;
      telegramBot.sendMessage(msg.chat.id, text, { parse_mode: "Markdown" });
    } catch (err) {
      telegramBot.sendMessage(msg.chat.id, "❌ Error: " + err.message);
    }
  });

  // /setbal <username> <amount>
  telegramBot.onText(/\/setbal\s+(\S+)\s+([\d.]+)/, async (msg, match) => {
    if (String(msg.chat.id) !== String(ADMIN_CHAT_ID)) {
      telegramBot.sendMessage(msg.chat.id, "❌ អ្នកមិនមានសិទ្ធិប្រើ command នេះទេ");
      return;
    }
    try {
      const { query, queryOne } = require("./db");
      const targetUsername = match[1];
      const amount = parseFloat(match[2]);
      if (isNaN(amount) || amount < 0) {
        telegramBot.sendMessage(msg.chat.id, "❌ Amount មិនត្រឹមត្រូវ");
        return;
      }
      const user = await queryOne(
        "SELECT * FROM users WHERE username = ? OR email = ? OR apiKey = ?",
        [targetUsername, targetUsername, targetUsername]
      );
      if (!user) {
        telegramBot.sendMessage(msg.chat.id, `❌ រកមិនឃើញ user: \`${targetUsername}\``, { parse_mode: "Markdown" });
        return;
      }
      const oldBalance = parseFloat(user.balance);
      await query("UPDATE users SET balance = ? WHERE id = ?", [amount, user.id]);
      const text = `✅ *បានកំណត់ Balance!*\n\n👤 User: \`${user.username}\`\n💰 Balance ចាស់: $${oldBalance.toFixed(3)}\n💰 Balance ថ្មី: $${amount.toFixed(3)}`;
      telegramBot.sendMessage(msg.chat.id, text, { parse_mode: "Markdown" });
    } catch (err) {
      telegramBot.sendMessage(msg.chat.id, "❌ Error: " + err.message);
    }
  });

  // /users
  telegramBot.onText(/\/users/, async (msg) => {
    if (String(msg.chat.id) !== String(ADMIN_CHAT_ID)) {
      telegramBot.sendMessage(msg.chat.id, "❌ អ្នកមិនមានសិទ្ធិប្រើ command នេះទេ");
      return;
    }
    try {
      const { query } = require("./db");
      const users = await query("SELECT username, balance FROM users ORDER BY createdAt DESC LIMIT 20");
      if (users.length === 0) {
        telegramBot.sendMessage(msg.chat.id, "📋 មិនទាន់មាន users ទេ");
        return;
      }
      let text = `👥 *Users (last 20)*\n\n`;
      users.forEach((u, i) => {
        text += `${i + 1}. \`${u.username}\` — $${parseFloat(u.balance).toFixed(3)}\n`;
      });
      telegramBot.sendMessage(msg.chat.id, text, { parse_mode: "Markdown" });
    } catch (err) {
      telegramBot.sendMessage(msg.chat.id, "❌ Error: " + err.message);
    }
  });

  // /getkey <username>
  telegramBot.onText(/\/getkey\s+(\S+)/, async (msg, match) => {
    if (String(msg.chat.id) !== String(ADMIN_CHAT_ID)) {
      telegramBot.sendMessage(msg.chat.id, "❌ អ្នកមិនមានសិទ្ធិប្រើ command នេះទេ");
      return;
    }
    try {
      const { queryOne } = require("./db");
      const targetUsername = match[1];
      const user = await queryOne("SELECT * FROM users WHERE username = ?", [targetUsername]);
      if (!user) {
        telegramBot.sendMessage(msg.chat.id, `❌ រកមិនឃើញ user: \`${targetUsername}\``, { parse_mode: "Markdown" });
        return;
      }
      const text = `🔑 *API Key Info*\n\n👤 Username: \`${user.username}\`\n📧 Email: \`${user.email}\`\n🔑 API Key: \`${user.apiKey}\`\n💰 Balance: $${parseFloat(user.balance).toFixed(3)}`;
      telegramBot.sendMessage(msg.chat.id, text, { parse_mode: "Markdown" });
    } catch (err) {
      telegramBot.sendMessage(msg.chat.id, "❌ Error: " + err.message);
    }
  });

  // /help
  telegramBot.onText(/\/help/, (msg) => {
    const isAdmin = String(msg.chat.id) === String(ADMIN_CHAT_ID);
    let text = `📖 *ZA-FARM-KH Bot Commands*\n\n`;
    text += `🔹 /start — ព័ org មានអំពី Bot\n`;
    text += `🔹 /stock — មើល stock\n`;
    text += `🔹 /orders — មើល orders ថ្មីៗ\n`;
    text += `🔹 /balance — មើល total revenue\n`;
    if (isAdmin) {
      text += `\n🔐 *Admin Commands:*\n\n`;
      text += `🔸 /addbal <username> <amount> — ដាក់លុយ\n`;
      text += `🔸 /setbal <username> <amount> — កំណត់ balance\n`;
      text += `🔸 /users — មើល user list\n`;
      text += `🔸 /getkey <username> — យក API key\n`;
    }
    telegramBot.sendMessage(msg.chat.id, text, { parse_mode: "Markdown" });
  });

  console.log("🤖 Telegram bot started");

  // Handle Callback Queries (Inline Buttons)
  telegramBot.on('callback_query', async (query) => {
    if (!query.data) return;
    const chatId = query.message.chat.id;
    const messageId = query.message.message_id;

    if (String(chatId) !== String(ADMIN_CHAT_ID)) {
      telegramBot.answerCallbackQuery(query.id, { text: "❌ Unauthorized", show_alert: true });
      return;
    }

    if (query.data.startsWith('approve_')) {
      const md5 = query.data.replace('approve_', '');
      try {
        const { query: dbQuery, queryOne, insert } = require("./db");
        const payment = await queryOne("SELECT * FROM payments WHERE id = ?", [md5]);
        
        if (!payment) {
          telegramBot.answerCallbackQuery(query.id, { text: "❌ Payment not found", show_alert: true });
          return;
        }
        
        if (payment.status === 'completed') {
          telegramBot.answerCallbackQuery(query.id, { text: "✅ Already completed!", show_alert: true });
          // Update button text to show it's completed
          telegramBot.editMessageReplyMarkup({ inline_keyboard: [[{ text: "✅ Already Completed", callback_data: "none" }]] }, { chat_id: chatId, message_id: messageId });
          return;
        }

        // --- Execute manual approval ---
        let meta = {};
        try { meta = JSON.parse(payment.username); } catch(e) {}
        
        const amt = parseFloat(payment.amount);
        const isApiPayment = meta.purpose === 'api' || meta.type === 'topup' || meta.type === 'buy_new';

        if (isApiPayment) {
          // Helper function for full https fetch
          const API_BASE_URL = "https://za-tool-kh.com/api/";
          const ADMIN_SECRET = "Admin1688";

          function fetchHttps(url) {
            return new Promise((resolve, reject) => {
              require("https").get(url, { timeout: 8000 }, (res) => {
                let d = ""; res.on("data", c => d += c);
                res.on("end", () => { try { resolve(JSON.parse(d)); } catch { resolve(d); } });
              }).on("error", reject).on("timeout", reject);
            });
          }

          // It's an API Top Up / Buy New
          if (meta.type === 'topup') {
            const balRes = await fetchHttps(`${API_BASE_URL}?action=balance&api_key=${encodeURIComponent(meta.api_key)}&_t=${Date.now()}`).catch(()=>null);
            if (!balRes || balRes.status !== "success" || balRes.balance === undefined) {
              telegramBot.answerCallbackQuery(query.id, { text: "❌ Failed to fetch current balance. Cannot top up.", show_alert: true });
              return;
            }
            const updateRes = await fetchHttps(`${API_BASE_URL}?action=admin_topup_user&admin_key=${ADMIN_SECRET}&user_key=${encodeURIComponent(meta.api_key)}&amount=${amt}&_t=${Date.now()}`).catch(()=>null);
            
            if (updateRes && updateRes.status === "success") {
              await dbQuery("UPDATE payments SET status = 'completed', paidAt = ? WHERE id = ?", [new Date(), md5]);
              await insert(`INSERT INTO user_api_keys (userId, api_key, type, amount_paid, credit, note) VALUES (?, ?, 'topup', ?, ?, 'Manual Approved Top Up')`, [payment.userId, meta.api_key, amt, amt]);
            } else {
              telegramBot.answerCallbackQuery(query.id, { text: "❌ Failed to update balance in external API.", show_alert: true });
              return;
            }
          } else {
            const crypto = require("crypto");
            const newKey = "ZA-" + crypto.randomBytes(10).toString("hex").toUpperCase();
            const createData = await fetchHttps(`${API_BASE_URL}?action=admin_add_user&admin_key=${ADMIN_SECRET}&new_user_key=${encodeURIComponent(newKey)}&amount=${amt}&_t=${Date.now()}`).catch(()=>null);
            
            if (createData && createData.status === "success") {
              await dbQuery("UPDATE payments SET status = 'completed', paidAt = ?, new_key = ? WHERE id = ?", [new Date(), newKey, md5]);
              await insert(`INSERT INTO user_api_keys (userId, api_key, type, amount_paid, credit, note) VALUES (?, ?, 'buy_new', ?, ?, 'Manual Approved New Key')`, [payment.userId, newKey, amt, amt]);
            } else {
              telegramBot.answerCallbackQuery(query.id, { text: "❌ Failed to create new API key.", show_alert: true });
              return;
            }
          }
        } else {
          // Regular Account Balance Top Up
          await dbQuery("UPDATE payments SET status = 'completed', paidAt = ? WHERE id = ?", [new Date(), md5]);
          await dbQuery("UPDATE users SET balance = balance + ? WHERE id = ?", [amt, payment.userId]);
        }

        telegramBot.answerCallbackQuery(query.id, { text: "✅ Payment Approved!", show_alert: true });
        telegramBot.editMessageReplyMarkup({ inline_keyboard: [[{ text: "✅ Approved by Admin", callback_data: "none" }]] }, { chat_id: chatId, message_id: messageId });
        telegramBot.sendMessage(chatId, `✅ *Payment ${md5}* has been manually approved!`, { parse_mode: "Markdown" });
        
      } catch (err) {
        console.error("Manual approve error:", err);
        telegramBot.answerCallbackQuery(query.id, { text: "❌ Error: " + err.message, show_alert: true });
      }
    } else if (query.data.startsWith('reject_')) {
      const md5 = query.data.replace('reject_', '');
      try {
        const { query: dbQuery, queryOne } = require("./db");
        const payment = await queryOne("SELECT * FROM payments WHERE id = ?", [md5]);
        if (!payment) return telegramBot.answerCallbackQuery(query.id, { text: "❌ Payment not found", show_alert: true });
        
        if (payment.status === 'completed') {
          return telegramBot.answerCallbackQuery(query.id, { text: "❌ Cannot reject, already completed!", show_alert: true });
        }
        
        await dbQuery("UPDATE payments SET status = 'rejected' WHERE id = ?", [md5]);
        telegramBot.answerCallbackQuery(query.id, { text: "❌ Payment Rejected!", show_alert: true });
        telegramBot.editMessageReplyMarkup({ inline_keyboard: [[{ text: "❌ Rejected by Admin", callback_data: "none" }]] }, { chat_id: chatId, message_id: messageId });
      } catch (err) {
        telegramBot.answerCallbackQuery(query.id, { text: "❌ Error: " + err.message, show_alert: true });
      }
    }
  });

} else {
  console.log("⚠️  Telegram bot disabled (no token in .env)");
}

// ═══════════════════════════════════════════════════════════
// Notification Functions
// ═══════════════════════════════════════════════════════════

function notifyNewOrder(order) {
  if (!bot.isActive || !ADMIN_CHAT_ID) return;
  const text = `🛒 *New Order!*\n\n👤 User: ${order.username}\n📦 Service: ${order.service}\n🔢 Qty: ${order.qty}\n💰 Total: $${order.total.toFixed(3)}\n⏰ ${order.createdAt}`;
  bot.sendMessage(ADMIN_CHAT_ID, text, { parse_mode: "Markdown" }).catch(() => {});
}

function notifyNewUser(user) {
  if (!bot.isActive || !ADMIN_CHAT_ID) return;
  const text = `👤 *New User Registered!*\n\n🏷️ Username: \`${user.username}\`\n📧 Email: \`${user.email}\`\n📱 Telegram: ${user.telegram || "N/A"}\n🔑 API Key: \`${user.apiKey}\`\n⏰ ${user.createdAt || new Date().toISOString()}`;
  bot.sendMessage(ADMIN_CHAT_ID, text, { parse_mode: "Markdown" }).catch(() => {});
}

function notifyPasswordReset(user, resetToken) {
  if (!bot.isActive || !ADMIN_CHAT_ID) return;
  const baseUrl = process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',')[0] : 'https://za-tool-kh.com';
  const text = `🔑 *Password Reset Request*\n\n📧 Email: ${user.email}\n🏷️ Username: ${user.username}\n🔗 Link: [Reset Password](${baseUrl}/reset?token=${resetToken})\n\n_Link expires in 15 minutes_`;
  bot.sendMessage(ADMIN_CHAT_ID, text, { parse_mode: "Markdown" }).catch(() => {});
}

function notifyPaymentCompleted(payment, user) {
  if (!bot.isActive || !ADMIN_CHAT_ID) return;
  const text = `💳 *Payment Completed!*\n\n👤 User: \`${user.username}\`\n💵 Amount: $${payment.amount.toFixed(2)}\n💰 New Balance: $${(user.balance || 0).toFixed(3)}\n🆔 MD5: \`${payment.id}\``;
  bot.sendMessage(ADMIN_CHAT_ID, text, { parse_mode: "Markdown" }).catch(() => {});
}

function notifyPaymentStarted(payment, user) {
  if (!bot.isActive || !ADMIN_CHAT_ID) return;
  
  let typeStr = "Account Balance Top Up";
  let extraInfo = "";
  let meta = {};
  
  try {
    if (payment.username && payment.username.startsWith('{')) {
      meta = JSON.parse(payment.username);
    }
  } catch (e) {}

  if (meta.purpose === "api") {
    const isNew = meta.type === "buy_new";
    typeStr = isNew ? "Buy New Outlook API Key" : "Top Up Outlook API Key";
    const accounts = Math.floor(parseFloat(payment.amount) / 0.012);
    extraInfo = `\n📦 Accounts: ~${accounts.toLocaleString()} Outlooks\n🔑 Target Key: \`${meta.api_key || "NEW KEY"}\``;
  }
  
  const text = `⏳ *New Payment Initiated!*\n\n👤 User: \`${user.username}\`\n📧 Email: \`${user.email}\`\n💵 Amount: $${parseFloat(payment.amount).toFixed(2)}\n🏷️ Type: ${typeStr}${extraInfo}\n🆔 MD5: \`${payment.id}\`\n\n_If auto-check fails, you can approve manually below:_`;
  
  const options = {
    parse_mode: "Markdown",
    reply_markup: JSON.stringify({
      inline_keyboard: [
        [{ text: "✅ Approve Payment", callback_data: "approve_" + payment.id }]
      ]
    })
  };
  
  bot.sendMessage(ADMIN_CHAT_ID, text, options).catch(() => {});
}

function notifyPaymentTailNumber(payment, user, tailNumber) {
  if (!bot.isActive || !ADMIN_CHAT_ID) return;
  
  let typeStr = "Account Balance Top Up";
  let extraInfo = "";
  let meta = {};
  
  try {
    if (payment.username && payment.username.startsWith('{')) {
      meta = JSON.parse(payment.username);
    }
  } catch (e) {}

  if (meta.purpose === "api") {
    const isNew = meta.type === "buy_new";
    typeStr = isNew ? "Buy New Outlook API Key" : "Top Up Outlook API Key";
    const accounts = Math.floor(parseFloat(payment.amount) / 0.012);
    extraInfo = `\n📦 Accounts: ~${accounts.toLocaleString()} Outlooks\n🔑 Target Key: \`${meta.api_key || "NEW KEY"}\``;
  }
  
  const text = `📝 *Transaction Tail Submitted!*\n\n👤 User: \`${user.username}\`\n📧 Email: \`${user.email}\`\n💵 Amount: $${parseFloat(payment.amount).toFixed(2)}\n🏷️ Type: ${typeStr}${extraInfo}\n🔢 Tail: *${tailNumber}*\n🆔 MD5: \`${payment.id}\`\n\n_If you see a $${parseFloat(payment.amount).toFixed(2)} payment ending in ${tailNumber}, approve it below:_`;
  
  const options = {
    parse_mode: "Markdown",
    reply_markup: JSON.stringify({
      inline_keyboard: [
        [{ text: "✅ Approve Payment", callback_data: "approve_" + payment.id }],
        [{ text: "❌ Reject", callback_data: "reject_" + payment.id }]
      ]
    })
  };
  
  bot.sendMessage(ADMIN_CHAT_ID, text, options).catch(() => {});
}

function notifySecurityAlert(type, details) {
  if (!bot.isActive || !ADMIN_CHAT_ID) return;
  const text = `🚨 *Security Alert!*\n\n⚠️ Type: ${type}\n📋 Details: ${details}\n⏰ ${new Date().toISOString()}`;
  bot.sendMessage(ADMIN_CHAT_ID, text, { parse_mode: "Markdown" }).catch(() => {});
}

function notifyLicensePurchase(info) {
  if (!bot.isActive || !ADMIN_CHAT_ID) return;
  const text = `🔑 *License Key Purchased!*\n\n👤 User: \`${info.username}\`\n📦 Package: ${info.packageName}\n💵 Price: $${info.price}\n🔑 Key: \`${info.licenseKey}\`\n📅 Expiry: ${info.expiryDate}`;
  bot.sendMessage(ADMIN_CHAT_ID, text, { parse_mode: "Markdown" }).catch(() => {});
}

module.exports = { isActive: bot.isActive, notifyNewOrder, notifyNewUser, notifyPasswordReset, notifyPaymentCompleted, notifyPaymentStarted, notifyPaymentTailNumber, notifySecurityAlert, notifyLicensePurchase };
