<?php

namespace Digits\SocialLogin\Auths;

use DigitsSocialOAuth2;

class DiscordAuth extends SocialLoginAuth
{
    private $client_id;
    private $redirect_url;
    private $icon_only;
    private $settings;

    function __construct($settings, $social_info, $icon_only)
    {
        $this->settings = $settings;
        $this->client_id = esc_attr($settings['clientID']);
        $this->redirect_url = $social_info['redirect_uri'];
        $this->icon_only = $icon_only;


        parent::__construct();

    }

    public function render()
    {
        $this->default_layout('digits_discord_login', 'Discord');

    }

    public function get_url()
    {
        $query = [
            'client_id' => urlencode($this->client_id),
            'scope' => 'identify%20email',
            'response_type' => 'code',
            'redirect_uri' => urlencode($this->redirect_url),
            'state' => wp_create_nonce('discord_login'),
        ];
        $base_url = 'https://discord.com/api/oauth2/authorize';
        return add_query_arg($query, $base_url);
    }

    public function enqueue_scripts()
    {
    }

    public function process_token()
    {

    }

    public function process_oauth_token()
    {
        if (empty($_REQUEST['code'])) {
            $this->invalid_info();
            die();
        }
        if (!wp_verify_nonce($_REQUEST['state'], 'discord_login')) {
            $this->nonce_fail();
            die();
        }
        try {

            $code = $_REQUEST['code'];
            $accessTokenUrl = 'https://discord.com/api/oauth2/token';

            $client = new DigitsSocialOAuth2\Client($this->client_id, $this->settings['clientSecretID'], DigitsSocialOAuth2\Client::AUTH_TYPE_FORM);

            $params = array("code" => $code, "redirect_uri" => $this->redirect_url);
            $response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params);

            $accessTokenResult = $response["result"];

            if (empty($accessTokenResult["access_token"])) {
                $this->invalid_info();
                die();
            }

            $client->setAccessToken($accessTokenResult["access_token"]);
            $client->setAccessTokenType(DigitsSocialOAuth2\Client::ACCESS_TOKEN_BEARER);

            $response = $client->fetch("https://discordapp.com/api/users/@me");

            $response = $response['result'];

            $name = $response['display_name'];
            $username = $response['username'];
            $discord_id = $response['id'];
            $email = $response['email'];

            $response = digits_social_create_user($name, $email, 'discord', $username, $discord_id);

            $this->success_view($response);
        } catch (\Exception $e) {
            $this->error_view($e);
        }

    }
}
