var token = '<TRUFFLEHOG_REDACTED_TELEGRAMBOTTOKEN>';
var id_sheet = '1ZlZs0641sNQ7i_EJXhHnUjcEGMLRdyfdluR-oNFjhXQ';
var saldo;
var adminId = 6487972153;

function setWebhook() {
  let drive = DriveApp.getRootFolder();
  
  let Bot = new TelegramBot();
  let result = Bot.request('setWebhook', {
    url: 'https://script.google.com/macros/s/AKfycbxsopnE9k4qOfiV51KaBoWwlZs93mrFTR0blCo09u4yg8OERLyZm8ZYQobSPfMSJ4irhg/exec'
  });
  Logger.log(result);
}


/////////////////////////////////////////////////////


var TelegramData;

function doPost(e) {
  if (e.postData.type == "application/json") {
    TelegramData = JSON.parse(e.postData.contents);
    let Bot = new TelegramBot();
    let Request = new RequestType();

    if (Request.botCommand()) {
      Bot.setType('bot_command');
      new BotCommand(Bot);
    }

    else if (Request.callbackInlineKeyboard()) {
      Bot.setType('callback_query');
      let message = TelegramData.callback_query.message.text;

      // RISPOSTA “InlineKeyboard”
      if (message == new InlineKeyboard().getQuestion()) {
        new InlineKeyboard().getAnswer(Bot);
      }

    }

    else {
      Bot.setType('text');
      let text = `Ciao ` + TelegramData.message.from.first_name + '!';
      if (Request.textAvailable())
        text += '\nIl messaggio : ' + TelegramData.message.text;
      text += `\nNon restituisce nulla, prova con /start .`
      Bot.sendMessage(text);

      /*
      let bot = new TelegramBot();
      let chatIdOrigine = TelegramData.message.chat.id; // L’ID dell’utente che ha inviato il messaggio al bot
      let messageId = TelegramData.message.message_id; // L’ID del messaggio da inoltrare

      bot.forwardMessage(625347711, chatIdOrigine, messageId);
      //bot.forwardMessage(6249434875, chatIdOrigine, messageId);
      */
    }

  }
}


/////////////////////////////////////////////////////


class InlineKeyboard {

  getKeyboard(type) {
    let keyboard = {

      'StartKeyboard': [
        [
          { 'text': '💳 Saldo 💳', 'callback_data': 'saldo' },
          { 'text': '🛍 Shop 🛍', 'callback_data': 'shop' }
        ],
        [
          { 'text': '✅ Feedback ✅', 'url': 't.me/PrimeShopBotFeeds' },
          { 'text': '📑 T.O.S 📑', 'url': 't.me/TosByPrimeShopBot' }
        ],
        [
          { 'text': '📣 Canale 📣', 'url': 't.me/ChannelOfPrimeShopBot' },
          { 'text': '☎️ Assistenza ☎️', 'url': 't.me/AssistenzaPrimeShopBot' }
        ]
      ],
      
      'ShopKeyboard': [
        [ 
          { 'text': '🤖 Telegram Bot 🤖', 'callback_data': 'bot' }
        ],
        /*[
          { 'text': '💻 Pacchetti Hacker 💻', 'callback_data': 'pacchetti_hacker' },
          { 'text': '📄 Metodi 📄', 'callback_data': 'metodi' },
        ],
        [
          { 'text': '🤖 Bot 🤖', 'callback_data': 'bot' },
          { 'text': '🌐 Sito Web 🌐', 'callback_data': 'sito_web' },
        ],*/
        [
          { 'text': '↩️ Indietro ↩️', 'callback_data': 'indietro_a_start' }
        ]
      ],
      
      'BotKeyboard': [
        [
          { 'text': 'Limitati Bot', 'callback_data': 'limitatiBot' }
        ],
        [
          { 'text': '↩️ Indietro ↩️', 'callback_data': 'indietro_a_start' }
        ]
      ],
      
      'LimitatiBotKeyboard': [
        [
          { 'text': 'Conferma acquisto', 'callback_data': 'conferma_limitatiBot' }
        ],
        [
          { 'text': '↩️ Indietro ↩️', 'callback_data': 'indietro_a_start' }
        ]
      ],
      
      'SaldoKeyboard': [
        [
          { 'text': '➕ Ricarica con PayPal ➕', 'callback_data': 'paypal' }
        ],
        [
          { 'text': '↩️ Indietro ↩️', 'callback_data': 'indietro_a_start' }
        ]
      ]

    };
    return keyboard[type];
  }

  getAnswer(Bot) {

    if (TelegramData.callback_query.data == 'shop'){
      Bot.editInlineKeyboard(this.getKeyboard('ShopKeyboard'));
    }

    else if (TelegramData.callback_query.data == 'bot'){
      Bot.editInlineKeyboard(this.getKeyboard('BotKeyboard'));
    }

    else if (TelegramData.callback_query.data == 'limitatiBot'){
      Bot.editInlineKeyboard(this.getKeyboard('LimitatiBotKeyboard'));

      var text = `
      <b>Limitati bot</b>\n\n<i>Prezzo: 0,50€\n\nHosting: 0,50€ al mese</i>
      `;
      
      let tempMessage = Bot.sendMessage(text, 'HTML');
      let tempMessageId = tempMessage.result.message_id;
      Bot.sendMessage(tempMessageId, 'HTML');

      let chatId = TelegramData.message.chat.id; // non funziona
      Bot.sendMessage(chatId, 'HTML');

      Utilities.sleep(5000);

      Bot.request('deleteMessage', {
        'chat_id': chatId,
        'message_id': tempMessageId
      });
    }
    else if (TelegramData.callback_query.data == 'conferma_limitatiBot'){
      Bot.editInlineKeyboard(this.getKeyboard('StartKeyboard'));

      var text = `
      <b>confermato</b>
      `;
      Bot.sendMessage(text, 'HTML');
    }

    else if(TelegramData.callback_query.data == 'indietro_a_start'){
      Bot.editInlineKeyboard(this.getKeyboard('StartKeyboard'));
    }

    else if(TelegramData.callback_query.data == 'saldo'){
      Bot.editInlineKeyboard(this.getKeyboard('SaldoKeyboard'));
    }
    else if(TelegramData.callback_query.data == 'paypal'){
      var text = `
      <b>Ricarica con PayPal</b>\n\nInvia il denaro su questo <a href="https://www.paypal.me/JMstudio05">link</a>\n\n<i>Nel messaggio scrivi la tua @ senza nessun errore così ti verrà ricaricato il saldo, i soldi si devono inviare come amici e familiari.\n\nNell'arco di 10 ore la transazione verrà confermata e il saldo aggiornato.</i>
      `;
      Bot.sendMessage(text, 'HTML');
    }

    else {
      Bot.editInlineKeyboard();
    }

  }

  getQuestion() {
    return ("Seleziona un pulsante dalla tastiera...");
  }

}


/////////////////////////////////////////////////////


class BotCommand {

  // 🤪🤩👋👍💾💰☎️⏳🛠⚙️🎁🛍📄📦🗂📍🔐⬅️⤵️↩️❌💯♨️✅⚠️💻📽🎞📱📞🕹🔗✏️🤖🌐

  constructor(bot) {
    this.bot = bot;
    this.text = TelegramData.message.text.split(' ');
    let botCommand = this.text[0].substring(1); // botCommand = first element of text without '/' 
    if (typeof this[botCommand] === "function")
      this[botCommand]();
    else
      this.bot.sendMessage("Comando non valido");
  }

  start(){
    /*
    let messageId = TelegramData.message.message_id;
    let chatId = TelegramData.message.chat.id;
    this.bot.request('deleteMessage', {
        'chat_id': chatId,
        'message_id': messageId
    });
    */

    var user_id = TelegramData.message.from.id;
    var user_nome = TelegramData.message.from.first_name;

    if (!isUserInSheet(TelegramData.message.from.id)) {
      addUserToSheet(TelegramData.message.from.id);
    }

    var text = 
    '<b><a href="https://telegra.ph/file/449aeaf060a6d132f4c3c.png">👉🏻</a> Benvenuto <a href="tg://user?id=' + user_id + '">' + user_nome +
    '</a></b><i> [' + user_id + ']</i><b> nel bot di 𝓟𝓻𝓲𝓶𝓮 𝓢𝓱𝓸𝓹𝓑𝓸𝓽 🔝\n\n' +
    '<i>🛍 Qui potrai Acquistare prodotti tramite apposite categorie.</i></b>\n\n' +
    '💸 Saldo: ' + saldo + '€\n\n' +
    '©️ Bot sviluppato da <a href="tg://user?id=' + adminId + '">𝓟𝓻𝓲𝓶𝓮 𝓢𝓱𝓸𝓹𝓑𝓸𝓽</a>';

    this.bot.sendMessage(text, 'HTML');

    /*
    var lastMessageId = this.bot.lastMessageId;
    this.bot.sendMessage(lastMessageId, 'HTML');
    */

    let Start = new InlineKeyboard()
    this.bot.sendMessageInlineKeyboard(Start.getQuestion(), Start.getKeyboard('StartKeyboard'));
  }

  admin(){
    if(TelegramData.message.from.id == adminId){
      this.bot.sendMessage(
        "<b>Sezione ADMIN</b>\n\nAggiorna il saldo <a href=''>qui</a>" , "HTML"
      );
    }
    else{
      this.bot.sendMessage(
        "<b>Mi dispiace, non sei autorizzato ad usare questo comando</b>" , "HTML"
      );
    }
  }

}


/////////////////////////////////////////////////////


// Aggiungi la funzione per verificare se l'ID dell'utente è presente nel foglio di Google Sheets
function isUserInSheet(userId) {
  let sheet = SpreadsheetApp.openById(id_sheet);
  let data = sheet.getSheetByName('utenti').getRange('A:A').getValues();
  let count = 1;
  for (let row of data) {
    if (row[0] == userId) {
      saldo = sheet.getSheetByName('utenti').getRange('F'+count).getValues();
      return true;
    }
    count += 1;
  }
  return false;
}

// Aggiungi la funzione per aggiungere l'ID dell'utente in coda nella colonna A
function addUserToSheet(userId) {
  let currentTime = new Date();
  let sheet = SpreadsheetApp.openById(id_sheet);
  let lastRow = sheet.getLastRow();

  sheet.getSheetByName('utenti').getRange('A' + (lastRow + 1)).setValue(userId);
  sheet.getSheetByName('utenti').getRange('B' + (lastRow + 1)).setValue(currentTime);
  sheet.getSheetByName('utenti').getRange('C' + (lastRow + 1)).setValue(TelegramData.message.from.username);
  sheet.getSheetByName('utenti').getRange('D' + (lastRow + 1)).setValue(TelegramData.message.from.first_name);
  sheet.getSheetByName('utenti').getRange('E' + (lastRow + 1)).setValue(TelegramData.message.from.last_name);
  sheet.getSheetByName('utenti').getRange('F' + (lastRow + 1)).setValue(0); // SALDO
  
  saldo = 0;
}


/////////////////////////////////////////////////////


class TelegramBot {
  constructor() {
    this.lastMessageId = null;
  }
  setType(type) {
    this.botType = type;
    this.chat_id = type == 'callback_query' ?
      TelegramData.callback_query.from.id :
      TelegramData.message.from.id;
  }
  request(method, data) {
    let options = {
      'method': 'post',
      'contentType': 'application/json',
      'payload': JSON.stringify(data)
    };
    let response = UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/' + method, options);
    if (response.getResponseCode() == 200) {
      return JSON.parse(response.getContentText());
    }
    return false;
  }
  sendMessage(text, mode) {
    mode = mode || 'None';
    let response = this.request('sendMessage', {
      'chat_id': this.chat_id,
      'text': text,
      'parse_mode': mode
    });
    if (response && response.ok) {
      this.lastMessageId = response.result.message_id;
    }
    return response;
  }
  forwardMessage(chatId, fromChatId, messageId) {
    return this.request('forwardMessage', {
      'chat_id': chatId,
      'from_chat_id': fromChatId,
      'message_id': messageId
    });
  }
  sendMessageKeyboard(text, keyboard, mode) {
    mode = mode || 'None';
    keyboard = keyboard ?
      { 'keyboard': keyboard } :
      { 'remove_keyboard': true };
    return this.request('sendMessage', {
      'chat_id': this.chat_id,
      'text': text,
      'parse_mode': mode,
      'reply_markup': JSON.stringify(keyboard)
    });
  }
  sendMessageInlineKeyboard(text, keyboard, mode) {
    keyboard = keyboard || [];
    mode = mode || 'None';
    return this.request('sendMessage', {
      'chat_id': this.chat_id,
      'text': text,
      'parse_mode': mode,
      'reply_markup': JSON.stringify({ 'inline_keyboard': keyboard })
    });
  }
  editInlineKeyboard(keyboard) {
    if (this.botType != 'callback_query') return false;
    keyboard = keyboard || [];
    return this.request('editMessageReplyMarkup', {
      'chat_id': this.chat_id,
      'message_id': TelegramData.callback_query.message.message_id,
      'reply_markup': JSON.stringify({ 'inline_keyboard': keyboard })
    });
  }

}

class RequestType {
  botCommand() {
    try {
      return (
        TelegramData.message.entities[0].type == 'bot_command' &&
        TelegramData.message.text.charAt(0) == '/'
      ) ? true : false;
    }
    catch (e) {
      return false;
    }
  }
  callbackInlineKeyboard() {
    try {
      return typeof TelegramData.callback_query.message.reply_markup.inline_keyboard != 'undefined';
    }
    catch (e) {
      return false;
    }
  }
  textAvailable() {
    try {
      return typeof TelegramData.message.text != 'undefined';
    }
    catch (e) {
      return false;
    }
  }
}