<?php
defined('BASEPATH') or exit('No direct script access allowed');

require APPPATH . '/libraries/REST_Controller.php';
require APPPATH . '/libraries/Format.php';

use Restserver\Libraries\REST_Controller;

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");

class Api_pdam_activity_transaksi extends REST_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->helper(['jwt', 'authorization']);
		$this->methods['index_post']['limit_transaksi'] = 1;
	}

	private $str_mst_user_zona_waktu;
	private $str_mst_user_kode;
	private $str_trx_pdam_kode;
	private $str_trx_pdam_nomor;
	private $str_trx_pdam_kategori_kode;
	private $str_trx_pdam_kategori_nama;
	private $str_trx_pdam_segmen;
	private $str_trx_pdam_nama;
	private $str_trx_pdam_admin;
	private $str_trx_pdam_harga;
	private $str_trx_pdam_lembar_tagihan;
	private $str_trx_pdam_periode;
	private $str_trx_pdam_keterangan;
	private $str_trx_pdam_notasi;

	public function index_post()
	{
		$this->transaksi_pdam();

		//TIME ZONE
		date_default_timezone_set($this->str_mst_user_zona_waktu);

		//USER
		$mst_user_kode = $this->str_mst_user_kode;

		//TRANSAKSI
		$trx_pdam_kode =   $this->str_trx_pdam_kode;
		$trx_pdam_tanggal = date('Y-m-d H:i:s');
		$trx_pdam_nomor = $this->str_trx_pdam_nomor;
		$trx_pdam_kategori_kode = $this->str_trx_pdam_kategori_kode;
		$trx_pdam_kategori_nama = $this->str_trx_pdam_kategori_nama;
		$trx_pdam_nama = $this->str_trx_pdam_nama;
		$trx_pdam_segmen = $this->str_trx_pdam_segmen;
		$trx_pdam_admin = str_replace(str_split('\\/:*?"<>|,.-+'), "", $this->str_trx_pdam_admin);
		$trx_pdam_harga = str_replace(str_split('\\/:*?"<>|,.-+'), "", $this->str_trx_pdam_harga);
		$trx_pdam_total = $trx_pdam_admin + $trx_pdam_harga;
		$trx_pdam_lembar_tagihan = $this->str_trx_pdam_lembar_tagihan;
		$trx_pdam_periode = $this->str_trx_pdam_periode;
		$trx_pdam_keterangan = $this->str_trx_pdam_keterangan;
		$trx_pdam_notasi = $this->str_trx_pdam_notasi;
		$trx_pdam_icon = $this->config->item('icon_pdam');

		//KATEGORI TRANSAKSI
		$trx_transaksi_kategori =  $this->config->item('transaksi_pdam');

		//CEK SALDO
		$saldo = $this->db->query("SELECT * FROM tbl_mst_saldo WHERE 
									mst_saldo_user_kode='$mst_user_kode' and 
									mst_saldo_jumlah >= '$trx_pdam_total'");
		if ($saldo->num_rows() > 0) {
			//SALDO CUKUP
			//DIGIFLAZZ
			$url = $this->config->item('digiflazz_api_url');
			$header = array(
				'Content-Type: text/plain',
			);
			$data = array(
				'commands' => 'pay-pasca',
				'username' => $this->config->item('digiflazz_api_username'),
				'buyer_sku_code' => $trx_pdam_kategori_kode,
				'customer_no' => $trx_pdam_nomor,
				'ref_id' => $trx_pdam_kode,
				'testing' => $this->config->item('digiflazz_api_testing'),
				'sign' => md5($this->config->item('digiflazz_api_username') . $this->config->item('digiflazz_api_key') . $trx_pdam_kode)
			);
			$json = json_encode($data);
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
			curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			$result = curl_exec($ch);
			curl_close($ch);
			$response = json_decode($result, true)['data'];

			if (!empty($response['rc'])) {
				//DIGIFLAZZ
				$rc = $response['rc'];
				$status = $response['status'];
				$sn = $response['sn'];

				//TRANSAKSI SUKSES
				if ($rc == "03" || $rc == "00") {
					//INSERT KE tbl_trx_pdam
					$this->db->query("insert into tbl_trx_pdam (
								trx_pdam_kode, 
								trx_pdam_user_kode, 
								trx_pdam_kategori_kode,
								trx_pdam_kategori_nama,
								trx_pdam_nomor, 
								trx_pdam_nama, 
								trx_pdam_segmen, 
								trx_pdam_admin, 
								trx_pdam_harga,
								trx_pdam_lembar_tagihan,
								trx_pdam_periode,
								trx_pdam_meter_awal, 
								trx_pdam_meter_akhir, 
								trx_pdam_sn, 
								trx_pdam_keterangan, 
								trx_pdam_notasi,
								trx_pdam_tanggal, 
								trx_pdam_icon,
								trx_pdam_rc,
								trx_pdam_status) values (
								'$trx_pdam_kode', 
								'$mst_user_kode', 
								'$trx_pdam_kategori_kode',
								'$trx_pdam_kategori_nama',
								'$trx_pdam_nomor',
								'$trx_pdam_nama', 
								'$trx_pdam_segmen', 
								'$trx_pdam_admin', 
								'$trx_pdam_harga',
								'$trx_pdam_lembar_tagihan', 
								'$trx_pdam_periode',
								'-',
								'-',
								'$sn', 
								'$trx_pdam_keterangan', 
								'Transaksi masih pending, cek status transaksi secara berkala', 
								'$trx_pdam_tanggal', 
								'$trx_pdam_icon',
								'$rc',
								'$status')");

					//INSERT KE tbl_trx_transaksi
					$this->db->query("insert into tbl_trx_transaksi (
								trx_transaksi_kode, 
								trx_transaksi_user_kode, 
								trx_transaksi_kategori, 
								trx_transaksi_nomor, 
								trx_transaksi_nama, 
								trx_transaksi_jumlah,
								trx_transaksi_keterangan,
								trx_transaksi_notasi, 
								trx_transaksi_tanggal, 
								trx_transaksi_icon, 
								trx_transaksi_rc,
								trx_transaksi_status) values (
								'$trx_pdam_kode', 
								'$mst_user_kode', 
								'$trx_transaksi_kategori', 
								'$trx_pdam_nomor',
								'$trx_pdam_nama', 
								'$trx_pdam_total', 
								'-',
								'Transaksi masih pending, cek status transaksi secara berkala ',  
								'$trx_pdam_tanggal', 
								'$trx_pdam_icon', 
								'$rc', 
								'$status')");

					//UPDATE tbl_mst_saldo
					$this->db->query("UPDATE tbl_mst_saldo set 
									mst_saldo_jumlah=mst_saldo_jumlah - '$trx_pdam_total'
									where
									mst_saldo_user_kode='$mst_user_kode'");

					//PANGGIL BPJS
					$pulsa = $this->db->query("SELECT * FROM tbl_trx_pdam 
											WHERE 
											trx_pdam_kode='$trx_pdam_kode' and 
											trx_pdam_user_kode='$mst_user_kode'");
					if ($pulsa->num_rows() > 0) {
						foreach ($pulsa->result() as $row) {
							$data['transaksi'][] = array(
								'trx_pdam_kode' => encrypt($row->trx_pdam_kode, $this->config->item('key')),
							);
						}

						//BERHASIL
						$sess["status"] = "11";
						$sess["pesan"] = "Transaksi berhasil dan ditemukan. Silahkan laporkan pesan error tersebut ke customer service untuk menyelesaikan masalah kamu.";
						$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
						$sess['data'] = array(
							'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
							'value' =>  encrypt(json_encode($data), $keytoken)
						);
						echo json_encode($sess);
					} else {
						//BERHASIL TAPI GAGAL MEMANGGIL
						$sess["status"] = "22";
						$sess["pesan"] = "Transaksi berhasil dilakukan. Pergi ke riwayat transaksi untuk melihat detail transaksi kamu";
						$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
						$sess['data'] = array(
							'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
							'value' =>  encrypt(json_encode(array()), $keytoken)
						);
						echo json_encode($sess);
					}
				} else {
					//GAGAL
					$sess["status"] = "33";
					$sess["pesan"] = $rc . " Transaksi gagal. Silahkan laporkan pesan error tersebut ke customer service untuk menyelesaikan masalah kamu.";
					$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
					$sess['data'] = array(
						'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
						'value' =>  encrypt(json_encode(array()), $keytoken)
					);
					echo json_encode($sess);
				}
			} else {
				//GAGAL
				$sess["status"] = "34";
				$sess["pesan"] = "Transaksi gagal. Silahkan laporkan pesan error tersebut ke customer service untuk menyelesaikan masalah kamu.";
				$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
				$sess['data'] = array(
					'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
					'value' =>  encrypt(json_encode(array()), $keytoken)
				);
				echo json_encode($sess);
			}
		} else {
			//SALDO TIDAK CUKUP
			$sess["status"] = "35";
			$sess["pesan"] = "Saldo kamu tidak cukup. Pastikan saldo kamu cukup sebelum melakukan transaksi";
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
		}
	}


	private function transaksi_pdam()
	{

		$input = decrypt($this->input->post("transaksi_pdam", true), $this->config->item('key'));
		$token = AUTHORIZATION::generateToken($input);
		try {
			$data = AUTHORIZATION::validateToken($token);
			if ($data === false) {
				$sess["status"] = "004";
				$sess["pesan"] = $this->config->item('error_parameter');
				$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
				$sess['data'] = array(
					'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
					'value' =>  encrypt(json_encode(array()), $keytoken)
				);
				echo json_encode($sess);
				exit();
			} else {
				$array = explode(".....", $data);
				$mst_transaksi = "";
				foreach ($array as $item) {
					$itemArray = explode(":", $item);
					$key = decrypt(trim($itemArray[0]), $this->config->item('key'));
					$value = trim($itemArray[1]);

					//AMBIL KEY TRANSAKSI
					if ($key == 'mst_transaksi') {
						$mst_transaksi = $value;
					}

					//GENERATE POST SELAIN KEY TRANSAKSI
					if ($key != 'mst_transaksi') {
						$this->transaksi_pdam_request($key, $mst_transaksi, $value);
					}
				}
			}
		} catch (Exception $e) {
			$sess["status"] = "004";
			$sess["pesan"] = $this->config->item('error_parameter');
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
			exit();
		}
	}

	private function transaksi_pdam_request($key, $mst_transaksi, $value)
	{
		$transaksi = decrypt($mst_transaksi, $this->config->item('key'));
		$input = decrypt($value, $transaksi);
		$token = AUTHORIZATION::generateToken($input);
		try {
			$data = AUTHORIZATION::validateToken($token);
			if ($data === false) {
				$sess["status"] = "004";
				$sess["pesan"] = $this->config->item('error_parameter');
				$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
				$sess['data'] = array(
					'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
					'value' =>  encrypt(json_encode(array()), $keytoken)
				);
				echo json_encode($sess);
				exit();
			} else {
				if ($key == 'mst_user_kode') {
					return $this->str_mst_user_kode = $data;
				}

				if ($key == 'mst_user_zona_waktu') {
					return $this->str_mst_user_zona_waktu = $data;
				}

				if ($key == 'trx_pdam_kode') {
					return $this->str_trx_pdam_kode = $data;
				}

				if ($key == 'trx_pdam_nomor') {
					return $this->str_trx_pdam_nomor = $data;
				}

				if ($key == 'trx_pdam_kategori_kode') {
					return $this->str_trx_pdam_kategori_kode = $data;
				}

				if ($key == 'trx_pdam_kategori_nama') {
					return $this->str_trx_pdam_kategori_nama = $data;
				}

				if ($key == 'trx_pdam_nama') {
					return $this->str_trx_pdam_nama = $data;
				}

				if ($key == 'trx_pdam_segmen') {
					return $this->str_trx_pdam_segmen = $data;
				}

				if ($key == 'trx_pdam_admin') {
					return $this->str_trx_pdam_admin = $data;
				}

				if ($key == 'trx_pdam_harga') {
					return $this->str_trx_pdam_harga = $data;
				}

				if ($key == 'trx_pdam_lembar_tagihan') {
					return $this->str_trx_pdam_lembar_tagihan = $data;
				}

				if ($key == 'trx_pdam_periode') {
					return $this->str_trx_pdam_periode = $data;
				}

				if ($key == 'trx_pdam_keterangan') {
					return $this->str_trx_pdam_keterangan = $data;
				}

				if ($key == 'trx_pdam_notasi') {
					return $this->str_trx_pdam_notasi = $data;
				}
			}
		} catch (Exception $e) {
			$sess["status"] = "004";
			$sess["pesan"] = $this->config->item('error_parameter');
			$keytoken = strtoupper(substr(sha1(uniqid()), 0, 16));;
			$sess['data'] = array(
				'token' =>  encrypt($keytoken, $this->config->item('keytoken')),
				'value' =>  encrypt(json_encode(array()), $keytoken)
			);
			echo json_encode($sess);
			exit();
		}
	}
}
