<?php

namespace App\Libraries\MySocket\GoogleSocket;

use GuzzleHttp\Client;
use App\Entities\UserSNSEntity as Entity;

class CURL extends GoogleSocket
{
	public function __construct()
	{
		parent::__construct();
	}

	public function getClient(): Client
	{
		if (!$this->_client) {
			$this->_client = new Client();
		}
		return $this->_client;
	}

	public function createAuthUrl(): string
	{
		$options = http_build_query([
			'response_type' => 'code',
			'client_id' => env('socket.google.client.id'),
			'redirect_uri' => base_url(env('socket.google.client.callback_url')),
			'scope' => "https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/userinfo.email",
			'access_type' => 'offline',
			'prompt' => 'consent'
		]);
		//기본적으로 검색할 범위를 지정하고 사용자를 Google OAuth 동의 화면으로 리디렉션합니다
		return "https://accounts.google.com/o/oauth2/v2/auth?" . $options;
	}

	//TokenInfo
	// (object) array(
	//    'access_token' => 'sdfsdfsdfsdf',
	//    'expires_in' => 3599,
	//    'refresh_token' => 'sdfsdf',
	//    'scope' => 'https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/userinfo.email',
	//    'token_type' => 'Bearer',
	//    'id_token' => 'fadfasdfsadf.sdfsdf.sdfsd',
	// )	
	// id_token(.을기준으로 base64_decode):
	// DEBUG - 2024-10-10 07:25:01 --> array (
	// 	'alg' => 'RS256',
	// 	'kid' => 'a50f6e70ef4bsdfsdffb8f54dce9ee',
	// 	'typ' => 'JWT',
	//   )
	//   DEBUG - 2024-10-10 07:25:01 --> array (
	// 	'iss' => 'accounts.google.com',
	// 	'azp' => '105607sdfsdfsdfsdfogleusercontent.com',
	// 	'aud' => '1056073563687sdfsdfsdftent.com',
	// 	'sub' => '103667492342341096838',
	// 	'email' => 'sdfsdfsdf@gmail.com',
	// 	'email_verified' => true,
	// 	'at_hash' => 'RKDNDFSrkeZ_LWg',
	// 	'iat' => 1728df545102,
	// 	'exp' => 172854df8702,
	//   )
	//   DEBUG - 2024-10-10 07:25:01 --> NULL

	public function setToken(string $access_code): void
	{
		$options = [
			'code' => $access_code,
			'client_id' => env('socket.google.client.id'),
			'client_secret' => env('socket.google.client.key'),
			'redirect_uri' => base_url(env('socket.google.client.callback_url')),
			'grant_type' => 'authorization_code',
		];
		$response = $this->post("https://accounts.google.com/o/oauth2/token", $options);
		if ($response->getStatusCode() != 200) {
			$message = sprintf(
				"Google: %s에서 API 호출 실패: \n--request options--\n%s\n--response--\n%s\n",
				__FUNCTION__,
				var_export($options, true),
				var_export($response, true)
			);
			log_message("error", $message);
			throw new \Exception($message);
		}
		$tokenInfo = json_decode($response->getBody(), true);
		// log_message("debug", var_export($tokenInfo, true));
		if (isset($tokenInfo['error']) || !isset($tokenInfo[$this->_token_name]) || empty($tokenInfo[$this->_token_name])) {
			$message = sprintf(
				"Google: Token 정보가 없습니다.\n--tokenInfo--\n%s\n",
				__FUNCTION__,
				var_export($tokenInfo, true)
			);
			log_message("error", $message);
			throw new \Exception($message);
		}
		//JWT값
		// $jwts = explode('.', $tokenInfo['id_token']);
		// foreach ($jwts as $jwt) {
		// 	$info = json_decode(base64_decode($jwt), true);
		// 	// log_message("debug", var_export($info, true));
		// }
		// 토큰 정보 가져오기
		$this->_access_token = $tokenInfo[$this->_token_name];
		// 세션에 Token 값 설정
		$this->getSession()->set($this->_token_name, $this->_access_token);
	}

	// throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 데이터 처리 필요");
	// DEBUG - 2023-07-13 12:54:51 --> \Google\Service\Oauth2\Userinfo::__set_state(array(
	// 	'internal_gapi_mappings' =>
	// 	 'familyName' => 'family_name',
	// 	 'givenName' => 'given_name',
	// 	 'verifiedEmail' => 'verified_email',
	//    ),
	// 	'modelData' =>
	//    array (
	// 	 'verified_email' => true,
	// 	 'given_name' => '이름',
	// 	 'family_name' => '성',
	//    ),
	// 	'processed' =>
	//    array (
	//    ),
	// 	'email' => 'twsdfsew342s@gmail.com',
	// 	'familyName' => '성',
	// 	'gender' => NULL,
	// 	'givenName' => '이름',
	// 	'hd' => NULL,
	// 	'id' => '103667492432234234236838324',
	// 	'link' => NULL,
	// 	'locale' => 'ko',
	// 	'name' => '성이름',
	// 	'picture' => 'https://lh3.googleusercontent.com/a/AAcHTteFSgefsdfsdRJBkJA2tBEmg4PQrvI1Ta_5IXu5=s96-c',
	// 	'verifiedEmail' => true,
	//  ))
	public function signup(): Entity
	{
		$options = [
			"headers" => [
				"Authorization" => "Bearer {$this->getToken()}",
				"Accept" => "application/json",
				'User-Agent' => $this->getUserAgent()
			],
		];
		$response = $this->get("https://www.googleapis.com/oauth2/v3/userinfo", $options);
		if ($response->getStatusCode() != 200) {
			$message = sprintf(
				"Google: %s에서 API 호출 실패: \n--request options--\n%s\n--response--\n%s\n",
				__FUNCTION__,
				var_export($options, true),
				var_export($response, true)
			);
			log_message("error", $message);
			throw new \Exception($message);
		}
		$userInfo = json_decode($response->getBody(), true);
		$detail = var_export($userInfo, true);
		// log_message("debug", $detail);
		if (isset($userInfo['error']) || !isset($userInfo['email']) || empty($userInfo['email'])) {
			$message = sprintf(
				"Google: User 정보가 없습니다.\n--userInfo--\n%s\n",
				__FUNCTION__,
				var_export($userInfo, true)
			);
			log_message("error", $message);
			throw new \Exception($message);
		}
		// 사용자정보 등록하기
		return $this->signup_process($userInfo["id"], $userInfo["name"], $userInfo["email"], $detail);
	}
}
