<?php

namespace Main\Controllers;

use Main\Libs\Discord;
use Exception;
use Main\Core\Controller;
use Main\Core\Redirect;
use Main\Services\UserService;

class DiscordLegacyController extends Controller
{
		public function __construct()
		{
			if (settings('loginProvider') == 'discord' || !modules('discord')->isActive()) abort_404();
		}
    public function login()
    {
        $websiteURL = settings("websiteURL");
        $redirectUrl = "$websiteURL/discord/login";

        $discord = new Discord(modules('discord')->settings('clientID'), modules('discord')->settings('clientSecret'), modules('discord')->settings('botToken'));

        if (get("code")) {
	          $back = new Redirect(url("auth.login"));
            try {
                $accessToken = $discord->getAccessToken(get("code"), $redirectUrl);
                $user = $discord->getUser($accessToken);
                $checkUser = db()->prepare("SELECT * FROM AccountDiscordData WHERE discordUserID = ?");
                $checkUser->execute([$user->id]);
                $checkUser = $checkUser->fetch();
                if ($checkUser) {
                    $checkUser["permissions"] = UserService::getPermissions($checkUser["accountID"]);
		                if (settings("maintenanceStatus") == 1 && !UserService::isStaff($checkUser["permissions"])) {
			                return $back->flash('error', t__('The site is under maintenance!'));
		                }

                    $loginToken = rand_token();
                    $insertAccountSessions = db()->prepare("INSERT INTO AccountSessions (accountID, loginToken, useragent, creationIP, expiryDate, creationDate) VALUES (?, ?, ?, ?, ?, ?)");
                    $insertAccountSessions->execute(array($checkUser["accountID"], $loginToken, $_SERVER['HTTP_USER_AGENT'], getIP(), createDuration(0.01666666666), datetime()));
										
										session()->set('login', $loginToken);
										
		                redirect(url('account.profile.index'));
                } else {
										return $back->flash("error", t__('Your Discord account is not linked to any account!'));
                }
            } catch (Exception $e) {
	            return $back->flash("error", t__('Your Discord account is not linked to any account!'));
            }
        } else {
            $discordPermissions = ['identify', 'email', 'guilds'];
            if (modules('discord')->settings('joinServerStatus') == 1) {
                $discordPermissions[] = 'guilds.join';
            }
            $loginURL = $discord->getLoginUrl($redirectUrl, $discordPermissions);
            redirect($loginURL);
        }
    }

    public function link()
    {
        $websiteURL = settings("websiteURL");
        $redirectUrl = "$websiteURL/discord/link";

        $discord = new Discord(modules('discord')->settings('clientID'), modules('discord')->settings('clientSecret'), modules('discord')->settings('botToken'));

        if (get("code")) {
	          $redirect = new Redirect(url("account.profile.index"));
            try {
                $accessToken = $discord->getAccessToken(get("code"), $redirectUrl);
                $user = $discord->getUser($accessToken);
                $checkUser = db()->prepare("SELECT * FROM AccountDiscordData WHERE discordUserID = ?");
                $checkUser->execute([$user->id]);
                $checkUser = $checkUser->fetch();
                if (!$checkUser) {
                    $updateAccount = db()->prepare("INSERT INTO AccountDiscordData (accountID, discordUserID, creationDate) VALUES (?, ?, ?)");
                    $updateAccount->execute([auth()->user()->id(), $user->id, datetime()]);

                    if (modules('discord')->settings('joinServerStatus') == 1) {
                        $discord->joinGuild($accessToken, modules('discord')->settings('guildID'), $user->id);
                    }

                    if (modules('discord')->settings('roleSyncingStatus') == 1) {
                        $discord->giveRole(modules('discord')->settings('guildID'), $user->id, modules('discord')->settings('syncedRoleID'));
                    }
										
	                  return $redirect->flash("success", t__('Your Discord account has been successfully linked to your account!'));
                } else {
	                return $redirect->flash("error", t__('Your Discord account is already linked to another account!'));
                }
            } catch (Exception $e) {
								return $redirect->flash("error", t__('Your Discord account could not be linked to your account!'));
            }
        } else {
            $discordPermissions = ['identify', 'email', 'guilds'];
            if (modules('discord')->settings('joinServerStatus') == 1) {
                $discordPermissions[] = 'guilds.join';
            }
            $loginURL = $discord->getLoginUrl($redirectUrl, $discordPermissions);
            redirect($loginURL);
        }
    }

    public function unlink()
    {
        $discord = new Discord(modules('discord')->settings('clientID'), modules('discord')->settings('clientSecret'), modules('discord')->settings('botToken'));

        if (modules('discord')->settings('roleSyncingStatus') == 1) {
            $discord->removeRole(modules('discord')->settings('guildID'), auth()->user()->data("discordUserID"), modules('discord')->settings('syncedRoleID'));
        }

        $unlinkDiscord = db()->prepare("DELETE FROM AccountDiscordData WHERE accountID = ?");
        $unlinkDiscord->execute([auth()->user()->id()]);
	    
	      $redirect = new Redirect(url("account.profile.index"));
	      return $redirect->flash("success", t__('Your Discord account has been successfully unlinked from your account!'));
    }
}