<?php

require_once '_asset/LZCompressor/LZString.php';
require_once '_asset/LZCompressor/LZReverseDictionary.php';
require_once '_asset/LZCompressor/LZData.php';
require_once '_asset/LZCompressor/LZUtil.php';
require_once '_asset/LZCompressor/LZUtil16.php';
require_once '_asset/LZCompressor/LZContext.php';

class Api_icare_model extends CI_Model {

	public function get_content($param)
	{
		$pengaturan = $this->db->select('*')->from('pengaturan')->get()->row();

		$bpjs['url'] = $pengaturan->bpjs_url_icare;

		$bpjs['data'] = array('param' => $param);

		if($bpjs['url'] != '')
		{
			date_default_timezone_set('UTC');
			$tStamp          		= strval(time()-strtotime('1970-01-01 00:00:00'));
			$signature        		= hash_hmac('sha256', $pengaturan->bpjs_cons_id.'&'.$tStamp, $pengaturan->bpjs_secret_key, true);
			$encodedSignature 		= base64_encode($signature);
			$encodedAuthorization 	= base64_encode($pengaturan->bpjs_username_icare.':'.$pengaturan->bpjs_password_icare.':095');

			$bpjs['headers'] = array(
				'Accept: application/json',
				'X-cons-id: '.$pengaturan->bpjs_cons_id.'',
				'X-timestamp: '.$tStamp.'',
				'X-signature: '.$encodedSignature.'',
				'user_key: '.$pengaturan->bpjs_user_key.'',
				'X-authorization: Basic '.$encodedAuthorization.'',
				'Content-Type: application/json'
			); 

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $bpjs['url']);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $bpjs['headers']);
			curl_setopt($ch, CURLOPT_TIMEOUT, 60);  
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($bpjs['data']));

			$bpjs['content'] = curl_exec($ch);
			$err = curl_error($ch);

			$data = json_decode($bpjs['content'], true);
			curl_close($ch); 

			$key = $pengaturan->bpjs_cons_id.$pengaturan->bpjs_secret_key.$tStamp;

			if(empty($data)) 
			{
				$data['eror'] = 'warning';
				$data['pesan'] = '<table width="100%"><tr><td><b>Gagal terhubung dengan BPJS! Cek koneksi internet</b></td><tr><tr><td style="font-size: 14px">klik tombol dibawah jika username & password ICARE berubah</td></tr><tr><td><a class="btn btn-default btn-sm" onclick="change_icare();"><i class="fas fa-key"></i> Ganti Username & Password ICare</i></td></tr></table>';
				$data['data'] = $bpjs;
			}
			else
			{
				if(isset($data['metadata'])) $data['metaData'] = $data['metadata'];

				if(!empty($data['metaData']))
				{
					if($data['metaData']['code'] == '200' || $data['metaData']['code'] == '201')
					{
						if(isset($data['response']))
						{
							if($data['response'] != '')
							{
								$data['result'] = $this->extract($key, $data['response']);
							} 
							else $data['result'] = '';
						} 			

						$data['eror'] = 'success';
						$data['pesan'] = 'Berhasil';
						$data['data'] = $data;				
					}
					else if($data['metaData']['code'] == '50000')
					{
						$data['eror'] = 'warning';
						$data['pesan'] = '['.$data['metaData']['code'].'] '.$data['metaData']['message'].'<br><table width="100%"><tr><td><a class="btn btn-default btn-sm" onclick="change_icare();"><i class="fas fa-key"></i> Ganti Username & Password ICare</i></td></tr></table>';
						$data['data'] = $bpjs;
					}
					else
					{
						$data['eror'] = 'warning';
						$data['pesan'] = '['.$data['metaData']['code'].'] '.$data['metaData']['message'].'<br><table width="100%"><tr><td><a class="btn btn-default btn-sm" onclick="change_icare();"><i class="fas fa-key"></i> Ganti Username & Password ICare</i></td></tr></table>';
						$data['data'] = json_encode($bpjs);
					}
				}					
				else 
				{
					$data['eror'] = 'warning';
					$data['pesan'] = '['.$data['metaData']['code'].'] '.$data['metaData']['message'].'<br><table width="100%"><tr><td><a class="btn btn-default btn-sm" onclick="change_icare();"><i class="fas fa-key"></i> Ganti Username & Password ICARE</i></td></tr></table>';
					$data['data'] = json_encode($bpjs);
				}		
			}
		}
		else 
		{
			$data['eror'] = 'warning';
			$data['pesan'] = 'Gagal terhubung dengan BPJS! URL kosong';
		}

		if($data['eror'] == 'warning') $this->db->insert('_log_error', ['model' => 'Api_bpjs_model', 'detail' => $data['pesan']]);
		
		return $data;    	
	}

	function extract($key, $response)
	{
		$encrypt_method = 'AES-256-CBC';
		$key_hash = hex2bin(hash('sha256', $key));       
		$iv = substr(hex2bin(hash('sha256', $key)), 0, 16);
		$output = openssl_decrypt(base64_decode($response), $encrypt_method, $key_hash, OPENSSL_RAW_DATA, $iv);

		$result = json_decode(LZCompressor\LZString::decompressFromEncodedURIComponent($output), true); 

		return $result;
	}

	//--------------------------------------------------------------------------------------------

	public function get_notif($name_function)
	{
		$eror = $this->db->error();

		if($eror['code'] == 0){
			$notif = array('eror'=>'success', 'pesan'=>$name_function.' data berhasil');
		} else if($eror['code'] == 1062){
			$notif = array('eror'=>'warning', 'pesan'=>'Username sudah terdaftar');
		} else $notif = array('eror'=>'warning', 'pesan'=>"Terjadi kesalahan. Mohon hubungi (septiaputra@gmail.com)<br>$eror[code]: $eror[message]");	

		return $notif;		
	}

}	