<?php
class Intense_OAuth2 {
	public $scope, $response_type, $client_id, $client_secret, $redirect_url, $access_token_url, $service, $authentication_url, $code, $state;

	function Intense_OAuth2( $service, $authentication_url, $access_token_url, $scope ) {
		$intense_visions_options = get_option( 'intense_visions_options' );

		$this->service = $service; //used for data keys and state
		$this->client_id = ( isset( $intense_visions_options[ 'intense_' . $service . '_client_id'] ) ? $intense_visions_options[ 'intense_' . $service . '_client_id'] : null );;
		$this->client_secret = ( isset( $intense_visions_options[ 'intense_' . $service . '_client_secret'] ) ? $intense_visions_options[ 'intense_' . $service . '_client_secret'] : null );
		$this->redirect_url = "http://" . $_SERVER['HTTP_HOST'] . "/wp-admin/admin.php?page=intense_visions_options";
		$this->access_token_url = $access_token_url;
		$this->authentication_url = $authentication_url;
		$this->code = isset( $_GET['code'] ) ? $_GET['code'] : null;
		$this->state = isset( $_GET['state'] ) ? $_GET['state'] : null;
		$this->scope = $scope;
	}

	function show_authentication_link() {
		return !empty( $this->client_id ) && !empty( $this->client_secret );
	}

	function get_authentication_link() {
		return '<a target="_blank" href="' . $this->authentication_url .
			'?redirect_uri=' . urlencode( $this->redirect_url ) .
			'&response_type=code&client_id=' . urlencode( $this->client_id ) .
			'&state=' . $this->service . 
			( ! empty( $this->scope ) ? '&scope=' . urlencode( $this->scope ) : '' ) . '"/>authenticate</a>';
	}

	function get_access_token() {
		$intense_visions_options = get_option( 'intense_visions_options' );

        if ( isset( $_GET['page'] ) && $_GET['page'] == 'intense_visions_options' && isset( $this->code ) && isset( $this->state ) && $this->state == $this->service ) {
			$response = wp_remote_post( $this->access_token_url,
				array(
					'body' => array(
						'code' => $this->code,
						// 'response_type' => 'authorization_code',
						'redirect_uri' => $this->redirect_url,
						'client_id' => $this->client_id,
						'client_secret' => $this->client_secret,
						'grant_type' => 'authorization_code',
					),
					'sslverify' => apply_filters( 'https_local_ssl_verify', false )
				)
			);

			$access_token = null;
			$username = null;
			$image = null;

			$success = false;
			$errormessage = null;
			$errortype = null;

			if ( !is_wp_error( $response ) && $response['response']['code'] < 400 && $response['response']['code'] >= 200 ) {
				$auth = json_decode( $response['body'] );

				if ( isset( $auth->access_token ) ) {
					$access_token = $auth->access_token;
					
					if ( isset( $auth->user ) ) {
						$user = $auth->user;
					}

					$success = true;
				} else if ( stripos( $response['body'], "access_token" ) !== false ) {
					$pairs = explode( '&', $response['body'] );

					foreach ( $pairs as $pair ) {
						$part = explode( '=', $pair );
						$get_parameters[$part[0]] = urldecode( $part[1] );
					}

					$access_token = $get_parameters["access_token"];
					$success = true;
				} else {
					echo "Unable to locate access token" . $response['body'];
				}
			} else if ( is_wp_error( $response ) ) {
				$error = $response->get_error_message();
				$errormessage = $error;
				$errortype = 'Wordpress Error';
				echo $errormessage;
			} else if ( $response['response']['code'] >= 400 ) {
				//echo "<pre>"; print_r($response); echo "</pre>";
				$error = json_decode( $response['body'] );
				$errormessage = $error->error_message;
				$errortype = $error->error_type;
				echo $errormessage;
			}			
			
					
			$this->save_access_token( $access_token );

			if ( $success ) {
				echo "<script> opener.location.reload(true);self.close(); </script>";
			}

			die( 1 );
		}
	}

	function save_access_token( $access_token ) {		
		$intense_visions_options = get_option( 'intense_visions_options' );
		$intense_visions_options[ 'intense_' . $this->service . '_access_token' ] = $access_token;	

		$args = array( 
			'opt_name' => 'intense_visions_options',
			'database' => null
		);

		if ( !isset( $args['database'] )) $args['database'] = null;

		if ( $args['database'] === 'transient' ) {
		 set_transient( $args['opt_name'] . '-transient', $intense_visions_options, $args['transient_time'] );
		} else if ( $args['database'] === 'theme_mods' ) {
		 set_theme_mod( $args['opt_name'] . '-mods', $intense_visions_options );
		} else if ( $args['database'] === 'theme_mods_expanded' ) {
		 foreach ( $intense_visions_options as $k=>$v ) {
		  set_theme_mod( $k, $v );
		 }
		} else {
		 update_option( $args['opt_name'], $intense_visions_options );
		}		
	}
}
