<?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://rest.local/tests";
		
		$secret = "o7lf5DUxSuPKtDjlbqc2VuZD9WjQ5qAZ";
		
		//$credSBY = [ "username"=>"pbmc_surabaya", "password"=>"pgcWfdwX3qEt9zaC" ];
		//$credDPS = [ "username"=>"pbmc_bali", "password"=>"J8e29XjLmDCFuQnk" ];
		
		$header = [
			'alg' => 'HS256', // HMAC SHA-256 algorithm
			'typ' => 'JWT'
		];

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

		$encodedHeader = base64UrlEncode(json_encode($header));
		$encodedPayload = base64UrlEncode(json_encode($payload));

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

		// Combine to create the JWT
		$jwt = "$encodedHeader.$encodedPayload.$encodedSignature";

		
		*/
		$header = http_build_query($header);
		$payload = http_build_query($payload);
		$signature = hash_hmac('sha256', "$header.$payload", $secret, true);
		$jwt = "$header.$payload.$signature<br/>";
		echo "JWT: $jwt\n";
		
		$client = \Config\Services::curlrequest();
		try { 
			$response = $client->request('GET', $TM_url, [
				"headers" => [
					"Accept" => "application/json",
					"Authorization" => "Bearer $jwt",
					"AppCode" => "2"
				],
				"body" => '',
				"verify" => false
			]);
			
            if ($response->getStatusCode() == 200) { 
				print_r($response);
            } else {
				print_r($response);
            }
			
        } catch (\Exception $e) {
            echo "Error: " . $e->getMessage();
        }
	}
	
	public function tests() {
		echo "<pre>";
		print_r($this);
		echo "</pre>";
	}
	
}