<?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_bpjs_model extends CI_Model {

	public function get_loop($context)
	{
		$url = '';
		$pengaturan = $this->db->select('*')->from('pengaturan')->get()->row();

		if(!isset($context['data'])) $context['data'] = array();

		$service_name = $context['service_name'];

		$row = 0;
		$max_row = 15;
		$loop = true;

		while ($loop) 
		{
			switch($service_name)
			{		
				case 'referensi_tindakan':
				$url = $pengaturan->bpjs_url_pcare."/tindakan/kdTkp/".$context['kdTkp']."/".$row."/".$max_row;
				break;

				case 'provider':
				$url = $pengaturan->bpjs_url_pcare."/provider/".$row."/15";
				break;

				case 'poli':
				$url = $pengaturan->bpjs_url_pcare."/poli/fktp/".$row."/15";
				break;

				case 'pendaftaran_provider':
				$url = $pengaturan->bpjs_url_pcare."/pendaftaran/tglDaftar/".$context['tglDaftar']."/".$row."/".$max_row;
				break;

				case 'obat_dpho':
				$url = $pengaturan->bpjs_url_pcare."/obat/dpho/".$context['keyword']."/".$row."/".$max_row;
				break;

				case 'diagnosa':
				$url = $pengaturan->bpjs_url_pcare."/diagnosa/".$context['keyword']."/".$row."/".$max_row;
				break;			

				case 'dokter':
				$url = $pengaturan->bpjs_url_pcare."/dokter/".$row."/".$max_row;
				break;
			}

			$execute_loop = $this->execute($url, 'GET', $context['data'], '');

			if($execute_loop['eror'] != 'warning')
			{
				if($execute_loop['metaData']['message'] == 'OK')
				{
					if($row == 0) 
					{
						$execute = $execute_loop;
					}
					else {

						$jml_data = count($execute['result']['list']);

						foreach ($execute_loop['result']['list'] as $key) 
						{
							$execute['result']['list'][$jml_data] = $key;

							$jml_data++;
						}
					}

					if(count($execute_loop['result']['list']) == $max_row)
					{
						$row = $row + $max_row;
						$max = $max_row + $max_row;
					} 
					else $loop = false;
				} 
				else 
				{
					$execute = $execute_loop;
					$loop = false;
				}
			} 
			else
			{
				$execute = $execute_loop;
				$loop = false;
			}
		}
		
		return $execute;
	}

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

		$service_name = $context['service_name']; 

		if(!isset($context['data'])) $context['data'] = array();

		switch($service_name)
		{			
			case 'poli':
			$url = $pengaturan->bpjs_url_pcare."/poli/fktp/0/15";
			break;

			case 'prognosa':
			$url = $pengaturan->bpjs_url_pcare."/alergi/prognosa";
			break;

			case 'alergi_obat':
			$url = $pengaturan->bpjs_url_pcare."/alergi/jenis/03";
			break;

			case 'alergi_udara':
			$url = $pengaturan->bpjs_url_pcare."/alergi/jenis/02";
			break;

			case 'alergi_makanan':
			$url = $pengaturan->bpjs_url_pcare."/alergi/jenis/01";
			break;

			case 'rujukan_khusus_2':
			$url = $pengaturan->bpjs_url_pcare."/spesialis/rujuk/khusus/".$context['kdKhusus']."/subspesialis/".$context['kdSubSpesialis']."/noKartu/".$context['noKartu']."/tglEstRujuk/".$context['tglEstRujuk'];
			break;

			case 'rujukan_khusus_1':
			$url = $pengaturan->bpjs_url_pcare."/spesialis/rujuk/khusus/".$context['kdKhusus']."/noKartu/".$context['noKartu']."/tglEstRujuk/".$context['tglEstRujuk'];
			break;
			
			case 'rujukan_subspesialis':
			$url = $pengaturan->bpjs_url_pcare."/spesialis/rujuk/subspesialis/".$context['kdSubSpesialis']."/sarana/".$context['kdSarana']."/tglEstRujuk/".$context['tglEstRujuk'];
			break;
			
			case 'referensi_khusus':
			$url = $pengaturan->bpjs_url_pcare."/spesialis/khusus";
			break;

			case 'sarana':
			$url = $pengaturan->bpjs_url_pcare."/spesialis/sarana";
			break;
			
			case 'subspesialis':
			$url = $pengaturan->bpjs_url_pcare."/spesialis/".$context['kdSpesialis']."/subspesialis";
			break;
			
			case 'spesialis':
			$url = $pengaturan->bpjs_url_pcare."/spesialis";
			break;
			
			case 'spesialis_khusus':
			$url = $pengaturan->bpjs_url_pcare."/spesialis/khusus";
			break;
			
			case 'peserta_kegiatan_kelompok':
			$url = $pengaturan->bpjs_url_pcare."/kelompok/peserta/".$context['eduId'];
			break;
			
			case 'kegiatan_kelompok':
			$url = $pengaturan->bpjs_url_pcare."/kelompok/kegiatan/".$context['bulan'];
			break;
			
			case 'club_prolanis':
			$url = $pengaturan->bpjs_url_pcare."/kelompok/club/".$context['kdJnsKelompok'];
			break;

			case 'status_pulang':
			$url = $pengaturan->bpjs_url_pcare."/statuspulang/rawatInap/false";
			break;
			
			case 'tindakan_by_kunjungan':
			$url = $pengaturan->bpjs_url_pcare."/tindakan/kunjungan/".$context['noKunjungan'];
			break;
			
			case 'peserta':
			$url = $pengaturan->bpjs_url_pcare."/peserta/".$context['jnsKartu']."/".$context['keyword'];
			break;
			
			case 'pendaftaran':
			$url = $pengaturan->bpjs_url_pcare."/pendaftaran/noUrut/".$context['noUrut']."/tglDaftar/".$context['tglDaftar'];
			break;

			case 'obat_by_kunjungan':
			$url = $pengaturan->bpjs_url_pcare."/obat/kunjungan/".$context['noKunjungan'];
			break;
			
			case 'mcu':
			$url = $pengaturan->bpjs_url_pcare."/mcu/kunjungan/".$context['noKunjungan'];
			break;
			
			case 'riwayat_kunjungan':
			$url = $pengaturan->bpjs_url_pcare."/kunjungan/peserta/".$context['noKartu'];
			break;
			
			case 'rujukan':
			$url = $pengaturan->bpjs_url_pcare."/kunjungan/rujukan/".$context['noKunjungan'];
			break;

			case 'kesadaran':
			$url = $pengaturan->bpjs_url_pcare."/kesadaran";
			break;

			case 'referensi_dokter_antrol':
			$url = $pengaturan->bpjs_url_antrol.'/ref/dokter/kodepoli/'.$context['kdPoli'].'/tanggal/'.$context['tgl'];
			break;
		}

		$execute = $this->execute($url, 'GET', $context['data'], '');
		
		return $execute;
	}

	public function add($context)
	{
		$url = '';
		$pengaturan = $this->db->select('*')->from('pengaturan')->get()->row();

		$service_name = $context['service_name'];

		switch($service_name)
		{			
			case 'pendaftaran':
			$url = $pengaturan->bpjs_url_pcare."/pendaftaran";
			break;
			
			case 'kunjungan':
			$url = $pengaturan->bpjs_url_pcare."/kunjungan/V1";
			break;
			
			case 'kirim_antrol':
			$url = $pengaturan->bpjs_url_antrol."/antrean/add";
			break;
			
			case 'update_antrol':
			$url = $pengaturan->bpjs_url_antrol."/antrean/panggil";
			break;
		}

		$execute = $this->execute($url, 'POST', $context['data'], '');
		
		return $execute;
	}

	public function edit($context)
	{
		$url = '';
		$pengaturan = $this->db->select('*')->from('pengaturan')->get()->row();

		$service_name = $context['service_name'];

		switch($service_name)
		{			
			case 'pendaftaran':
			$url = $pengaturan->bpjs_url_pcare."/pendaftaran";
			break;
			
			case 'kunjungan':
			$url = $pengaturan->bpjs_url_pcare."/kunjungan";
			break;
		}

		$execute = $this->execute($url, 'PUT', $context['data'], '');
		
		return $execute;
	}

	public function delete($context)
	{
		$url = '';
		$pengaturan = $this->db->select('*')->from('pengaturan')->get()->row();

		$service_name = $context['service_name'];

		switch($service_name)
		{			
			case 'pendaftaran':
			$url = $pengaturan->bpjs_url_pcare."/pendaftaran/peserta/".$context['noKartu']."/tglDaftar/".$context['tglDaftar']."/noUrut/".$context['noUrut']."/kdPoli/".$context['kdPoli'];
			break;

			case 'kunjungan':
			$url = $pengaturan->bpjs_url_pcare."/kunjungan/".$context['noKunjungan'];
			break;
		}

		$execute = $this->execute($url, "DELETE", $context['data'], '');
		
		return $execute;
	}

	public function execute($url, $type, $data, $type_content)
	{
		$pengaturan = $this->db->select('*')->from('pengaturan')->get()->row();

		$bpjs['url'] = $url;
		$bpjs['data'] = $data;

		if($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_pcare.':'.$pengaturan->bpjs_password_pcare.':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.''
			); 

			$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, $type);

			if(!empty($data)) 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><td></td></tr><tr><td style="font-size: 14px">klik tombol dibawah jika username & password Pcare berubah</td></tr><tr><td><a class="btn btn-default btn-sm" onclick="change_pcare();"><i class="fas fa-key"></i> Ganti Username & Password PCare</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'] = '<table width="100%"><tr><td><b>Gagal terhubung dengan BPJS! Cek koneksi internet</b></td><tr><td></td></tr><tr><td style="font-size: 14px">klik tombol dibawah jika username & password Pcare berubah</td></tr><tr><td><a class="btn btn-default btn-sm" onclick="change_pcare();"><i class="fas fa-key"></i> Ganti Username & Password PCare</i></td></tr></table>';
						$data['data'] = $bpjs;
					}
					else if($data['metaData']['code'] == '401')
					{
						$data['eror'] = 'warning';
						$data['pesan'] = '['.$data['metaData']['code'].'] '.$data['metaData']['message'];
						$data['data'] = json_encode($bpjs);
					}
					else
					{
						if($data['metaData']['message'] == 'PRECONDITION_FAILED')
						{
							$data['eror'] = 'warning';

							$data['pesan'] = 'Cek input data !<br>['.$data['metaData']['code'].'] '.$data['metaData']['message'];

							if(isset($data['response']))
							{
								if(is_array($data['response']))
								{
									foreach ($data['response'] as $key)
									{
										if(isset($key['field']))
										{
											$data['pesan'] .= '<br> ['.$key['field'].'] '.$key['message'];
										}
										else $data['pesan'] .= '<br>'.$key;						
									}
								}
								else 
								{
									$extract = $this->extract($key, $data['response']);

									if(is_array($extract))
									{
										foreach($extract as $key)
										{
											if(isset($key['field']))
											{
												$data['pesan'] .= '<br> ['.$key['field'].'] '.$key['message'];
											}
											else $data['pesan'] .= '<br>'.$key;						
										}
									}
									else $data['pesan'] .= '<br>'.$data['response'];
								}
							}

							$data['data'] = $bpjs;
						} 
						else {
							$data['eror'] = 'warning';
							$data['pesan'] = '['.$data['metaData']['code'].'] '.$data['metaData']['message'];
							$data['data'] = json_encode($bpjs);
						}
					}
				}					
				else 
				{
					$data['eror'] = 'warning';
					$data['pesan'] = 'Gagal terhubung dengan BPJS! response kosong';
					$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;		
	}

}	