<?php	
date_default_timezone_set("Asia/Bangkok");
class JWT
{
	/**
	 * Decodes a JWT string into a PHP object.
	 *
	 * @param string      $jwt    The JWT
	 * @param string|null $key    The secret key
	 * @param bool        $verify Don't skip verification process 
	 *
	 * @return object      The JWT's payload as a PHP object
	 * @throws UnexpectedValueException Provided JWT was invalid
	 * @throws DomainException          Algorithm was not provided
	 * 
	 * @uses jsonDecode
	 * @uses urlsafeB64Decode
	 */
	public static function decode($jwt, $key = null, $verify = true)
	{
		$tks = explode('.', $jwt);
		if (count($tks) != 3) {
			throw new UnexpectedValueException('Wrong number of segments');
		}
		list($headb64, $bodyb64, $cryptob64) = $tks;
		if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) {
			throw new UnexpectedValueException('Invalid segment encoding');
		}
		if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) {
			throw new UnexpectedValueException('Invalid segment encoding');
		}
		$sig = JWT::urlsafeB64Decode($cryptob64);
		
		if ($verify) {
			if (empty($header->alg)) {
				throw new DomainException('Empty algorithm');
			}
			if ($sig != JWT::sign("$headb64.$bodyb64", $key, $header->alg)) {
				throw new UnexpectedValueException('Signature verification failed');
			}
		}
		return $payload;
	}
	/**
	 * Converts and signs a PHP object or array into a JWT string.
	 *
	 * @param object|array $payload PHP object or array
	 * @param string       $key     The secret key
	 * @param string       $algo    The signing algorithm. Supported
	 *                              algorithms are 'HS256', 'HS384' and 'HS512'
	 *
	 * @return string      A signed JWT
	 * @uses jsonEncode
	 * @uses urlsafeB64Encode
	 */
	public static function encode($payload, $key, $algo = 'HS256')
	{
		$header = array('typ' => 'JWT', 'alg' => $algo);
		$segments = array();
		$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
		$segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
		$signing_input = implode('.', $segments);
		$signature = JWT::sign($signing_input, $key, $algo);
		$segments[] = JWT::urlsafeB64Encode($signature);
		return implode('.', $segments);
	}
	/**
	 * Sign a string with a given key and algorithm.
	 *
	 * @param string $msg    The message to sign
	 * @param string $key    The secret key
	 * @param string $method The signing algorithm. Supported
	 *                       algorithms are 'HS256', 'HS384' and 'HS512'
	 *
	 * @return string          An encrypted message
	 * @throws DomainException Unsupported algorithm was specified
	 */
	public static function sign($msg, $key, $method = 'HS256')
	{
		$methods = array(
			'HS256' => 'sha256',
			'HS384' => 'sha384',
			'HS512' => 'sha512',
		);
		if (empty($methods[$method])) {
			throw new DomainException('Algorithm not supported');
		}
		return hash_hmac($methods[$method], $msg, $key, true);
	}
	/**
	 * Decode a JSON string into a PHP object.
	 *
	 * @param string $input JSON string
	 *
	 * @return object          Object representation of JSON string
	 * @throws DomainException Provided string was invalid JSON
	 */
	public static function jsonDecode($input)
	{
		$obj = json_decode($input);
		if (function_exists('json_last_error') && $errno = json_last_error()) {
			JWT::_handleJsonError($errno);
		} else if ($obj === null && $input !== 'null') {
			throw new DomainException('Null result with non-null input');
		}
		return $obj;
	}
	/**
	 * Encode a PHP object into a JSON string.
	 *
	 * @param object|array $input A PHP object or array
	 *
	 * @return string          JSON representation of the PHP object or array
	 * @throws DomainException Provided object could not be encoded to valid JSON
	 */
	public static function jsonEncode($input)
	{
		$json = json_encode($input);
		if (function_exists('json_last_error') && $errno = json_last_error()) {
			JWT::_handleJsonError($errno);
		} else if ($json === 'null' && $input !== null) {
			throw new DomainException('Null result with non-null input');
		}
		return $json;
	}
	/**
	 * Decode a string with URL-safe Base64.
	 *
	 * @param string $input A Base64 encoded string
	 *
	 * @return string A decoded string
	 */
	public static function urlsafeB64Decode($input)
	{
		$remainder = strlen($input) % 4;
		if ($remainder) {
			$padlen = 4 - $remainder;
			$input .= str_repeat('=', $padlen);
		}
		return base64_decode(strtr($input, '-_', '+/'));
	}
	/**
	 * Encode a string with URL-safe Base64.
	 *
	 * @param string $input The string you want encoded
	 *
	 * @return string The base64 encode of what you passed in
	 */
	public static function urlsafeB64Encode($input)
	{
		return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
	}
	/**
	 * Helper method to create a JSON error.
	 *
	 * @param int $errno An error number from json_last_error()
	 *
	 * @return void
	 */
	private static function _handleJsonError($errno)
	{
		$messages = array(
			JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
			JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
			JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
		);
		throw new DomainException(
			isset($messages[$errno])
			? $messages[$errno]
			: 'Unknown JSON error: ' . $errno
		);
	}
}
//=========================================
//class JWT
$transaksi = new JWT();
$key = "TokenJWT_BMI_ICT";

include_once 'include/global.php';
$db=pDatabase::getInstance();

$response = array(
	'ERR' => '30',//96
	'METHOD' => '',
	'DESCRIPTION' => 'Token tidak ada',
	'CUSTNAME' => '',
	'DESCRIPTION2' => '',
	'BILL' => '0', //+ 2000
	'CCY' => '360'
);

if(!isset($_REQUEST['token'])){
	echo JWT::encode($response, $key);
	exit;
}

$tagihans = array();

try {
    $decoded = $transaksi->decode($_REQUEST['token'], $key, array('HS256'));
} catch (Exception $e) {
    $response['DESCRIPTION']="JWT ".$e->getMessage();
	echo JWT::encode($response, $key);
	exit;
}

if(!isset($decoded)){
	$response['DESCRIPTION']="Error Decode";
	echo JWT::encode($response, $key);
	exit;
}
	
$decoded_array = (array) $decoded;

$METHOD =  $decoded_array[METHOD];
if(!isset($METHOD)){
	$response['DESCRIPTION']="METHOD Tidak ditemukan";
	echo JWT::encode($response, $key);
	exit;
}

$response['METHOD']=$METHOD;

if($METHOD=='INQUIRY'){
	if(!isset($decoded_array[VANO])){
		$response['DESCRIPTION']="Salah format message";
		echo JWT::encode($response, $key);
		exit;
	}
	
	$nova=$decoded_array[VANO];
	if(strlen($nova)!=16){
		$response['DESCRIPTION']="Format no VA Salah";
		echo JWT::encode($response, $key);
		exit;
	}
	$statusnomor=false;
	$namapembayaran="-";
	$deskripsi="-";
	$jumlah=0;
	$namauser="";
	
	$noakhirva=substr($nova, 12);
	
	if($noakhirva=="0001"){
		$query="select id,no_va_uangsaku,nama from tb_siswa where no_va_uangsaku=? ";
		$rss=$db->loadAssoc($query,array($nova));
		if(!isset($rss['id'])){
			$response['ERR']="15";
			$response['DESCRIPTION']="Nomor Identitas Pembayaran tidak ditemukan ";
			echo JWT::encode($response, $key);
			exit;
		}
		
		$statusnomor=true;
		$namapembayaran="Uang Saku ".$rss['nama'];
		$deskripsi="Penitipan Uang Saku Santri ".$rss['nama'];
		$namauser=$rss['nama'];
	}else if($noakhirva=="0002"){
		$query="select id,no_va_tabungan,nama,nis from tb_siswa where no_va_tabungan=? and nis is not null";
		$rss=$db->loadAssoc($query,array($nova));
		
		if(!isset($rss['id'])){
			$response['ERR']="15";
			$response['DESCRIPTION']="Nomor Identitas Pembayaran tidak ditemukan ";
			echo JWT::encode($response, $key);
			exit;
		}
		
		$statusnomor=true;
		$namapembayaran="Tabungan ".$rss['nama'];
		$deskripsi="Tabungan Santri ".$rss['nama'];
		$namauser=$rss['nama'];
	}else{
		$query="select t1.id,t1.idjenis,t1.no_va,t1.ta,t1.bulan,t2.nama,
				t1.jenis_pembayaran,t1.jumlah_pembayaran,
				t1.total
				from tb_pembayaran_siswa_tagihan as t1
			inner join tb_siswa as t2 on t1.idsiswa=t2.id
			where t1.jumlah_pembayaran<t1.total and t1.no_va=?";
			
		$rss=$db->loadAssoc($query,array($decoded_array[VANO]));
		if(!isset($rss['id'])){
			$response['ERR']="15";
			$response['DESCRIPTION']="Nomor Identitas Pembayaran tidak ditemukan di basis data Billing Provider";
			echo JWT::encode($response, $key);
			exit;
		}
		
		$statusnomor=true;
		$namapembayaran=$rss['jenis_pembayaran']."/".$rss['bulan']." ".$rss['nama'];
		$deskripsi=$rss['jenis_pembayaran']." ".$rss['bulan']."/".$rss['ta'];
		$jumlah=$rss['total']-$rss['jumlah_pembayaran'];
		$jumlah=number_format($jumlah,0,'','')*100;
	}
	
	if($statusnomor){
		$response['ERR']="00";
		$response['DESCRIPTION']=$namapembayaran;
		$response['DESCRIPTION2']=$deskripsi;
		$response['CUSTNAME']=$namapembayaran;
		$response['BILL']=$jumlah;
		$response['CCY']="";
		echo JWT::encode($response, $key);
		exit;
	}else{
		$response['DESCRIPTION']="Terjadi kesalahan";
		echo JWT::encode($response, $key);
		exit;
	}
	
}else if($METHOD=='PAYMENT'){
	if(!isset($decoded_array[VANO]) || !isset($decoded_array[PAYMENT]) || !isset($decoded_array[BILL])){
		$response['DESCRIPTION']="Salah format message";
		echo JWT::encode($response, $key);
		exit;
	}
	
	$nova=$decoded_array[VANO];
	if(strlen($nova)!=16){
		$response['DESCRIPTION']="Format no VA Salah";
		echo JWT::encode($response, $key);
		exit;
	}
	$statusnomor=false;
	$namapembayaran="-";
	$deskripsi="-";
	$jumlah=0;
	$namauser="";
	$idtagihan=0;
	$tahunajaran=0;
	$bulan=0;
	$idjenis=0;
	$idsiswa=0;
	$jenispembayaran="";
	$nis="";
	
	$BILL =  $decoded_array[BILL]; //nominal tagihan diambil saat inquiry
	$PAYMENT =  $decoded_array[PAYMENT];
	if($PAYMENT<=0){
		$response['DESCRIPTION']="Jumlah pembayaran salah ";
		echo JWT::encode($response, $key);
		exit;
	}
	
	$noakhirva=substr($nova, 12);
	
	if($noakhirva=="0001"){
		$query="select id,no_va_uangsaku,nama,nis from tb_siswa where no_va_uangsaku=? ";
		$rss=$db->loadAssoc($query,array($nova));
		if(!isset($rss['id'])){
			$response['ERR']="15";
			$response['DESCRIPTION']="Nomor Identitas Pembayaran tidak ditemukan ";
			echo JWT::encode($response, $key);
			exit;
		}
		
		$statusnomor=true;
		$namapembayaran="Uang Saku ".$rss['nama'];
		$deskripsi="Penitipan Uang Saku Santri ".$rss['nama'];
		$namauser=$rss['nama'];
		$idsiswa=$rss['id'];
		$jenispembayaran="Penitipan Uang Saku";
		$nis=$rss['nis'];
	}else if($noakhirva=="0002"){
		$query="select id,no_va_tabungan,nama,nis from tb_siswa where no_va_tabungan=? and nis is not null";
		$rss=$db->loadAssoc($query,array($nova));
		if(!isset($rss['id'])){
			$response['ERR']="15";
			$response['DESCRIPTION']="Nomor Identitas Pembayaran tidak ditemukan ";
			echo JWT::encode($response, $key);
			exit;
		}
		
		$statusnomor=true;
		$namapembayaran="Tabungan ".$rss['nama'];
		$deskripsi="Tabungan Santri ".$rss['nama'];
		$namauser=$rss['nama'];
		$idsiswa=$rss['id'];
		$jenispembayaran="Tabungan Santri";
		$nis=$rss['nis'];
	}else{
		$query="select t1.id,t1.idjenis,t1.idtipe,
				t1.no_va,t1.ta,t1.bulan,
				t1.idsiswa,t2.nama,
				t1.jenis_pembayaran,t1.jumlah_pembayaran,
				t1.total
				from tb_pembayaran_siswa_tagihan as t1
			inner join tb_siswa as t2 on t1.idsiswa=t2.id
			where t1.jumlah_pembayaran<t1.total and t1.no_va=?";
			
		$rss=$db->loadAssoc($query,array($decoded_array[VANO]));
		if(!isset($rss['id'])){
			$response['ERR']="15";
			$response['DESCRIPTION']="Nomor Identitas Pembayaran tidak ditemukan di basis data Billing Provider";
			echo JWT::encode($response, $key);
			exit;
		}
		
		$jumlah=$rss['total']-$rss['jumlah_pembayaran'];
		if($rss['idtipe']==2 || $rss['idtipe']==3){
			if($PAYMENT!=$jumlah){
				$response['ERR']="15";
				$response['DESCRIPTION']="Jumlah payment tidak sesuai tagihan";
				echo JWT::encode($response, $key);
				exit;
			}
		}else{
			if($PAYMENT>$jumlah){
				$response['ERR']="15";
				$response['DESCRIPTION']="Jumlah payment lebih besar dari tagihan";
				echo JWT::encode($response, $key);
				exit;
			}
		}
		
		$statusnomor=true;
		$idtagihan=$rss['id'];
		$tahunajaran=$rss['ta'];
		$bulan=$rss['bulan'];
		$idjenis=$rss['idjenis'];
		$idsiswa=$rss['idsiswa'];
		$jenispembayaran=$rss['jenis_pembayaran'];
	}
	
	if($statusnomor){
		$tanggalsekarang=date("Y-m-d H:i:s");
		$tanggalnow=date("Y-m-d");
		$tanggalsekarangindo=date("d/m/Y H:i:s");
		if(isset($decoded_array[TRXDATE])){
			$tanggalsekarang=$decoded_array[TRXDATE];
		}
		
		if($noakhirva=="0001"){
			$datain=[
				"tanggal"=>$tanggalsekarang,
				"iduser"=>0,
				"idsiswa"=>$idsiswa,
				"mode"=>1,
				"jenis"=>1,
				"jumlah"=>$PAYMENT,
				"keterangan"=>"VA Uang Saku",
				"idtipe"=>2
			];
			
			$rsp=$db->insert("tb_uangsaku",$datain);
			if($rsp!=1){
				$response['ERR']="12";
				$response['DESCRIPTION']="Declined - Transaksi salah";
				echo JWT::encode($response, $key);
				exit;
			}
		}else if($noakhirva=="0002"){
			$datain=[
				"tanggal_input"=>$tanggalsekarang,
				"tanggal"=>$tanggalnow,
				"no_rek"=>$nis,
				"id_user"=>0,
				"jenis"=>0,
				"jumlah"=>$PAYMENT,
				"keterangan"=>"VA Tabungan",
				"idtipe"=>2
			];
			
			$rsp=$db->insert("tb_tabungan",$datain);
			
			if($rsp!=1){
				$response['ERR']="12";
				$response['DESCRIPTION']="Declined - Transaksi salah";
				echo JWT::encode($response, $key);
				exit;
			}
		}else{
			$datain=[
				"idtagihan"=>$idtagihan,
				"iduser"=>0,
				"tanggal"=>$tanggalsekarang,
				"ta"=>$tahunajaran,
				"bulan"=>$bulan,
				"idjenis"=>$idjenis,
				"idsiswa"=>$idsiswa,
				"jumlah"=>$PAYMENT,
				"modebayar"=>2
			];
			$rsp=$db->insert("tb_pembayaran_siswa",$datain);
			
			if($rsp!=1){
				$response['ERR']="12";
				$response['DESCRIPTION']="Declined - Transaksi salah";
				echo JWT::encode($response, $key);
				exit;
			}
		}
		
		$datasms=$db->gethpourtu($idsiswa);
		if(isset($datasms['id']) && $datasms['hp']!=""){
			$rstpl=array();
			if($noakhirva=="0001"){
				$query="select * from tb_template_sms where kode='01'";
				$rstpl=$db->loadAssoc($query);
			}else if($noakhirva=="0002"){
				$query="select * from tb_template_sms where kode='02'";
				$rstpl=$db->loadAssoc($query);
			}else{
				$query="select * from tb_template_sms where kode='04'";
				$rstpl=$db->loadAssoc($query);
			}
			
			if(!isset($rstpl['id'])) return false;
			
			$dataps=array();
			$dataps=array("namasantri"=>$datasms['nama'],"nis"=>$datasms['nis'],"nisn"=>$datasms['nisn'],
				"nisn"=>$datasms['nisn'],"jumlah"=>number_format($PAYMENT,'0',',','.'),"tanggal"=>$tanggalsekarangindo,
				"jenispembayaran"=>$jenispembayaran);
			
			
			$obj=(object) array("data"=>$rstpl['template']);
			$pesan=$db->renderdata($obj,$dataps);
			$kode=$db->gentoken(64);
			
			$datakirim=[
				"kode"=>$kode,
				"tanggal"=>$tanggalsekarang,
				"iduser"=>0,
				"judul"=>$jenispembayaran,
				"tujuan"=>$datasms['hp'],
				"pesan"=>$pesan,
				"status"=>0
			];
			
			$rss=$db->insert("tb_kirimsms",$datakirim,1);
			
			if($rss>0){
				shell_exec("nohup python ".HOMEDIR."py/kirimsms.py $rss > /dev/null 2>&1 &");
			}
		}
		
		$response['ERR']="00";
		$response['DESCRIPTION']="Payment Success";
		$response['BILL']=$PAYMENT;
		$response['CCY']="";
		echo JWT::encode($response, $key);
		exit;
	}else{
		$response['DESCRIPTION']="Terjadi kesalahan";
		echo JWT::encode($response, $key);
		exit;
	}
	
}	
?>