<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Laravel\Socialite\Two\AbstractProvider;
use Laravel\Socialite\Two\ProviderInterface;
use Laravel\Socialite\Two\User;

class ZaloProvider extends AbstractProvider implements ProviderInterface {
	/**
	 * Register services.
	 *
	 * @return void
	 */
	const IDENTIFIER = 'ZALO';
	public function register() {
		//
	}

	/**
	 * Bootstrap services.
	 *
	 * @return void
	 */
	public function boot() {
		//
	}

	/**
	 * {@inheritdoc}
	 */
	protected function getCodeFields($state = null)
	{
		$fields = [
			'app_id' => $this->clientId,
			'redirect_uri' => $this->redirectUrl,
			'state' => $state,
		];

		return array_merge($fields, $this->parameters);
	}


	public function getAccessTokenResponse($code)
	{
		$response = $this->getHttpClient()->get($this->getTokenUrl(), [
			'headers' => ['Accept' => 'application/json'],
			'query' => $this->getTokenFields($code),
		]);

		return json_decode($response->getBody(), true);
	}

	/**
	 * Get the authentication URL for the provider.
	 *
	 * @param string $state
	 *
	 * @return string
	 */

	protected function getAuthUrl( $state ) {
		// TODO: Implement getAuthUrl() method.
		return $this->buildAuthUrlFromBase( 'https://oauth.zaloapp.com/v3/auth', $state );
	}

	/**
	 * Get the token URL for the provider.
	 *
	 * @return string
	 */
	protected function getTokenUrl() {
		// TODO: Implement getTokenUrl() method.
		return 'https://oauth.zaloapp.com/v3/access_token';
	}

	/**
	 * Get the raw user for the given access token.
	 *
	 * @param string $token
	 *
	 * @return array
	 */
	protected function getUserByToken( $token ) {
		// TODO: Implement getUserByToken() method.
		$response = $this->getHttpClient()->get( 'https://graph.zalo.me/v2.0/me?access_token=' . $token . '&fields=id,name,picture' );

		return json_decode( $response->getBody(), true );
	}

	/**
	 * Map the raw user array to a Socialite User instance.
	 *
	 * @param array $user
	 *
	 * @return \Laravel\Socialite\Two\User
	 */
	protected function mapUserToObject( array $user ) {
		// TODO: Implement mapUserToObject() method.
		return ( new User() )->setRaw( $user )->map( [
			'id'       => $user['id'],
			'nickname' => null,
			'name'     => $user['name'],
			'email'    => null,
			'avatar'   => preg_replace( '/^http:/i', 'https:', $user['picture']['data']['url'] ),
		] );
	}

	protected function getTokenFields($code)
	{
		return [
			'app_id' => $this->clientId,
			'app_secret' => $this->clientSecret,
			'code' => $code,
			'redirect_uri' => $this->redirectUrl,
		];
	}
}
