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

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

	private $str_mst_user_zona_waktu;
	private $str_mst_user_kode;
	private $str_mst_user_nama_lengkap;
	private $str_mst_user_nomor_hp;
	private $str_trx_transfer_tujuan_kode;
	private $str_trx_transfer_tujuan_nomor;
	private $str_trx_transfer_tujuan_nama;
	private $str_trx_transfer_admin;
	private $str_trx_transfer_jumlah;
	private $str_trx_transfer_keterangan;

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

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

		//USER
		$mst_user_kode = $this->str_mst_user_kode;
		$mst_user_nama_lengkap = $this->str_mst_user_nama_lengkap;
		$mst_user_nomor_hp = $this->str_mst_user_nomor_hp;

		//TRANSAKSI
		$trx_transfer_kode =  "TRANSFER-" . strtoupper(substr(sha1(uniqid()), 0, 10)) . "-" . rand(0, 999) . "-" . date('Hms');
		$trx_transfer_tanggal = date('Y-m-d H:i:s');
		$trx_transfer_tujuan_kode = $this->str_trx_transfer_tujuan_kode;
		$trx_transfer_tujuan_nomor = $this->str_trx_transfer_tujuan_nomor;
		$trx_transfer_tujuan_nama = $this->str_trx_transfer_tujuan_nama;
		$trx_transfer_admin = str_replace(str_split('\\/:*?"<>|,.-+'), "", $this->str_trx_transfer_admin);
		$trx_transfer_jumlah = str_replace(str_split('\\/:*?"<>|,.-+'), "", $this->str_trx_transfer_jumlah);
		$trx_transfer_total = $trx_transfer_jumlah + $trx_transfer_admin;
		$trx_transfer_keterangan = $this->str_trx_transfer_keterangan;
		$trx_transfer_icon = $this->config->item('icon_transfer');

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

		//CEK USER
		$user_kode = $this->db->query("SELECT * FROM tbl_mst_user WHERE mst_user_nomor_hp='$trx_transfer_tujuan_nomor' and mst_user_kode='$mst_user_kode'");
		if ($user_kode->num_rows() > 0) {
			//TIDAK BISA TRANSFER KE NOMOR SENDIRI
			$sess["status"] = "33";
			$sess["pesan"] = "Tidak bisa transfer ke nomor sendiri, pastikan nomor tujuan transfer kamu sudah benar!";
			$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 {
			//CEK SALDO
			$saldo = $this->db->query("SELECT * FROM tbl_mst_saldo WHERE 
									mst_saldo_user_kode='$mst_user_kode' and 
									mst_saldo_jumlah >= '$trx_transfer_total'");
			if ($saldo->num_rows() > 0) {
				//SALDO CUKUP
				//INSERT KE tbl_trx_transfer PENGIRIM
				$this->db->query("insert into tbl_trx_transfer (
							trx_transfer_kode, 
							trx_transfer_user_kode, 
							trx_transfer_tujuan_kode, 
							trx_transfer_tujuan_nomor,
							trx_transfer_tujuan_nama,
							trx_transfer_admin,
							trx_transfer_jumlah, 
							trx_transfer_tanggal, 
							trx_transfer_keterangan,
							trx_transfer_icon, 
							trx_transfer_rc,
							trx_transfer_status) values (
							'$trx_transfer_kode', 
							'$mst_user_kode', 
							'$trx_transfer_tujuan_kode', 
							'$trx_transfer_tujuan_nomor',
							'$trx_transfer_tujuan_nama', 
							'$trx_transfer_admin', 
							'$trx_transfer_jumlah', 
							'$trx_transfer_tanggal', 
							'$trx_transfer_keterangan', 
							'$trx_transfer_icon',
							'00',
							'Sukses')");

				//INSERT KE tbl_trx_transfer PENERIMA
				$this->db->query("insert into tbl_trx_transfer (
							trx_transfer_kode, 
							trx_transfer_user_kode, 
							trx_transfer_tujuan_kode, 
							trx_transfer_tujuan_nomor,
							trx_transfer_tujuan_nama,
							trx_transfer_admin,
							trx_transfer_jumlah, 
							trx_transfer_tanggal, 
							trx_transfer_keterangan,
							trx_transfer_icon, 
							trx_transfer_rc,
							trx_transfer_status) values (
							'$trx_transfer_kode', 
							'$trx_transfer_tujuan_kode', 
							'$mst_user_kode', 
							'$mst_user_nomor_hp',
							'$mst_user_nama_lengkap', 
							'$trx_transfer_admin', 
							'$trx_transfer_jumlah', 
							'$trx_transfer_tanggal', 
							'$trx_transfer_keterangan', 
							'$trx_transfer_icon',
							'00',
							'Sukses')");

				//INSERT KE tbl_trx_transaksi PENGIRIM
				$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_transfer_kode', 
							'$mst_user_kode', 
							'$trx_transaksi_kategori', 
							'$trx_transfer_tujuan_nomor',
							'Transfer ke $trx_transfer_tujuan_nama', 
							'$trx_transfer_total', 
							'$trx_transfer_keterangan',
							'',  
							'$trx_transfer_tanggal', 
							'$trx_transfer_icon', 
							'00', 
							'Sukses')");

				//INSERT KE tbl_trx_transaksi PENERIMA
				$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_transfer_kode', 
							'$trx_transfer_tujuan_kode', 
							'$trx_transaksi_kategori', 
							'$mst_user_nomor_hp',
							'Transfer dari $mst_user_nama_lengkap', 
							'$trx_transfer_total', 
							'$trx_transfer_keterangan',
							'',  
							'$trx_transfer_tanggal', 
							'$trx_transfer_icon', 
							'00', 
							'Sukses')");

				//INSERT KE tbl_trx_pendapatan
				$this->db->query("insert into tbl_trx_pendapatan (
								trx_pendapatan_kode, 
								trx_pendapatan_user_kode, 
								trx_pendapatan_kategori, 
								trx_pendapatan_jumlah, 
								trx_pendapatan_tanggal) values (
								'$trx_transfer_kode', 
								'$mst_user_kode', 
								'$trx_transaksi_kategori',
								'$trx_transfer_admin', 
								'$trx_transfer_tanggal')");

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


				//UPDATE tbl_mst_saldo PENERIMA
				$this->db->query("UPDATE tbl_mst_saldo set 
								mst_saldo_jumlah=mst_saldo_jumlah + '$trx_transfer_jumlah'
								where
								mst_saldo_user_kode='$trx_transfer_tujuan_kode'");

				//KIRIM NOTIF KE PENERIMA
				//PANGGIL USER
				$user = $this->db->query("SELECT * FROM tbl_mst_user WHERE mst_user_kode='$trx_transfer_tujuan_kode'");
				if ($user->num_rows() > 0) {
					foreach ($user->result() as $row) {
						$mst_user_firebase = $row->mst_user_firebase;
					}
					$title = "Transfer masuk!";
					$body = $mst_user_nama_lengkap . " baru saja mengirim saldo ke kamu";
					firebase_notification($title, $body, $mst_user_firebase);
				}


				//PANGGIL TRANSFER
				$transfer = $this->db->query("SELECT * FROM tbl_trx_transfer WHERE 
											trx_transfer_kode='$trx_transfer_kode' and 
											trx_transfer_user_kode='$mst_user_kode'");
				if ($transfer->num_rows() > 0) {
					foreach ($transfer->result() as $row) {
						$data['transaksi'][] = array(
							'trx_transfer_kode' => encrypt($row->trx_transfer_kode, $this->config->item('key')),
						);
					}

					//BERHASIL
					$sess["status"] = "11";
					$sess["pesan"] = "Transaksi berhasil dan ditemukan";
					$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 {
				//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_transfer()
	{

		$input = decrypt($this->input->post("transaksi_transfer", 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_transfer_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_transfer_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_nama_lengkap') {
					return $this->str_mst_user_nama_lengkap = $data;
				}

				if ($key == 'mst_user_nomor_hp') {
					return $this->str_mst_user_nomor_hp = $data;
				}

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

				if ($key == 'trx_transfer_tujuan_kode') {
					return $this->str_trx_transfer_tujuan_kode = $data;
				}

				if ($key == 'trx_transfer_tujuan_nomor') {
					return $this->str_trx_transfer_tujuan_nomor = $data;
				}

				if ($key == 'trx_transfer_tujuan_nama') {
					return $this->str_trx_transfer_tujuan_nama = $data;
				}

				if ($key == 'trx_transfer_keterangan') {
					return $this->str_trx_transfer_keterangan = $data;
				}

				if ($key == 'trx_transfer_jumlah') {
					return $this->str_trx_transfer_jumlah = $data;
				}

				if ($key == 'trx_transfer_admin') {
					return $this->str_trx_transfer_admin = $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();
		}
	}
}
