<?php

namespace Digits\SocialLogin\Auths;

use Abraham\TwitterOAuth\TwitterOAuth;
use DigitsSocialOAuth2;

class TwitterAuth 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 getConnection()
    {
        $connection = new TwitterOAuth($this->client_id, $this->settings['clientSecretID']);
        return $connection;
    }

    public function render()
    {
        $this->default_layout('digits_twitter_login', 'Twitter');
    }

    public function get_url()
    {
        return add_query_arg(
            ['state' => wp_create_nonce('twitter_login')],
            $this->redirect_url);
    }

    public function oauth_get_url()
    {
        try {
            session_start();
            $connection = $this->getConnection();
            $request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => $this->redirect_url));

            $url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));

            $_SESSION['oauth_token'] = $request_token['oauth_token'];
            $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

        } catch (\Exception $e) {
            wp_die($e->getMessage());
        }
        return $url;
    }


    public function enqueue_scripts()
    {
    }

    public function process_token()
    {
    }

    public function process_oauth_token()
    {
        if (!wp_verify_nonce($_REQUEST['state'], 'twitter_login')) {
            $this->nonce_fail();
            die();
        }

        if (empty($_REQUEST['oauth_token']) || empty($_REQUEST['oauth_verifier'])) {
            wp_redirect($this->oauth_get_url());
            die();
        } else {
            try {
                $connection = $this->getConnection();
                $connection->setOauthToken($_REQUEST['oauth_token'], $_REQUEST['oauth_verifier']);;
                $access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_REQUEST['oauth_verifier']]);
                $user = $connection->get('account/verify_credentials', ['include_email' => 'true']);

                $id = $user->id;
                $username = $user->screen_name;
                $name = $user->name;
                $email = $user->email;

                $response = digits_social_create_user($name, $email, 'twitter', $username, $id);
                $this->success_view($response);
            } catch (\Exception $e) {
                $this->error_view($e);
            }
        }
    }
}
