<?php

namespace Dashboard\Controllers\Settings;

use Curl\Curl;
use Dashboard\Core\Controller;
use Dashboard\Core\Redirect;
use PDO;

class DiscordBotController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_SETTINGS');
    }

    public function index()
    {
        $isLinked = moduleSettings('discord_bot', 'botLinkToken') != '' && moduleSettings('discord_bot', 'guildID') != '';
				$websiteRoles = db()->query("SELECT * FROM Roles ORDER BY priority DESC, id DESC")->fetchAll(PDO::FETCH_ASSOC);
				
        return view('settings.discord-bot.index', compact('isLinked', 'websiteRoles'));
    }
	
    public function link()
    {
        if (moduleSettings('discord_bot', 'botLinkToken') != '' && moduleSettings('discord_bot', 'guildID') != '') {
            return back()->flash("error", t__('Discord Bot is already connected!'));
        }

        $token = moduleSettings('discord_bot', 'botLinkToken');
        if ($token == '') {
            $curl = new Curl();
            $curl->post("https://discord-bot-api.leaderos.net/create-token", [
                "apiKey"   => settings('apiKey'),
                "server" => LOCATION,
            ]);
            $response = json_decode($curl->response);
            if ($curl->error || !isset($response->data->token)) {
                if (isset($response->error) && $response->error == 'INVALID_API_KEY') {
                    return back()->flash("error", t__('Invalid API Key! Please reset your API Key from Dashboard > Settings > API.'));
                }
                return back()->flash("error", t__('An error occurred while connecting to the Discord server. Please try again later.'));
            }
            $token = $response->data->token;
	          updateModuleSettings('discord_bot', [
		          'botLinkToken' => $token
	          ]);
        }
        $inviteLink = "https://discord-bot-api.leaderos.net/invite";

        return view('settings.discord-bot.link', compact('token', 'inviteLink'));
    }

    public function validate()
    {
        $curl = new Curl();
        $curl->post("https://discord-bot-api.leaderos.net/validate-token", [
            "token"   => moduleSettings('discord_bot', 'botLinkToken'),
        ]);
        $response = json_decode($curl->response);
        if ($curl->error || !isset($response->status)) {
            return back()->flash("error", t__('An error occurred while connecting to the Discord server. Please try again later.'));
        }
        if (!$response->status && $response->error == 'INVALID_TOKEN') {
            return back()->flash("error", t__('An error occurred while connecting to the Discord server. Please try again later.'));
        }
        if (!$response->status && $response->error == 'NOT_LINKED') {
            return back()->flash("error", t__('The Discord Bot is not linked to a server. Please follow the steps to link the bot to your Discord server!'));
        }
        $guildID = $response->data->guildID;
        updateModuleSettings('discord_bot', [
	        'guildID' => $guildID
        ]);

        $redirect = new Redirect(url('dashboard.settings.discord-bot.index'));
        return $redirect->flash("success", t__('Discord Bot has been successfully connected!'));
    }

    public function update()
    {
		    updateModuleSettings('discord_bot', [
			    'syncNames' => post('syncNames'),
		    ]);
        createLog("DISCORD_SETTINGS_UPDATED");
	    
		    $curl = new Curl();
		    $curl->post("https://discord-bot-api.leaderos.net/update-settings", [
			    "token"   => moduleSettings('discord_bot', 'botLinkToken'),
			    "syncNames" => post('syncNames'),
		    ]);
		    $response = json_decode($curl->response);
		    if ($curl->error || !isset($response->status) || !$response->status) {
			    return back()->flash("error", t__('An error occurred while updating the Discord settings. Please try again later.'));
		    }

        return back()->flash("success", t__('Changes has been saved successfully!'));
    }
	
		public function reset()
		{
			$token = moduleSettings('discord_bot', 'botLinkToken');
			updateModuleSettings('discord_bot', [
				'botLinkToken' => '',
				'guildID' => '',
				'syncNames' => '0',
			]);
			
			$curl = new Curl();
			$curl->post("https://discord-bot-api.leaderos.net/reset-bot", [
				"token" => $token,
			]);
			$response = json_decode($curl->response);
			if ($curl->error || !isset($response->status) || !$response->status) {
				response()->json([
					'status' => false,
					'message' => t__('An error occurred while updating the Discord settings. Please try again later.')
				]);
			}
			
			response()->json([
				'status' => true
			]);
		}
		
		public function linkRoles()
		{
			validate([
				'roles' => 'required|array',
			]);
			
			if (count(array_filter($_POST["roles"]))) {
				$updateSiteRole = db()->prepare("UPDATE Roles SET discordRoleID = ? WHERE id = ?");
				foreach ($_POST["roles"] as $key => $command) {
					$siteRoleID = strip_tags($_POST["roles"][$key]);
					$discordRoleID = strip_tags($_POST["discordRoles"][$key]);
					
					if ($siteRoleID == '') continue;
					if ($discordRoleID == '') $discordRoleID = null;
					
					$updateSiteRole->execute([$discordRoleID, $siteRoleID]);
				}
			}
			
			return back()->flash("success", t__('Changes has been saved successfully!'));
		}
}