Tickets! and a lot of bug fixes
diff --git a/src/actions/tickets/delete.ts b/src/actions/tickets/delete.ts
index cab38ec..48d2a51 100644
--- a/src/actions/tickets/delete.ts
+++ b/src/actions/tickets/delete.ts
@@ -1,50 +1,52 @@
-import Discord, { ButtonBuilder, ActionRowBuilder, ButtonStyle, ButtonInteraction } from "discord.js";
+import { getCommandMentionByName } from '../../utils/getCommandMentionByName.js';
+import Discord, { ActionRowBuilder, ButtonBuilder, ButtonInteraction, PrivateThreadChannel, TextChannel, ButtonStyle } from "discord.js";
 import client from "../../utils/client.js";
 import EmojiEmbed from "../../utils/generateEmojiEmbed.js";
 import getEmojiByName from "../../utils/getEmojiByName.js";
+import { preloadPage } from '../../utils/createTemporaryStorage.js';
 
 export default async function (interaction: Discord.CommandInteraction | ButtonInteraction) {
     if (!interaction.guild) return;
+    const config = await client.database.guilds.read(interaction.guild.id);
     const { log, NucleusColors, entry, renderUser, renderChannel, renderDelta } = client.logger;
 
-    const config = await client.database.guilds.read(interaction.guild.id);
-    let thread = false;
-    if (interaction.channel instanceof Discord.ThreadChannel) thread = true;
-    const threadChannel = interaction.channel as Discord.ThreadChannel;
-    const channel = interaction.channel as Discord.TextChannel;
-    if (
-        !channel.parent ||
-        config.tickets.category !== channel.parent.id ||
-        (thread ? threadChannel.parent.parent.id !== config.tickets.category : false)
-    ) {
-        return interaction.reply({
+    const ticketChannel = config.tickets.category;
+    if (!("parent" in interaction.channel!)) {
+        return await interaction.reply({
             embeds: [
                 new EmojiEmbed()
-                    .setTitle("Deleting Ticket...")
-                    .setDescription(
-                        "This ticket is not in your tickets category, so cannot be deleted. You cannot run close in a thread."
-                    )
+                    .setTitle("Not a ticket")
+                    .setDescription("This channel isn't a ticket, so you can't delete it.")
                     .setStatus("Danger")
                     .setEmoji("CONTROL.BLOCKCROSS")
-            ],
-            ephemeral: true
+            ], ephemeral: true
         });
-    }
-    const status = channel.topic.split(" ")[1];
-    if (status === "Archived") {
-        await interaction.reply({
+    } else if (interaction.channel!.parent!.id !== ticketChannel) {
+        return await interaction.reply({
             embeds: [
                 new EmojiEmbed()
-                    .setTitle("Delete Ticket")
-                    .setDescription("Your ticket is being deleted...")
+                    .setTitle("Not a ticket")
+                    .setDescription("This channel isn't a ticket, so you can't delete it.")
                     .setStatus("Danger")
-                    .setEmoji("GUILD.TICKET.CLOSE")
-            ]
+                    .setEmoji("CONTROL.BLOCKCROSS")
+            ], ephemeral: true
         });
+    }
+    const channel: PrivateThreadChannel | TextChannel = interaction.channel as PrivateThreadChannel | TextChannel;
+    let status: string | null = ("topic" in interaction.channel) ? interaction.channel!.topic : interaction.channel.name;
+    status = status ?? "";
+    if (status.endsWith("Archived")) { status = "Archived"; }
+    else { status = "Active"; }
+
+    const uID = channel.type === Discord.ChannelType.PrivateThread ? channel.name.split(" - ")[1] : channel.topic!.split(" ")[0];
+
+    if (status === "Archived") {
+        // Delete the ticket
+
         const data = {
             meta: {
-                type: "ticketDeleted",
-                displayName: "Ticket Deleted",
+                type: "ticketClosed",
+                displayName: "Ticket Closed",
                 calculateType: "ticketUpdate",
                 color: NucleusColors.red,
                 emoji: "GUILD.TICKET.CLOSE",
@@ -52,85 +54,45 @@
             },
             list: {
                 ticketFor: entry(
-                    channel.topic.split(" ")[0],
-                    renderUser((await interaction.guild.members.fetch(channel.topic.split(" ")[0])).user)
+                    uID!,
+                    renderUser((await interaction.guild.members.fetch(uID!)).user)
                 ),
-                deletedBy: entry(interaction.member.user.id, renderUser(interaction.member.user)),
-                deleted: entry(new Date().getTime(), renderDelta(new Date().getTime()))
+                closedBy: entry(interaction.member!.user.id, renderUser(interaction.member!.user as Discord.User)),
+                closed: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+                ticketChannel: entry(channel.id, channel.name)
             },
             hidden: {
                 guild: interaction.guild.id
             }
         };
         log(data);
-        interaction.channel.delete();
-        return;
+
+        await channel.delete();
     } else if (status === "Active") {
+        // Close the ticket
+
+        if (channel.isThread()) {
+            channel.setName(`${channel.name.replace("Active", "Archived")}`);
+            channel.members.remove(channel.name.split(" - ")[1]!);
+        } else {
+            channel.setTopic(`${(channel.topic ?? "").replace("Active", "Archived")}`);
+            if (!channel.topic!.includes("Archived")) { channel.setTopic("0 Archived"); }
+            await channel.permissionOverwrites.delete(channel.topic!.split(" ")[0]!);
+        }
+        preloadPage(interaction.channel.id, "privacy", "2")
         await interaction.reply({
             embeds: [
                 new EmojiEmbed()
-                    .setTitle("Close Ticket")
-                    .setDescription("Your ticket is being closed...")
-                    .setStatus("Warning")
-                    .setEmoji("GUILD.TICKET.ARCHIVED")
-            ]
-        });
-        const overwrites = [
-            {
-                id: channel.topic.split(" ")[0],
-                deny: ["VIEW_CHANNEL"],
-                type: "member"
-            },
-            {
-                id: interaction.guild.id,
-                deny: ["VIEW_CHANNEL"],
-                type: "role"
-            }
-        ] as Discord.OverwriteResolvable[];
-        if (config.tickets.supportRole !== null) {
-            overwrites.push({
-                id: interaction.guild.roles.cache.get(config.tickets.supportRole),
-                allow: ["VIEW_CHANNEL", "SEND_MESSAGES", "ATTACH_FILES", "ADD_REACTIONS", "READ_MESSAGE_HISTORY"],
-                type: "role"
-            });
-        }
-        channel.edit({ permissionOverwrites: overwrites });
-        channel.setTopic(`${channel.topic.split(" ")[0]} Archived`);
-        const data = {
-            meta: {
-                type: "ticketClosed",
-                displayName: "Ticket Closed",
-                calculateType: "ticketUpdate",
-                color: NucleusColors.yellow,
-                emoji: "GUILD.TICKET.ARCHIVED",
-                timestamp: new Date().getTime()
-            },
-            list: {
-                ticketFor: entry(
-                    channel.topic.split(" ")[0],
-                    renderUser((await interaction.guild.members.fetch(channel.topic.split(" ")[0])).user)
-                ),
-                closedBy: entry(interaction.member.user.id, renderUser(interaction.member.user)),
-                closed: entry(new Date().getTime(), renderDelta(new Date().getTime())),
-                ticketChannel: entry(channel.id, renderChannel(channel))
-            },
-            hidden: {
-                guild: interaction.guild.id
-            }
-        };
-        log(data);
-        await interaction.editReply({
-            embeds: [
-                new EmojiEmbed()
-                    .setTitle("Close Ticket")
-                    .setDescription(
-                        "This ticket has been closed.\nType `/ticket close` again to delete it.\n\nNote: Check `/privacy` for details about transcripts."
-                    )
+                    .setTitle("Archived Ticket")
+                    .setDescription(`This ticket has been Archived. Type ${await getCommandMentionByName("ticket/close")} to delete it.` +
+                        await client.database.premium.hasPremium(interaction.guild.id) ?
+                        `\n\nFor more info on transcripts, check ${await getCommandMentionByName("privacy")}` :
+                        "")
                     .setStatus("Warning")
                     .setEmoji("GUILD.TICKET.ARCHIVED")
             ],
             components: [
-                new ActionRowBuilder().addComponents(
+                new ActionRowBuilder<ButtonBuilder>().addComponents(
                     [
                         new ButtonBuilder()
                             .setLabel("Delete")
@@ -138,27 +100,52 @@
                             .setCustomId("closeticket")
                             .setEmoji(getEmojiByName("CONTROL.CROSS", "id"))
                     ].concat(
-                        client.database.premium.hasPremium(interaction.guild.id)
+                        await client.database.premium.hasPremium(interaction.guild.id)
                             ? [
-                                  new ButtonBuilder()
-                                      .setLabel("Create Transcript and Delete")
-                                      .setStyle(ButtonStyle.Primary)
-                                      .setCustomId("createtranscript")
-                                      .setEmoji(getEmojiByName("CONTROL.DOWNLOAD", "id"))
-                              ]
+                                    new ButtonBuilder()
+                                        .setLabel("Create Transcript and Delete")
+                                        .setStyle(ButtonStyle.Primary)
+                                        .setCustomId("createtranscript")
+                                        .setEmoji(getEmojiByName("CONTROL.DOWNLOAD", "id"))
+                                ]
                             : []
                     )
                 )
             ]
         });
-        return;
+        const data = {
+            meta: {
+                type: "ticketClosed",
+                displayName: "Ticket Archived",
+                calculateType: "ticketUpdate",
+                color: NucleusColors.yellow,
+                emoji: "GUILD.TICKET.ARCHIVED",
+                timestamp: new Date().getTime()
+            },
+            list: {
+                ticketFor: entry(
+                    uID!,
+                    renderUser((await interaction.guild.members.fetch(uID!)).user)
+                ),
+                archivedBy: entry(interaction.member!.user.id, renderUser(interaction.member!.user as Discord.User)),
+                archived: entry(new Date().getTime(), renderDelta(new Date().getTime())),
+                ticketChannel: entry(channel.id, renderChannel(channel))
+            },
+            hidden: {
+                guild: interaction.guild.id
+            }
+        };
+        log(data);
     }
+    return;
 }
 
-async function purgeByUser(member, guild) {
+
+async function purgeByUser(member: string, guild: string) {
     const config = await client.database.guilds.read(guild.id);
+    const fetchedGuild = await client.guilds.fetch(guild);
     if (!config.tickets.category) return;
-    const tickets = guild.channels.cache.get(config.tickets.category);
+    const tickets = fetchedGuild.channels.cache.get(config.tickets.category);
     if (!tickets) return;
     const ticketChannels = tickets.children;
     let deleted = 0;
@@ -198,4 +185,4 @@
     }
 }
 
-export { purgeByUser };
+export { purgeByUser };
\ No newline at end of file