<?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_deposit_activity_transaksi extends REST_Controller
{

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


	public function index_post()
	{
		date_default_timezone_set($this->mst_user_zona_waktu());

		//USER
		$mst_user_kode = $this->mst_user_kode();
		$mst_user_nama_lengkap = $this->mst_user_nama_lengkap();
		$mst_user_nomor_hp = $this->mst_user_nomor_hp();
		$mst_user_email = $this->mst_user_email();

		//DEPOSIT
		$mst_deposit_kode = $this->mst_deposit_kode();
		$trx_deposit_kode =  "DEPOSIT-" . strtoupper(substr(sha1(uniqid()), 0, 10)) . "-" . rand(0, 999) . "-" . date('Hms');
		$trx_deposit_tanggal = date('Y-m-d H:i:s');
		$trx_deposit_jumlah = str_replace(str_split('\\/:*?"<>|,.-+'), "", $this->trx_deposit_jumlah());
		$trx_deposit_keterangan = "Hai, " . $mst_user_nama_lengkap . ". isi saldo Arifah Pulsa dengan aman melalui salah satu payment gateway terbaik di indonesia";
		$trx_deposit_icon =  $this->config->item('icon_deposit');

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


		//TRIPAY
		$url = 'https://tripay.co.id/api-sandbox/transaction/create';

		$header = array(
			'Authorization: Bearer ' . $this->config->item('tripay_api_key'),
		);

		$params = [
			'method'         => $mst_deposit_kode,
			'merchant_ref'   => $trx_deposit_kode,
			'amount'         => (int) $trx_deposit_jumlah,
			'customer_name'  => $mst_user_nama_lengkap,
			'customer_email' => $mst_user_email,
			'customer_phone' => $mst_user_nomor_hp,
			'order_items'    => [
				[
					'sku'         => $trx_deposit_kode,
					'name'        => 'arifahpulsa',
					'price'       => (int) $trx_deposit_jumlah,
					'quantity'    => 1,
					'product_url' => '',
					'image_url'   => '',
				]
			],
			'expired_time' => (time() + (1 * 60 * 60)), // 24 jam
			'signature'    => hash_hmac('sha256', $this->config->item('tripay_merchant_kode') . $trx_deposit_kode . $trx_deposit_jumlah, $this->config->item('tripay_private_key'))
		];

		$json = http_build_query($params);
		$ch = curl_init();
		curl_setopt_array($ch, [
			CURLOPT_FRESH_CONNECT  => true,
			CURLOPT_URL            => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HEADER         => false,
			CURLOPT_HTTPHEADER     => $header,
			CURLOPT_FAILONERROR    => false,
			CURLOPT_POST           => true,
			CURLOPT_POSTFIELDS     => $json,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4
		]);
		$result = curl_exec($ch);
		curl_close($ch);

		$response = json_decode($result, true)['data'];
		if (!empty($response['reference'])) {
			$reference = $response['reference'];
			$payment_method = $response['payment_method'];
			$payment_name = str_replace(' (Customizable)', '', $response['payment_name']);
			$fee_customer = $response['fee_customer'];
			$pay_code = $response['pay_code'];
			$checkout_url = $response['checkout_url'];

			//INSERT KE tbl_trx_deposit
			$this->db->query("insert into tbl_trx_deposit (
				trx_deposit_kode, 
				trx_deposit_user_kode, 
				trx_deposit_tripay_reference, 
				trx_deposit_metode, 
				trx_deposit_tanggal, 
				trx_deposit_jumlah, 
				trx_deposit_admin,
				trx_deposit_channel,
				trx_deposit_va,
				trx_deposit_link,
				trx_deposit_keterangan, 
				trx_deposit_notasi, 
				trx_deposit_icon, 
				trx_deposit_rc, 
				trx_deposit_status) values (
				'$trx_deposit_kode', 
				'$mst_user_kode', 
				'$reference',
				'$payment_method',
				'$trx_deposit_tanggal', 
				'$trx_deposit_jumlah', 
				'$fee_customer',
				'$payment_name', 
				'$pay_code', 
				'$checkout_url', 
				'$trx_deposit_keterangan', 
				'Jika transaksi berhasil saldo kamu akan bertambah sejumlah Rp $trx_deposit_jumlah. Tekan bayar sekarang untuk melanjutkan pengisian saldo', 
				'$trx_deposit_icon', 
				'0', 
				'Pending')");

			//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_deposit_kode', 
				'$mst_user_kode', 
				'$trx_transaksi_kategori', 
				'$reference',
				'Isi saldo', 
				'$trx_deposit_jumlah' + '$fee_customer', 
				'$trx_deposit_keterangan',
				'Segera lakukan pembayaran', 
				'$trx_deposit_tanggal', 
				'$trx_deposit_icon', 
				'0', 
				'Pending')");

			//PANGGIL DEPOSIT
			$deposit = $this->db->query("SELECT * FROM tbl_trx_deposit 
									WHERE 
									trx_deposit_kode='$trx_deposit_kode' and 
									trx_deposit_user_kode='$mst_user_kode'");
			if ($deposit->num_rows() > 0) {
				foreach ($deposit->result() as $row) {
					$data['transaksi'][] = array(
						'trx_deposit_kode' => encrypt($row->trx_deposit_kode, $this->config->item('key')),
						'trx_deposit_tripay_reference' => encrypt($row->trx_deposit_tripay_reference, $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 {
				//GAGAL
				$sess["status"] = "22";
				$sess["pesan"] = "Transaksi tidak 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(array()), $keytoken)
				);
				echo json_encode($sess);
			}
		} else {
			//GAGAL
			$sess["status"] = "33";
			$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);
		}
	}

	private function formatNomorHp($mst_user_nomor_hp)
	{
		// kadang ada penulisan no hp 0811 239 345
		$mst_user_nomor_hp = str_replace(" ", "", $mst_user_nomor_hp);
		// kadang ada penulisan no hp (0274) 778787
		$mst_user_nomor_hp = str_replace("(", "", $mst_user_nomor_hp);
		// kadang ada penulisan no hp (0274) 778787
		$mst_user_nomor_hp = str_replace(")", "", $mst_user_nomor_hp);
		// kadang ada penulisan no hp 0811.239.345
		$mst_user_nomor_hp = str_replace(".", "", $mst_user_nomor_hp);

		// cek apakah no hp mengandung karakter + dan 0-9
		if (!preg_match('/[^+0-9]/', trim($mst_user_nomor_hp))) {
			// cek apakah no hp karakter 1-3 adalah +62
			if (substr(trim($mst_user_nomor_hp), 0, 3) == '+62') {
				$mst_user_nomor_hp = trim($mst_user_nomor_hp);
			}
			// cek apakah no hp karakter 1 adalah 0
			elseif (substr(trim($mst_user_nomor_hp), 0, 1) == '0') {
				$mst_user_nomor_hp = '+62' . substr(trim($mst_user_nomor_hp), 1);
			}
		}
		return $mst_user_nomor_hp;
	}


	private function mst_user_kode()
	{
		$input = decrypt($this->input->post("mst_user_kode", 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 {
				return $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();
		}
	}

	private function mst_user_nama_lengkap()
	{
		$input = decrypt($this->input->post("mst_user_nama_lengkap", 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 {
				return $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();
		}
	}

	private function mst_user_nomor_hp()
	{
		$input = decrypt($this->input->post("mst_user_nomor_hp", 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 {
				return $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();
		}
	}

	private function mst_user_email()
	{
		$input = decrypt($this->input->post("mst_user_email", 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 {
				return $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();
		}
	}

	private function mst_user_zona_waktu()
	{
		$input = decrypt($this->input->post("mst_user_zona_waktu", 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 {
				return $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();
		}
	}

	private function mst_deposit_kode()
	{
		$input = decrypt($this->input->post("mst_deposit_kode", 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 {
				return $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();
		}
	}

	private function trx_deposit_jumlah()
	{
		$input = decrypt($this->input->post("trx_deposit_jumlah", 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 {
				return $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();
		}
	}
}
