const axios = require('axios');
const { ActionRowBuilder, ButtonBuilder, StringSelectMenuBuilder } = require('discord.js');

module.exports = {
  interaction: {
    name: "ayarlar",
    description: "Sunucunun Nraphy ayarlarÄ±nÄ± gÃ¶sterir.",
    options: []
  },
  interactionOnly: true,
  aliases: ["settings"],
  category: "Moderation",
  memberPermissions: ["ManageChannels"],
  botPermissions: ["SendMessages", "EmbedLinks", "ManageChannels", "ManageWebhooks"],
  nsfw: false,
  cooldown: 10000,
  ownerOnly: false,

  async execute(client, interaction, data) {

    await interaction.deferReply();

    const autoReply = data.guild.autoReply;
    const autoRole = data.guild.autoRole;
    const inviteManager = data.guild.inviteManager;
    const linkBlock = data.guild.linkBlock;
    const memberCounter = data.guild.memberCounter;
    const prefix = data.guild.prefix || client.settings.prefix;
    const spamProtection = data.guild.spamProtection;
    const upperCaseBlock = data.guild.upperCaseBlock;
    const wordGame = data.guild.wordGame;

    //------------------------------HATA TESPÄ°T------------------------------//

    var caughtProblems = [];

    //ButtonRole
    let amountOfButtonsWithError = 0;
    for await (let [messageId, buttonRoleData] of Object.entries(data.guild.buttonRole || {})) {
      //messageId => "1073286862325686322"
      //buttonRoleData => { channelId: "1073286862325686322", title: null... }
      if (!buttonRoleData.channelId || !interaction.guild.channels.cache.get(buttonRoleData.channelId)) {
        delete data.guild.buttonRole[messageId];
        amountOfButtonsWithError++;
      }
    }
    if (amountOfButtonsWithError) {
      data.guild.markModified('buttonRole');
      await data.guild.save();
      caughtProblems.push(`Sorunlu ${amountOfButtonsWithError} adet buton rol mesajÄ± tespit edildi ve veri tabanÄ±ndan silindi. Merak etme, aktif olarak kullanÄ±lan buton rollerde bir problem olmayacak.`);
    }

    //Kelime Oyunu
    if (wordGame.channel && !interaction.guild.channels.cache.get(wordGame.channel)) {
      data.guild.wordGame.channel = undefined;
      await data.guild.save();
      caughtProblems.push("Kelime oyunu kanalÄ± bulunamadÄ±. Kelime oyunu kapatÄ±ldÄ±. (Ä°statistikler korunuyor)");
    }

    //Logger
    var logger = data.guild.logger, loggerChannel;
    if (logger?.webhook) {
      await axios
        .get(logger.webhook)
        .then(res => { loggerChannel = res.data.channel_id; })
        .catch(async () => {
          data.guild.logger.webhook = undefined;
          await data.guild.save();
          caughtProblems.push("Log sistemi Webhook'u bulunamadÄ±. Log sistemi kapatÄ±ldÄ±.");
        });
    }

    //Warns
    let warns_users = 0, warns_warns = 0;
    if (Object.keys(data.guild.warns || {}).length)
      for await (let warnDataId of Object.keys(data.guild.warns || {})) {
        warns_users++;

        let warnData = data.guild.warns[warnDataId];
        if (warnData.length) warns_warns += warnData.length;
      }

    //"Bir takÄ±m problemlerle karÅŸÄ±laÅŸÄ±ldÄ±" uyarÄ±sÄ±
    if (caughtProblems.length)
      return interaction.editReply({
        embeds: [
          {
            color: client.settings.embedColors.yellow,
            title: "**Â»** Bir TakÄ±m Problemlerle KarÅŸÄ±laÅŸÄ±ldÄ±!",
            description:
              `**â€¢** \`${caughtProblems.join('`\n**â€¢** `')}\`\n\n` +

              `**â€¢** AyarlarÄ± gÃ¶rmek iÃ§in lÃ¼tfen komutu tekrar kullanÄ±n.\n` +
              `**â€¢** Bir sorun olduÄŸunu dÃ¼ÅŸÃ¼nÃ¼yorsanÄ±z [destek sunucumuza](https://discord.gg/QvaDHvuYVm) gelebilirsiniz.`
          }
        ],
        components: [
          {
            type: 1, components: [
              new ButtonBuilder().setLabel('Destek Sunucusu').setURL("https://discord.gg/VppTU9h").setStyle('Link')
            ]
          },
        ]
      });

    //------------------------------HATA TESPÄ°T------------------------------//

    let moderationPageEmbed = {
      color: client.settings.embedColors.default,
      author: {
        name: `${interaction.guild.name} Sunucusunun AyarlarÄ± (Moderasyon)`,
        icon_url: interaction.guild.iconURL(),
      },
      title: `**Â»** Prefix: \`${prefix !== client.settings.prefix ? prefix : `${client.settings.prefix} (VarsayÄ±lan)`}\``,
      fields: [
        {
          name: '**Â»** Davet Sistemi',
          value: `**â€¢** ${inviteManager.channel ? `Kanal: ${interaction.guild.channels.cache.get(inviteManager.channel)}` : `\`KapalÄ±\``}`,
        },
        {
          name: '**Â»** Oto-Cevap',
          value: `**â€¢** ${autoReply ? `\`AÃ§Ä±k\`` : `\`KapalÄ±\``}`,
        },
        {
          name: '**Â»** Oto-Rol',
          value: `**â€¢** ${autoRole.role ? `Rol: ${interaction.guild.roles.cache.get(autoRole.role)}\n**â€¢** Kanal: ${autoRole.channel ? interaction.guild.channels.cache.get(autoRole.channel) : `\`AyarlÄ± DeÄŸil\``}` : `\`KapalÄ±\``}`,
        },
        {
          name: '**Â»** SayaÃ§',
          value: `**â€¢** ${memberCounter.channel ? `Kanal: ${interaction.guild.channels.cache.get(memberCounter.channel)}\n**â€¢** Hedef: \`${memberCounter.target}\`` : `\`KapalÄ±\``}`,
        },
        {
          name: '**Â»** Log Sistemi',
          value:
            (loggerChannel ?
              `**â€¢** Kanal: ${interaction.guild.channels.cache.get(loggerChannel)}\n` +
              `**â€¢** AkÄ±llÄ± Filtreler: \`${logger.smartFilters ? "AÃ§Ä±k" : "KapalÄ± (/log akÄ±llÄ±-filtreler aÃ§)"}\``
              : `**â€¢** \`KapalÄ±\``) +
            `**â€¢** Log sisteminin nihai sÃ¼rÃ¼mÃ¼ yalnÄ±zca ResmÃ® Nraphy botunda mevcuttur.`,
        },
        {
          name: '**Â»** Bilgi âš ï¸�',
          value:
            `**â€¢** Bu bot Nraphy aÃ§Ä±k kaynak altyapÄ±sÄ± kullanÄ±larak oluÅŸturulmuÅŸtur.\n` +
            `**â€¢** AÃ§Ä±k kaynak altyapÄ±sÄ±nda aÅŸaÄŸÄ±daki sistemler mevcut deÄŸildir.\n` +
            `**â€¢** Bu sistemler ve daha fazlasÄ± ResmÃ® Nraphy botunda mevcuttur.\n` +
            `**â€¢** [Nraphy'i sunucuna eklemek iÃ§in buraya tÄ±kla!](https://top.gg/bot/700959962452459550/)\n\n` +

            `**â€¢** Ä°sim Temizleme Sistemi\n` +
            `**â€¢** Kampanya Haber\n` +
            `**â€¢** Galeri Sistemi\n` +
            `**â€¢** UyarÄ± Sistemi\n` +
            `**â€¢** ve daha fazlasÄ±...`,
        },
      ],
    };

    //Row
    const row = new ActionRowBuilder()
      .addComponents(
        new StringSelectMenuBuilder()
          .setCustomId('select')
          .setPlaceholder('Buradan kategori seÃ§ebilirsin')
          .addOptions([
            {
              label: 'DiÄŸer Moderasyon',
              value: 'moderationPageOption',
              description: 'Davet Sistemi, Oto-Cevap, Oto-Rol, SayaÃ§, Kampanya Haber, Log, Galeri, UyarÄ±lar, Ä°sim Temizleme',
              emoji: 'ðŸ“˜'
            },
            {
              label: 'BaÄŸlantÄ± Engel',
              value: 'linkBlockPageOption',
              //description: '',
              emoji: 'ðŸ“˜'
            },
            {
              label: 'BÃ¼yÃ¼k Harf Engel',
              value: 'upperCaseBlockPageOption',
              //description: '',
              emoji: 'ðŸ“˜'
            },
            {
              label: 'Spam KorumasÄ±',
              value: 'spamProtectionPageOption',
              //description: '',
              emoji: 'ðŸ“˜'
            },
            {
              label: 'Buton Rol (BakÄ±mda)',
              value: 'buttonRolePageOption',
              //description: '',
              emoji: 'ðŸ“˜'
            },
            {
              label: 'Ã‡ekiliÅŸler',
              value: 'giveawaysPageOption',
              //description: '',
              emoji: 'ðŸŽ‰'
            },
            {
              label: 'Oyunlar SayfasÄ±',
              value: 'gamesPageOption',
              description: 'Kelime Oyunu, SayÄ± Saymaca ve Tuttu TutmadÄ±',
              emoji: 'ðŸ“•'
            },
          ])
      );

    await interaction.editReply({
      embeds: [moderationPageEmbed],
      components: [row]
    });

    const reply = await interaction.fetchReply();
    const filter = i => {
      return i.message.id === reply.id && i.deferUpdate() && i.user.id === interaction.user.id;
    };

    const collector = reply.createMessageComponentCollector({ filter, time: 600000 });

    collector.on('collect', async int => {

      let collectedOption = row.components[0].options.find(selectMenuOption => selectMenuOption.data.value == int.values.toString());
      row.components[0].setPlaceholder(`${collectedOption.data.emoji.name} ${collectedOption.data.label}`);

      if (int.values.toString() === "moderationPageOption") {

        interaction.editReply({
          embeds: [moderationPageEmbed],
          components: [row]
        });

      } else if (int.values.toString() === "linkBlockPageOption") {

        interaction.editReply({
          embeds: [
            {
              color: client.settings.embedColors.default,
              author: {
                name: `${interaction.guild.name} Sunucusunun AyarlarÄ± (BaÄŸlantÄ± Engel)`,
                icon_url: interaction.guild.iconURL(),
              },
              title: `**Â»** ${linkBlock?.guild ? "AÃ§Ä±k!" : "KapalÄ±"}`,
              fields: [
                {
                  name: '**Â»** Muaflar',
                  value:
                    `**â€¢** Kanallar: ${linkBlock?.exempts?.channels?.length > 0
                      ? linkBlock.exempts.channels.map(channel => interaction.guild.channels.cache.get(channel)).join(`, `)
                      : `\`Muaf kanal yok\``}\n` +
                    `**â€¢** Roller: ${linkBlock?.exempts?.roles?.length > 0
                      ? linkBlock.exempts.roles.map(role => interaction.guild.roles.cache.get(role)).join(`, `)
                      : `\`Muaf rol yok\``}\n` +
                    `**â€¢** BaÄŸlantÄ±lar: \`GIPHY, Tenor, GIBIRNet\` (DÃ¼zenleme ÅŸimdilik mevcut deÄŸil)\n` +
                    `**â€¢** Ek: \`"MesajlarÄ± YÃ¶net" yetkisine sahip Ã¼yeler\``
                },
              ],
            }
          ],
          components: [row]
        });

      } else if (int.values.toString() === "upperCaseBlockPageOption") {

        interaction.editReply({
          embeds: [
            {
              color: client.settings.embedColors.default,
              author: {
                name: `${interaction.guild.name} Sunucusunun AyarlarÄ± (BÃ¼yÃ¼k Harf Engel)`,
                icon_url: interaction.guild.iconURL(),
              },
              title: `**Â»** ${upperCaseBlock?.guild ? "AÃ§Ä±k!" : "KapalÄ±"}`,
              fields: [
                {
                  name: '**Â»** BÃ¼yÃ¼k Harf OranÄ±',
                  value: `**â€¢** ${upperCaseBlock.rate ? `\`%${upperCaseBlock.rate}\`` : `\`VarsayÄ±lan (%70)\``}`
                },
                {
                  name: '**Â»** Muaflar',
                  value:
                    `**â€¢** Kanallar: ${upperCaseBlock?.exempts?.channels?.length > 0
                      ? upperCaseBlock.exempts.channels.map(channel => interaction.guild.channels.cache.get(channel)).join(`, `)
                      : `\`Muaf kanal yok\``}\n` +
                    `**â€¢** Roller: ${upperCaseBlock?.exempts?.roles?.length > 0
                      ? upperCaseBlock.exempts.roles.map(role => interaction.guild.roles.cache.get(role)).join(`, `)
                      : `\`Muaf rol yok\``}\n` +
                    `**â€¢** Ek: \`"MesajlarÄ± YÃ¶net" yetkisine sahip Ã¼yeler\``
                },
              ],
            }
          ],
          components: [row]
        });

      } else if (int.values.toString() === "spamProtectionPageOption") {

        interaction.editReply({
          embeds: [
            {
              color: client.settings.embedColors.default,
              author: {
                name: `${interaction.guild.name} Sunucusunun AyarlarÄ± (Spam KorumasÄ±)`,
                icon_url: interaction.guild.iconURL(),
              },
              title: `**Â»** ${spamProtection.guild ? "AÃ§Ä±k!" : "KapalÄ±"}`,
              fields: [
                {
                  name: '**Â»** Muaflar',
                  value:
                    `**â€¢** Kanallar: ${spamProtection?.exempts?.channels?.length > 0
                      ? spamProtection.exempts.channels.map(channel => interaction.guild.channels.cache.get(channel)).join(`, `)
                      : `\`Muaf kanal yok\``}\n` +
                    `**â€¢** Roller: ${spamProtection?.exempts?.roles?.length > 0
                      ? spamProtection.exempts.roles.map(role => interaction.guild.roles.cache.get(role)).join(`, `)
                      : `\`Muaf rol yok\``}\n` +
                    `**â€¢** Ek: \`"MesajlarÄ± YÃ¶net" yetkisine sahip Ã¼yeler\`, \`Nraphy'nin zaman aÅŸÄ±mÄ± veremeyeceÄŸi Ã¼yeler\``
                },
              ],
            }
          ],
          components: [row]
        });

      } else if (int.values.toString() === "buttonRolePageOption") {

        interaction.editReply({
          embeds: [
            {
              color: client.settings.embedColors.red, //client.settings.embedColors.default,
              author: {
                name: `${interaction.guild.name} Sunucusunun AyarlarÄ± (Buton Rol)`,
                icon_url: interaction.guild.iconURL(),
              },
              description: "Bu sayfa bakÄ±mdadÄ±r. En kÄ±sa sÃ¼rede gÃ¼ncelleme ile dÃ¼zeltilecektir ðŸ˜Š"
            }
          ],
          components: [row]
        });

      } else if (int.values.toString() === "giveawaysPageOption") {

        interaction.editReply({
          embeds: [
            {
              color: client.settings.embedColors.default,
              author: {
                name: `${interaction.guild.name} Sunucusunun AyarlarÄ± (Ã‡ekiliÅŸler)`,
                icon_url: interaction.guild.iconURL(),
              },
              description:
                `**â€¢** Bu bot Nraphy aÃ§Ä±k kaynak altyapÄ±sÄ± kullanÄ±larak oluÅŸturulmuÅŸtur.\n` +
                `**â€¢** AÃ§Ä±k kaynak altyapÄ±sÄ±nda Ã‡ekiliÅŸ komutlarÄ± mevcut deÄŸildir.\n` +
                `**â€¢** Ã‡ekiliÅŸ komutlarÄ± ve daha fazlasÄ± ResmÃ® Nraphy botunda mevcuttur.\n` +
                `**â€¢** [Nraphy'i sunucuna eklemek iÃ§in buraya tÄ±kla!](https://top.gg/bot/700959962452459550/)`
            }
          ],
          components: [row]
        });

      } else if (int.values.toString() === "gamesPageOption") {

        interaction.editReply({
          embeds: [
            {
              color: client.settings.embedColors.default,
              author: {
                name: `${interaction.guild.name} Sunucusunun AyarlarÄ± (Oyunlar)`,
                icon_url: interaction.guild.iconURL(),
              },
              fields: [
                {
                  name: '**Â»** Kelime Oyunu',
                  value:
                    wordGame?.channel ?
                      `**â€¢** Kanal: ${interaction.guild.channels.cache.get(wordGame.channel)}\n` +
                      `**â€¢** Ãœst Ãœste Yazma: \`${wordGame?.writeMore ? `AÃ§Ä±k` : `KapalÄ±`}\``
                      : `**â€¢** \`KapalÄ±\``,
                },
                {
                  name: '**Â»** SayÄ± Saymaca Oyunu ðŸ”’',
                  value: `**â€¢** \`Bu oyun yalnÄ±zca ResmÃ® Nraphy botunda mevcuttur\``,
                },
                {
                  name: '**Â»** Tuttu TutmadÄ± Oyunu ðŸ”’',
                  value: `**â€¢** \`Bu oyun yalnÄ±zca ResmÃ® Nraphy botunda mevcuttur\``,
                },
                {
                  name: '**Â»** Bilgi âš ï¸�',
                  value:
                    `**â€¢** Bu bot Nraphy aÃ§Ä±k kaynak altyapÄ±sÄ± kullanÄ±larak oluÅŸturulmuÅŸtur.\n` +
                    `**â€¢** AÃ§Ä±k kaynak altyapÄ±sÄ±nda \`/sÄ±ralama\` komutu mevcut deÄŸildir.\n` +
                    `**â€¢** SÄ±ralama komutu ve daha fazlasÄ± ResmÃ® Nraphy botunda mevcuttur.\n` +
                    `**â€¢** [Nraphy'i sunucuna eklemek iÃ§in buraya tÄ±kla!](https://top.gg/bot/700959962452459550/)`,
                },
              ],
            }
          ],
          components: [row]
        });

      }
    });

    collector.on('end', collected => {
      return interaction.editReply({
        components: []
      }).catch(() => { });
    });

  }
};