<?php

namespace Digits\SocialLogin\Auths;
use DigitsSocialOAuth2;

class LinkedinAuth 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_linkedin_login', 'LinkedIn');
    }

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

            $code = $_REQUEST['code'];
            $accessTokenUrl = 'https://www.linkedin.com/oauth/v2/accessToken';

            $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://api.linkedin.com/v2/me");
            $response = $response['result']['data'][0];

            $name = $response['localizedFirstName'] . " " . $response['localizedLastName'];
            $id = $response['id'];
            $username = '';


            $email_response = $client->fetch("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))");
            $response = $email_response['result'];

            $email = $response['elements'][0]['handle~']['emailAddress'];

            $response = digits_social_create_user($name, $email, 'linkedin', $username, $id);

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