<?php

namespace Digits\SocialLogin\Auths;

use DigitsSocialOAuth2;

class GitlabAuth 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_gitlab_login', 'GitLab');
    }

    public function get_url()
    {
        $query = [
            'client_id' => urlencode($this->client_id),
            'response_type' => 'code',
            'scope' => urlencode('read_user'),
            'redirect_uri' => urlencode($this->redirect_url),
            'state' => wp_create_nonce('gitlab_login'),
        ];
        $base_url = 'https://gitlab.com/oauth/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'], 'gitlab_login')) {
            $this->nonce_fail();
            die();
        }
        try {

            $code = $_REQUEST['code'];
            $accessTokenUrl = 'https://gitlab.com/oauth/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://gitlab.com/api/v4/user");
            $response = $response['result'];

            $name = $response['name'];
            $username = $response['username'];
            $gitlab_id = $response['id'];
            $email = $response['email'];

            $response = digits_social_create_user($name, $email, 'gitlab', $username, $gitlab_id);

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

    }
}
