<?php
namespace App\Controllers;

class Auths extends BaseController {

	public function login() {
		$TM_url = "https://api-transmedic1.transmedic.co.id/api/token/create";
		//$TM_url = "http://cmod-rest.local/tests";
		$fileSBY = "tokens/pbmc_sby.txt";
		$fileDPS = "tokens/pbmc_dps.txt";
		
		$secret = "o7lf5DUxSuPKtDjlbqc2VuZD9WjQ5qAZ";
		
		//$credSBY = [ "username"=>"pbmc_surabaya", "password"=>"pgcWfdwX3qEt9zaC" ];
		//$credDPS = [ "username"=>"pbmc_bali", "password"=>"J8e29XjLmDCFuQnk" ];
		
		$header = [
			'typ' => 'JWT',
			'alg' => 'HS256'
		];

		$payloadSBY = [
			'iat' => time(),
			'data'=> [
				'username'=>"pbmc_surabaya", 
				'password'=>"pgcWfdwX3qEt9zaC"
			]
		];
		
		$payloadDPS = [
			'iat' => time(),
			'data'=> [
				'username'=>"pbmc_bali", 
				'password'=>"J8e29XjLmDCFuQnk"
			]
		];
		
		function base64UrlEncode($data) {
			return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
		}

		function createJWT($header, $payload, $secret) {
			$encodedHeader = base64UrlEncode(json_encode($header));
			$encodedPayload = base64UrlEncode(json_encode($payload));

			$signature = hash_hmac('sha256', "$encodedHeader.$encodedPayload", $secret, true);
			$encodedSignature = base64UrlEncode($signature);

			// Combine to create the JWT
			$jwt = "$encodedHeader.$encodedPayload.$encodedSignature";
			return $jwt;
		}
		
		function token2file($TM_url, $jwt, $file ) { 
			$client = \Config\Services::curlrequest();
			try { 
				$response = $client->request('GET', $TM_url, [
					"headers" => [
						"AppCode" => "2",
						"Accept" => "application/json",
						"Authorization" => "Bearer $jwt"
					],
					"body" => '',
					"verify" => false
				]);
				
				if ($response->getStatusCode() == 200) { 
					$body = $response->getBody();
					$data = json_decode($body, true);	
					$token = $data['data']['token'];
					if (file_put_contents($file, $token) !== false) {
						echo "Response saved to: " . $file . "<br/>";
					}
				} else {
					print_r($response);
				}
			} catch (\Exception $e) {
				echo "Error: " . $e->getMessage();
			}
		}
		
		
		$jwtSBY = createJWT($header, $payloadSBY, $secret);
		$jwtDPS = createJWT($header, $payloadDPS, $secret);
		
		token2file($TM_url, $jwtSBY, $fileSBY);
		token2file($TM_url, $jwtDPS, $fileDPS);
		
	}
		
}