<?php

function get_themes()
{
	$_this = &get_Instance();
	$conf = site_url('asset/themes');
	if ($conf <> '') {
		return $conf;
	} else {
		return false;
	}
}

function get_myconf($var)
{
	$_this = &get_Instance();
	$conf = $_this->config->item($var);
	if ($conf <> '') {
		return $conf;
	} else {
		return false;
	}
}

function set_myconf($var, $value)
{
	$_this = &get_Instance();
	return $_this->config->set_item($var, $value);
}

function validate_input($str = '', $params = array())
{
	$_this = &get_Instance();

	$name = isset($params['name']) ? $params['name'] : 'undefined';

	if (isset($params['required'])) {
		if ($params['required']) {
			if ($str == '') {
				error('kolom ' . $name . ' belum di isi');
			}
		}
	}

	if ($str) {
		if (isset($params['type'])) {
			if ($params['type']) {
				if (($params['type'] == 'string') || ($params['type'] == 'varchar') || ($params['type'] == 'text')) {
					if (!is_string($str)) {
						error('kolom ' . $name . ' harus berisi tipe ' . $params['type']);
					}
				}

				if (($params['type'] == 'number') || ($params['type'] == 'float') || ($params['type'] == 'int') || ($params['type'] == 'integer')) {
					if (!is_numeric($str)) {
						error('kolom ' . $name . ' harus berisi tipe ' . $params['type']);
					}
				}

				if (($params['type'] == 'date')) {
					if (!(preg_match("/^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$/", getSQLDate($str)))) {
						error('kolom ' . $name . ' invalid ' . $params['type'] . ' format');
					}

					$year = substr(getSQLDate($str), 0, 4); // returns "2019"
					$month = substr(getSQLDate($str), 4, 2); // returns "12"
					$day = substr(getSQLDate($str), 6, 2); // returns "31"
					if (!checkdate($month, $day, $year)) {
						error('params ' . $name . ' invalid ' . $params['type'] . ' format' . ' y:' . $year . ' m:' . $month . ' d:' . $day);
					}
				}
			}
		}
	}

	if (isset($params['maxlength'])) {
		if ($params['maxlength']) {
			if (strlen($str) > $params['maxlength']) {
				error('kolom ' . $name . ' melebihi panjang maximum ' . $params['maxlength']);
			}
		}
	}

	if (isset($params['default'])) {
		if ($str == '') {
			$str = $params['default'];
		}
	}

	return $str;
}

if (!function_exists('error')) {
	function error($err,$error_code='400',$error_header='error')
	{
		$request = $_REQUEST;
		$_this = &get_Instance();
		if(!is_production())
		{
			$_this->result['request']['method'] 	= $_this->input->method();
			$_this->result['request']['data'] 		= $request;
		}
		$_this->result['statusCode']			= 0;
		$_this->result['message']				= $err;
		header('Content-Type: application/json');
		header("HTTP/1.1 ".$error_code." ".$error_header);
		echo json_encode($_this->result);
		exit;
	}
}

if (!function_exists('success')) {
	function success($msg='',$success_code='200',$success_header='OK')
	{
		$request = $_REQUEST;
		$_this = &get_Instance();
		if(!is_production())
		{
			$_this->result['request']['method'] 	= $_this->input->method();
			$_this->result['request']['data'] 		= $request;
		}
		$_this->result['statusCode']			= 1;
		$_this->result['message']				= $msg;
		header('Content-Type: application/json');
		header("HTTP/1.1 ".$success_code." ".$success_header);
		echo json_encode($_this->result);
	}
}

if (!function_exists('match_key')) {
	function match_key($data, $key)
	{
		$data_upper = trim(strtoupper($data));
		$key_upper = trim(strtoupper($key));
		$pos_start = strrpos($data_upper, $key_upper);
		$result = $data;
		//$mark_start = '<span style="background-color: rgb(178, 179, 0);">';
		//$mark_start = '<span class="marked">';
		$mark_start = '<b><span style="color:red;">';
		$mark_end = '</span></b>';
		if ($pos_start or $key_upper == substr($data_upper, 0, strlen($key_upper))) {
			$pos_end = $pos_start + strlen($key_upper);
			$result = substr_replace($data, $mark_start, $pos_start, 0);
			$result = substr_replace($result, $mark_end, $pos_end + strlen($mark_start), 0);
		}

		return $result;
	}
}
if (!function_exists('text2num')) {
	function text2num($text = '0')
	{
		$result = str_replace(",", "", $text);
		$result = $result ? $result : '0';
		return $result;
	}
}

//decode
if (!function_exists('encode')) {
	function encode($str = '')
	{
		$result = base64_encode($str);
		$result = base64_encode($result);
		//$result = strtr($result, '+/', '-_');
		return $result;
	}
}
if (!function_exists('decode')) {
	function decode($str = '')
	{
		$result = base64_decode($str);
		$result = base64_decode($result);
		return $result;
	}
}

// check privilage user
if (!function_exists('check_priv')) {
	function check_priv($priv = false)
	{
		$_this = &get_Instance();

		$_this->load->model('utilities/operator_priv_model');
		$hasil = 0;
		$where = array();
		$where['tbl.fid_operator'] = $_this->session->userdata('id_operator');
		if ($priv) {
			$where['prv.kode'] = $priv;
		}
		$_this->operator_priv_model->set_where($where);
		$hasil = ($_this->operator_priv_model->count() > 0);
		return $hasil;
	}
}

// check file poto is exist
if (!function_exists('check_profile_pict')) {
	function check_profile_pict($id, $path = false)
	{
		$path = $path ? $path . '/' : '';
		$foto = 'files/foto/' . $path . $id . '.jpg';
		if (!file_exists($foto))
			$foto = base_url() . 'files/foto/nopict.jpg';
		else
			$foto = base_url() . $foto;
		return $foto;
	}
}
// check file poto is exist
if (!function_exists('thausand_spar')) {
	function thausand_spar($num)
	{
		return number_format($num, 2, '.', ',');;
	}
}
// check num_to_aplha is exist
if (!function_exists('num_to_aplha')) {
	function num_to_aplha($data)
	{
		$alphabet =   array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
		$alpha_flip = array_flip($alphabet);
		if ($data <= 25) {
			return $alphabet[$data];
		} elseif ($data > 25) {
			$dividend = ($data + 1);
			$alpha = '';
			$modulo = '';
			while ($dividend > 0) {
				$modulo = ($dividend - 1) % 26;
				$alpha = $alphabet[$modulo] . $alpha;
				$dividend = floor((($dividend - $modulo) / 26));
			}
			return $alpha;
		}
	}
}

// check alpha_to_num is exist
if (!function_exists('alpha_to_num')) {
	function alpha_to_num($data)
	{
		$alphabet = array(
			'a', 'b', 'c', 'd', 'e',
			'f', 'g', 'h', 'i', 'j',
			'k', 'l', 'm', 'n', 'o',
			'p', 'q', 'r', 's', 't',
			'u', 'v', 'w', 'x', 'y',
			'z'
		);
		$alpha_flip = array_flip($alphabet);
		$return_value = -1;
		$length = strlen($data);
		for ($i = 0; $i < $length; $i++) {
			$return_value +=
				($alpha_flip[$data[$i]] + 1) * pow(26, ($length - $i - 1));
		}
		return $return_value;
	}
}

if (!function_exists('get_month_name')) {
	function get_month_name($month_id = 0, $type = 1)
	{
		// jika 1 Short, 2 Full
		$bulan = array();
		$bulan[1][1] = 'JAN';
		$bulan[1][2] = 'JANUARI';
		$bulan[2][1] = 'FEB';
		$bulan[2][2] = 'FEBRUARI';
		$bulan[3][1] = 'MAR';
		$bulan[3][2] = 'MARET';
		$bulan[4][1] = 'APR';
		$bulan[4][2] = 'APRIL';
		$bulan[5][1] = 'MAY';
		$bulan[5][2] = 'MAY';
		$bulan[6][1] = 'JUN';
		$bulan[6][2] = 'JUNE';
		$bulan[7][1] = 'JUL';
		$bulan[7][2] = 'JULY';
		$bulan[8][1] = 'AUG';
		$bulan[8][2] = 'AUGUST';
		$bulan[9][1] = 'SEP';
		$bulan[9][2] = 'SEPTEMBER';
		$bulan[10][1] = 'OCT';
		$bulan[10][2] = 'OCTOBER';
		$bulan[11][1] = 'NOV';
		$bulan[11][2] = 'NOVEMBER';
		$bulan[12][1] = 'DEC';
		$bulan[12][2] = 'DECEMBER';

		return $bulan[$month_id][$type];
	}
}

function jml_minggu($tgl_awal, $tgl_akhir)
{
	$detik = 24 * 3600;
	$tgl_awal = strtotime($tgl_awal);
	$tgl_akhir = strtotime($tgl_akhir);

	$minggu = 0;
	for ($i = $tgl_awal; $i < $tgl_akhir; $i += $detik) {
		if (date("w", $i) == "0") {
			$minggu++;
		}
	}
	return $minggu;
}

function getWeekDates($date, $start_date, $end_date)
{
	$previous_week = strtotime("0 week +1 day");
	$start_week = strtotime("last sunday midnight", $previous_week);
	$end_week = strtotime("next saturday", $start_week);

	$week = date('W', strtotime($date));
	$year = date('Y', strtotime($date));
	// $from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week

	$from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week

	if ($from < $start_date)
		$from = $start_date;
	$to = date("Y-m-d", strtotime("{$year}-W{$week}-7"));   //Returns the date of sunday in week

	if ($to > $end_date)
		$to = $end_date;

	if ($from != $to)
		echo "Start Date-->" . $from . "End Date -->" . $to . "<br>"; //Output : Start Date-->2012-09-03 End Date-->2012-09-09
}

function GenTransNumber($compcode = '', $tgl = '')
{
	$sqldate = getSQLDate($tgl);
	$date = DateTime::createFromFormat("Ymd", $sqldate);
	$day = $date->format("d");
	$month = $date->format("m");
	$year = $date->format("Y");
	// echo $year;
	$hari = '';
	$bulan = '';
	$tahun = '';
	$numbfix = '';
	if ($day <= 9) {
		for ($i = 1; $i <= 9; $i++) {
			if ($day == $i)
				$hari =  $i;
		}
	}
	$y = 2010;
	$m = 0;
	$d = 9;
	foreach (range('A', 'Z') as $char) {
		$m++;
		$y++;
		$d++;
		if ($y == $year) {
			$tahun = $char;
		}

		if ($m == $month) {
			$bulan = $char;
		}

		if ($d == $day) {
			$hari = $char;
		}


		$numbfix = $compcode . $tahun . $bulan . $hari;
	}
	return $numbfix;
}

if (!function_exists('quotedstr')) {
	function quotedstr($str)
	{
		return "'" . $str . "'";
	}
}

if (!function_exists('time_elapsed_string')) {
	function time_elapsed_string($datetime, $full = false)
	{
		$now = new DateTime;
		$ago = new DateTime($datetime);
		$diff = $now->diff($ago);

		$diff->w = floor($diff->d / 7);
		$diff->d -= $diff->w * 7;

		$string = array(
			'y' => 'tahun',
			'm' => 'bulan',
			'w' => 'minggu',
			'd' => 'hari',
			'h' => 'jam',
			'i' => 'menit',
			's' => 'detik',
		);

		foreach ($string as $k => &$v) {
			if ($diff->$k) {
				$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? ' ' : '');
			} else {
				unset($string[$k]);
			}
		}

		if (!$full) $string = array_slice($string, 0, 1);
		return $string ? implode(', ', $string) . ' yang lalu' : 'baru saja';
	}
}

function random_color_part()
{
	return str_pad(dechex(mt_rand(0, 255)), 2, '0', STR_PAD_LEFT);
}

function random_color()
{
	return random_color_part() . random_color_part() . random_color_part();
}

function getImageList($id, $type)
{
	$_this = &get_Instance();
	$_this->load->model('main/image_upload_model');
	$url = base_url();
	$list_files = array();
	$_this->image_upload_model->set_order(array('orderBy' => 'ASC'));
	$_this->image_upload_model->set_where(array('foreignId' => $id, 'imageType' => $type));
	$getFU		= $_this->image_upload_model->get_list();
	if ($getFU->num_rows() > 0) {
		foreach ($getFU->result_array() as $key => $row) {
			$list_files[$key]['idImages'] = $row['idImages'];
			$list_files[$key]['source'] = $url . '' . $row['path'] . '/' . $row['serverName'];
			$list_files[$key]['options']['type'] = 'local';
			$list_files[$key]['options']['file']['name'] = $row['serverNameWithoutExt'];
			$list_files[$key]['options']['file']['size'] = $row['size'];
			$list_files[$key]['options']['file']['type'] = $row['type'];
			$list_files[$key]['options']['metadata']['poster'] = $list_files[$key]['source'];
		}
	}

	return $list_files;
}

function getInputs()
{
	$_this = &get_Instance();
	$input_method = $_this->input->method();
	$request = $_REQUEST;
	$inputs = array();
	if ($input_method == 'get') {
		$inputs = $_this->input->get();
	} else if ($input_method == 'post') {
		$inputs = $_this->input->post();
	} else {
		$inputs = $request;
	}

	return $inputs;
}

function getImagePath($img_type)
{
	$produk_folder = 'images/'.$img_type;
	if (!file_exists($produk_folder)) {
		mkdir($produk_folder);
		// mkdir($produk_folder, 0777, true);
		// chmod($produk_folder, $permit);
	}
	return $produk_folder;
}

function globalRemoveImages($foreign_id, $img_type)
{
	$_this = &get_Instance();
	$_this->load->model('image_upload_model');
	$get_image	= $_this->image_upload_model->get(array(
		'foreignId' => $foreign_id, 'imageType' => $img_type
	));
	$get_image_row = $get_image;
	// echo $_this->db->last_query();
	$delete = $_this->image_upload_model->delete(array('idImages' => $get_image_row['idImages']));

	$full_image_path = getImagePath($img_type) . '/' . $get_image_row['serverName'];
	// echo $full_image_path;
	if (file_exists($full_image_path)) unlink($full_image_path);
}

function getCurrencyRate($currencyCode)
{
	$currencyRate = 1;
	$_this = &get_Instance();

	$qry = $_this->db->query('SELECT "currencyRate" FROM "currencyRate" WHERE "upper"(currency)= upper('.quotedStr($currencyCode).') ORDER BY "rateDate" DESC limit 1');
	if($qry->num_rows() === 1)
	{
		$get_curr = $qry->row_array();
		$currencyRate = $get_curr['currencyRate'];
	}
	return $currencyRate;
}

function getLocation($warehouse,$business_unit)
{
	$location_code = '';
	$_this = &get_Instance();

	$qry = $_this->db->query('SELECT "locationCode" FROM wms."location" WHERE "warehouseCode"= '.quotedStr($warehouse).' AND "businessUnitCode" = '.quotedStr($business_unit).' ');
	if($qry->num_rows() === 1)
	{
		$get_location = $qry->row_array();
		$location_code = $get_location['locationCode'];
	}
	return $location_code;
}

function getMenuBoxed()
{
	$_this = &get_Instance();

	$uri_string 				= preg_replace('/[^a-z0-9]/i', '_', (uri_string()));
	$_this->db->where('lower(url) = ' . quotedstr($uri_string) . '');
	$_this->db->where('am.isActive = 1');
	$_this->db->where('am.menuType = 1');
	$_this->db->where('am.idMenu IN 
							(SELECT fidMenu
									FROM msOperatorAccess
									WHERE fidOperator = ' . $_this->session->userdata('idOperator') . ')');
	$_this->db->order_by('orderBy', 'ASC');
	$get_parent = $_this->db->get('Menu am');
	$menu_parent = array();
	$menu_child_list = array();
	if (($get_parent->num_rows() > 0) && ($uri_string != '')) {
		$menu_parent = $get_parent->row_array();
		$id_menu = $menu_parent['idMenu'];
	} else {
		$id_menu = 0;
	}
	$_this->db->where('am.fidMenu = ' . $id_menu . '');
	$_this->db->where('am.isActive = 1');
	$_this->db->where('am.menuType = 1');
	$_this->db->where('am.idMenu IN 
								(SELECT fidMenu
										FROM msOperatorAccess
										WHERE fidOperator = ' . $_this->session->userdata('idOperator') . ')');
	$_this->db->order_by('orderBy', 'ASC');
	$get_child = $_this->db->get('Menu am');

	if ($get_child->num_rows() > 0) {
		$menu_child_list = $get_child->result_array();
	}
	$default_menu_url	= 'main/menu_boxed';
	$data = array(
		'content' => $default_menu_url, 'title'	=>	'Settings', 'uri_string'	=>	$uri_string, 'menu_child_list'	=>	$menu_child_list
	);
	$_this->load->view('tpl', $data);
}

function show_not_allowed()
{
	$_this = &get_Instance();
	$_this->load->view('tpl',array('content'=>'not_allowed_content'));
	return;
}

function form_header($header_type = 0, $data = array())
{
	$form_template_dir = 'form_template';
	$_this = &get_Instance();
	$form_view = $form_template_dir.'/header_'.$header_type;
	$_this->load->view($form_view,$data);
	return;
}

function array_to_string_list($arr_value)
{
	$str_value = '';
	if(is_array($arr_value))
	{
		if(count($arr_value)>0)
		{
			$str_value = '';
			foreach ($arr_value as $key => $value)
			{
				if($key!=0)
				{
					$str_value .= ',';
				}
				$str_value .= quotedStr($value);
			}
		}
	}
	return $str_value;
}
function array_to_list($arr_value)
{
	$str_value = '';
	if(is_array($arr_value))
	{
		if(count($arr_value)>0)
		{
			$str_value = '';
			foreach ($arr_value as $key => $value)
			{
				if($key!=0)
				{
					$str_value .= ',';
				}
				$str_value .= $value;
			}
		}
	}
	return $str_value;
}

function negative_to_parentheses($numb)
{
	if($numb<0)
	{
		$numb = $numb*-1;
		return '('.number_format($numb).')';
	}else{
		return number_format($numb);
	}
}

function getBankCashAccountCode($bankAccountCode,$businessUnitCode)
{
	$accountCode = '';
	$_this = &get_Instance();

	$qry = $_this->db->query('SELECT "accountCode" FROM "facc"."bankCashAccount" WHERE "upper"("bankAccountCode")= upper('.quotedStr($bankAccountCode).') AND "upper"("businessUnitCode")= upper('.quotedStr($businessUnitCode).')');
	if($qry->num_rows() === 1)
	{
		$get_account = $qry->row_array();
		$accountCode = $get_account['accountCode'];
	}
	return $accountCode;
}

function getAccountName($accountCode)
{
	$accountName = '';
	$_this = &get_Instance();

	$qry = $_this->db->query('SELECT "accountName" FROM "facc"."coa" WHERE "upper"("accountCode")= upper('.quotedStr($accountCode).')' );
	if($qry->num_rows() === 1)
	{
		$get_account = $qry->row_array();
		$accountName = $get_account['accountName'];
	}
	return $accountName;
}

function getAttachmentUploadPath()
{
	return 'upload/attachment/';
}

function getQrUploadPath()
{
	return 'upload/qr_code/';
}

function generate_qr($text)
{
	$_this = &get_Instance();

	$_this->load->library('ciqrcode');
	header("Content-Type: image/png");
	$params['data'] = $text;
	$_this->ciqrcode->generate($params);
}

function qr_link($qr_no)
{
	$_this = &get_Instance();
	$_this->load->library('ciqrcode');

	$config['imagedir']     = './'.getQrUploadPath(); //direktori penyimpanan qr code
	$config['cacheable']    = false; //boolean, the default is true
	/*
	$config['cachedir']     = './assets/'; //string, the default is application/cache/
	$config['errorlog']     = './assets/'; //string, the default is application/logs/
	$config['quality']      = true; //boolean, the default is true
	$config['size']         = '1024'; //interger, the default is 1024
	$config['black']        = array(224,255,255); // array, default is array(255,255,255)
	$config['white']        = array(70,130,180); // array, default is array(0,0,0)
	$_this->ciqrcode->initialize($config);
	*/

	$image_name=encode($qr_no).'.png'; //buat name dari qr code sesuai dengan nip

	$params['data'] = $qr_no; //data yang akan di jadikan QR CODE
	$params['level'] = 'H'; //H=High
	$params['size'] = 10;
	$params['savename'] = FCPATH.$config['imagedir'].$image_name; //simpan image QR CODE ke folder assets/images/
	$_this->ciqrcode->generate($params); // fungsi untuk generate QR CODE

	echo base_url().getQrUploadPath().$image_name;
}

function formatKB($kbytes, $precision = 2) { 
	$units = array('KB', 'MB', 'GB', 'TB'); 

	$kbytes = max($kbytes, 0); 
	$pow = floor(($kbytes ? log($kbytes) : 0) / log(1024)); 
	$pow = min($pow, count($units) - 1); 

	// Uncomment one of the following alternatives
	$kbytes /= pow(1024, $pow);
	// $kbytes /= (1 << (10 * $pow)); 

	return round($kbytes, $precision) . ' ' . $units[$pow]; 
}

function convertToObject($array) {
	$object = new stdClass();
	foreach ($array as $key => $value) {
			if (is_array($value)) {
					$value = convertToObject($value);
			}
			$object->$key = $value;
	}
	return $object;
}



function getAccountCategory($accountCode)
{
	$_this = &get_Instance();
	$_this->load->model('finance/bank_cash_account_model');

	$businessUnitCode = $_this->session->userdata('businessUnitCode');

	$where = array();
	$where['bankAccountCode'] = $accountCode;
	$where['businessUnitCode'] = $businessUnitCode;
	$data = $_this->bank_cash_account_model->get($where);
	return $data;
}

function generate_barcode($txt_code = '', $show_text = false)
{
	$encoded_txt_code = encode($txt_code);

	$_this = &get_instance();

	$_this->load->library('Zend');
	$_this->zend->load('Zend/Barcode');
	$file = Zend_Barcode::draw('code128', 'image', array('text' => $txt_code, 'drawText' => $show_text), array());
	$directory_barcode = './assets/img/barcode/';
	$image_file = "{$directory_barcode}{$encoded_txt_code}.png";
	$full_link = base_url()."assets/img/barcode/{$encoded_txt_code}.png";
	imagepng($file, $image_file);

	return $full_link;
}

function get_operator_by_id($id=0)
{
	$_this = &get_Instance();
	$_this->load->model('master/operator_model');

	$where = array();
	$where['idOperator'] = $id?:0;
	$data = $_this->operator_model->get($where);
	return $data;
}


function get_unit_bisnis_by_code($code=0)
{
	$_this = &get_Instance();
	$_this->load->model('master/business_unit_model');

	$where = array();
	$where['businessUnitCode'] = $code?:'';
	$data = $_this->business_unit_model->get($where);
	return $data;
}

function get_list_dept_privilege()
{
	$_this = &get_Instance();
	$id = $_this->session->userdata('idOperator')?:0;
	$data = get_operator_by_id($id);
	return $data['deptListPrivilege'];
}

function have_dept_privilege()
{
	$my_privilege = get_list_dept_privilege();
	return ($my_privilege=='')?0:1;
}

function is_production()
{
	return (strtolower(ENVIRONMENT)==='production')?true:false;
}


function sendFirebaseNotification($params = array())
{
		$image_default		= 'http://elshop.elcorps.com/api_url/asset/img/mobile_assets/launcher_icon.png';
		$token 				= $params['token'];
		$title 				= $params['title'];
		$body 				= $params['body'];
		$request 			= isset($params['request'])?$params['request']:array();
		$subtitle 			= isset($params['subtitle'])?$params['subtitle']:"";
		$click_action 		= isset($params['click_action'])?$params['click_action']:'FLUTTER_NOTIFICATION_CLICK';
		// $image 				= $params['image']?$params['image']:$image_default;
		$api_access_key 	= get_myconf('firbase_api_access_key');
		
		unset($request['deviceToken']);
		unset($request['title']);
		unset($request['body']);

		$payload = array(
			'subtitle'	=> 'ini adalah sub title',
			'click_action'	=> $click_action
		);
		 $msg = array
		(
			'body' 	=> $body,
			'title'	=> $title,
			'click_action'	=> $click_action,
			'title_loc_key'	=> 'TEST_DATA_LOC_KEY'
		);
		$fields = array
		(
			'to'		=> $token,
			'notification'	=> $msg,
			'data'	=> $request
		);
		$headers = array
		(
			'Authorization: key=' . $api_access_key,
			'Content-Type: application/json'
		);
		$old_fcm_url = 'https://fcm.googleapis.com/fcm/send';
		$new_fcm_url = 'https://fcm.googleapis.com/v1/projects/elshop-eca46/messages:send';
		#Send Reponse To FireBase Server	
		$ch = curl_init();
		curl_setopt( $ch,CURLOPT_URL,  $old_fcm_url);
		curl_setopt( $ch,CURLOPT_POST, true );
		curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
		curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
		curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
		$result = curl_exec($ch );
		
		curl_close( $ch );
		$result = json_decode($result,TRUE);
		$result_formatted = json_encode($result);
		
		return $result_formatted;
		// echo "success:<br>";
}

function updateStatusCashDeposit($id_bank_reconsile_detail,$verifiedBy)
{
	$_this = &get_Instance();
	$_this->load->model('finance/bank_reconsile_detail_model');
	$_this->load->model('finance/bank_reconsile_model');

	$data_detail = $_this->bank_reconsile_detail_model->get(array('idBankReconsileDetail'=>$id_bank_reconsile_detail));

	if($data_detail['idBankReconsileDetail']!='')
	{
		$where_bank = array();
		$where_bank['storeCode'] = $data_detail['storeCode'];
		$where_bank['transDate'] = $data_detail['transDate'];
		$where_bank['businessUnitCode'] = $data_detail['businessUnitCode'];
		//get all cash deposit
		$where_all = $where_bank;
		$where_all['ncCode'] = '000';
		$_this->bank_reconsile_detail_model->set_where($where_all);
		$count_all_cash = $_this->bank_reconsile_detail_model->count();
		// get all cash deposit posted
		$where_posted = $where_bank;
		$where_posted['ncCode'] = '000';
		$where_posted['tranStatus'] = 1;
		$_this->bank_reconsile_detail_model->set_where($where_posted);
		$count_posted_cash = $_this->bank_reconsile_detail_model->count();
		if($count_all_cash != $count_posted_cash)
		{
			// update header status cash posted
			$data_header['cashDepositStatus'] = 1;
			$data_header['verifiedBy'] = $verifiedBy;
			$_this->db->where($where_bank);
			$_this->db->update('facc.bankReconsile', $data_header);
		} else 
		if($count_all_cash == $count_posted_cash)
		{
			// update header status cash posted
			$data_header['cashDepositStatus'] = 9;
			$data_header['verifiedBy'] = $verifiedBy;
			$_this->db->where($where_bank);
			$_this->db->update('facc.bankReconsile', $data_header);
		}
	}
}

function updateStatusTransferDeposit($id_bank_reconsile_detail,$verifiedBy)
{
	$_this = &get_Instance();
	$_this->load->model('finance/bank_reconsile_detail_model');
	$_this->load->model('finance/bank_reconsile_model');

	$data_detail = $_this->bank_reconsile_detail_model->get(array('idBankReconsileDetail'=>$id_bank_reconsile_detail));

	if($data_detail['idBankReconsileDetail']!='')
	{
		$where_bank = array();
		$where_bank['storeCode'] = $data_detail['storeCode'];
		$where_bank['transDate'] = $data_detail['transDate'];
		$where_bank['businessUnitCode'] = $data_detail['businessUnitCode'];
		//get all transfer deposit
		$where_all = $where_bank;
		$where_all['left("ncCode",1) =\'1\' AND "ncCode" <> \'150\''] = null;
		$_this->bank_reconsile_detail_model->set_where($where_all);
		$count_all_cash = $_this->bank_reconsile_detail_model->count();
		// get all transfer posted
		$where_posted = $where_bank;
		$where_posted['left("ncCode",1) =\'1\' AND "ncCode" <> \'150\''] = null;
		$where_posted['tranStatus'] = 1;
		$_this->bank_reconsile_detail_model->set_where($where_posted);
		$count_posted_cash = $_this->bank_reconsile_detail_model->count();
		if($count_all_cash != $count_posted_cash)
		{
			// update header status transfer posted
			$data_header['transferStatus'] = 1;
			$data_header['verifiedBy'] = $verifiedBy;
			$_this->db->where($where_bank);
			$_this->db->update('facc.bankReconsile', $data_header);
		} else
		if($count_all_cash == $count_posted_cash)
		{
			// update header status transfer posted
			$data_header['transferStatus'] = 9;
			$data_header['verifiedBy'] = $verifiedBy;
			$_this->db->where($where_bank);
			$_this->db->update('facc.bankReconsile', $data_header);
		}
	}
}


function getCoaCategory($acc_category,$business_unit)
{
	$_this = &get_Instance();
	$_this->load->model('master/coa_category_model');

	return $_this->coa_category_model->get(array('accCategory'=>$acc_category,'businessUnitCode'=>$business_unit));
}

function get_accept_header()
{
	$CI = &get_Instance();
	$accept_request = $CI->input->get_request_header('accept', TRUE);
	$arr = explode(",", $accept_request, 2);
	$first = $arr[0];
	return strtolower($first);
}