<?php 
/*
Fungsi : Semua fungsi-fungsi global ditaruh disini
*/
Class Fungsi
{
function Fungsi()
	{
		/* Load Library CI */
		$this->CI =& get_instance();
		$this->CI->load->library(array('session','form_validation','fungsi_sap'));
		$this->CI->load->model('user/user_model', '', TRUE);
		$this->CI->load->model('admin/admin_model', '', TRUE);
		$this->CI->load->helper(array('captcha'));
		
	}
/* Fungsi utk cancel mutasi po */
function cancel_po_mutasi($sj)
{
	$data = array();
	$query = $this->CI->db->query("select * from t_po_mutasi WHERE  iddn ='".$sj."'");
	foreach($query->result() as $row)
	{
		$data[] = array( 
										'idcab'	=> $row->idcab,
										'ebeln'	=> $row->ebeln,
										'iddn'	=> $sj,
										'qty'	=> $row->qty * -1,
										'oa'	=> $row->oa,
										'addby'		=> $this->CI->session->userdata('uid'),
										'adddate' 	=> date( 'Y-m-d H:i:s'),
										);					
	}
	
	$this->CI->db->insert_batch('t_po_mutasi', $data); 
}
/* Fungsi utk proses mutasi po */
function add_po_mutasi($idcab,$sj,$vol)
{
	$data = array();
	$query_sum = $this->CI->db->query("select SUM(tot_qty) as total from v_po_mutasi WHERE  idcab ='".$idcab."' AND tot_qty > 0 ORDER BY ebeln");
	foreach($query_sum->result() as $row_sum)
	{
		if($vol > $row_sum->total)
		{
			//return $data;
			break;
		}
		else
		{
			$tot_vol = 0;
			$vols = $vol;
			$query = $this->CI->db->query("select * from v_po_mutasi WHERE  idcab ='".$idcab."' AND tot_qty > 0 ORDER BY ebeln");	
			foreach($query->result() as $row)
			{
				if($vols < $row->tot_qty)
				{
					$entry = $vols *-1;
					$tot_vol = $tot_vol + $vols;
					$vols =  $row->tot_qty - $vols;
					$sisa = $row->tot_qty - $vols;	
				}
				else
				{
					$vols =  $vols - $row->tot_qty;
					$tot_vol = $row->tot_qty + $tot_vol;
					$sisa = $row->tot_qty;
					$entry = $row->tot_qty *-1;
				}
										$data[] = array( 
										'idcab'	=> $idcab,
										'ebeln'	=> $row->ebeln,
										'iddn'	=> $sj,
										'qty'	=> $entry,
										'oa'	=> $row->oa,
										'addby'		=> $this->CI->session->userdata('uid'),
										'adddate' 	=> date( 'Y-m-d H:i:s'),
										);					
				if($tot_vol == $vol)
				{
					$this->CI->db->insert_batch('t_po_mutasi',$data); 
					break;
				}
			}
		}
	}
	
	
	//return $data;
	
}

/* Fungsi utk mendapatkan tarif ongkos angkut */
function get_oa_trf($idcab,$date)
{
	//Cari data dimana tgl harga valid lebih besar atau sama dengan dari tgl hari ini
	$query = $this->CI->db->query("select * from t_oa_trf WHERE  idcab ='".$idcab."' AND valid >= '".$date."' LIMIT 1");
	//Jika tidak ditemukan maka ambil harga terakhir
	if ($query->num_rows() == 0)
		{
			$query = $this->CI->db->query("select * from t_oa_trf WHERE  idcab ='".$idcab."' ORDER BY valid DESC LIMIT 1");
			foreach($query->result() as $row)
				{
						return $row->price;
				}
		}
	//Jika ditemukan cek apakah tgl harga valid > dari tgl hari ini
	elseif ($query->num_rows() > 0)
	{
		foreach($query->result() as $row)
		{
			//Jika tgl harga valid > dari tgl hari ini maka ambil data dimana tgl harga valid lebih kecil atau sama dengan tgl hari ini
			if(	$row->valid	> $date )
			{
				$query = $this->CI->db->query("select * from t_oa_trf WHERE  idcab ='".$idcab."' AND valid <= '".$date."' ORDER BY valid DESC LIMIT 1");
				if ($query->num_rows() == 0)
				{
					return 0;
				}
				else
				{
					foreach($query->result() as $row)
						{
								return $row->price;
						}
				}
			}
			else
			{
				return $row->price;
			}
		}
	}
	
	
}
/* Fungsi display 10 transaksi bank terakhir */
function display_last10_banktrans($idcab)
{
	$query = $this->CI->db->query("select * from t_cpv WHERE  idcab = '".$idcab."' and nocpdu <> '' order by adddate desc limit 10 ");
	return $query->result();
}
/* Fungsi display 10 transaksi bank terakhir */

/* Fungsi display semua saldo cabang untuk dashboard cabang pusat */
function display_all_saldo_cab()
{
	
	$table = '<table width="100%" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#000000">
  <tr>
    <td colspan="6" align="center"><h1>SYSTEM DASHBOARD<br />'.$this->CI->session->userdata('idcab').' - '.strtoupper($this->CI->session->userdata('namacab')).'</h1></td>
  </tr>
  <tr>
   	<th width="500">BRANCH</th>
    <th width="214">BANK BALANCE</th>
    <th width="214">PETTY CASH UO BALANCE</th>
    <th width="230">PETTY CASH OP BALANCE</th>
    <th width="204">STOCK BALANCE</th>
    <th width="204">WASTE BALANCE</th>
  </tr>';
					$query = $this->CI->db->query("select * from m_cab WHERE  idcab <> 1");
					foreach($query->result() as $row)
					{
						if($this->get_stock_bal($row->idcab) <> $this->CI->fungsi_sap->fm_get_stock($row->lgort))
						{
							$status = '<font color="#FF0000">Not Balance!</font>';		
						}
						else
						{
							$status = '<font color="#009900">Balance</font>';			
						}
						$table .= '<tr>
	 <td align="center" valign="middle" bgcolor="#FFFF00"><h1>'.$row->cabname.'</h1></td>
    <td align="right" valign="middle" bgcolor="#FFFF00"><h1>'.$this->format_idr( $this->get_bank_bal($row->pcbankglacc)).'</h1></td>
    <td align="right" valign="middle" bgcolor="#FFFF00"><h1>'.$this->format_idr($this->get_pc_bal($row->idcab)).'</h1></td>
    <td align="right" valign="middle" bgcolor="#FFFF00"><h1>'.$this->format_idr($this->get_pc_bal_op($row->idcab)).'</h1></td>
    <td align="center" bgcolor="#FFFF00"><h1>'.number_format($this->get_stock_bal($row->idcab)).'</h1>'.$status.'</td>
     <td align="center" bgcolor="#FFFF00"><h1>'.number_format($this->CI->fungsi_sap->fm_get_stock_waste($row->lgort)).'</h1></td></tr>';
						
					}
	
	$table .='</table>'; 
	
	return $table;
	
}
/* Fungsi display semua saldo cabang untuk dashboard cabang pusat */


/* Fungsi cari transporter autocomplete */
function search_transporter($opt)
{				
					$return_arr = array();
					
					$query = $this->CI->db->query("select * from m_transport WHERE  idcab ='".$this->CI->session->userdata('idcab')."'");
					foreach($query->result() as $row)
					{
						if($opt=='idtrans')
						{
							 $row_array['label'] = $row->idtrans;
			 				  $row_array['value'] = $row->idtrans;
			 				  $row_array['nama_trans'] = $row->name;
							   $row_array['vnumb'] = $row->vnumb;
							 
							
						}
						else
						{
							  $row_array['label'] = $row->name;
			 				 $row_array['value'] = $row->name;
			 				 $row_array['idtrans'] = $row->idtrans;
							   $row_array['vnumb'] = $row->vnumb;
						}
						
						 array_push($return_arr,$row_array);
						
					}
				
				echo json_encode($return_arr);
}
/* Fungsi terbilang */
function terbilang($x)
{
/* Fungsi Untuk Terbilang */
  $abil = array("", "Satu ", "Dua ", "Tiga ", "Empat ", "Lima ", "Enam ", "Tujuh ", "Delapan ", "Sembilan ", "Sepuluh ", "Sebelas ");
  if ($x < 12)
    return " " . $abil[$x];
  elseif ($x < 20)
    return $this->terbilang($x - 10) . "Belas";
  elseif ($x < 100)
    return $this->terbilang($x / 10) . " Puluh" . $this->terbilang($x % 10);
  elseif ($x < 200)
    return " Seratus" . $this->terbilang($x - 100);
  elseif ($x < 1000)
    return $this->terbilang($x / 100) . " Ratus" . $this->terbilang($x % 100);
  elseif ($x < 2000)
    return " Seribu" . $this->terbilang($x - 1000);
  elseif ($x < 1000000)
    return $this->terbilang($x / 1000) . " Ribu" . $this->terbilang($x % 1000);
  elseif ($x < 1000000000)
    return $this->terbilang($x / 1000000) . " Juta" . $this->terbilang($x % 1000000);
elseif ($x < 1000000000000)
    return $this->terbilang($x / 1000000000) . " Milyard" . $this->terbilang($x % 1000000000);
}
/* Display system message ok & error */
function disp_sys_msg()
{	
	echo $this->CI->session->flashdata('message_ok') == '' ? '' : '<div class="success">' . $this->CI->session->flashdata('message_ok') . '</div>';
	echo $this->CI->session->flashdata('message_err') == '' ? '' : '<div class="error">' . $this->CI->session->flashdata('message_err') . '</div>';	
}

/* Fungsi untuk membuat combo box menu */
function get_menu($id,$level, $post_data)
{
      			$response = '';
				$query = $this->CI->db->query('SELECT * FROM master_menu WHERE pid ='.$id.' ORDER BY mid, pid ASC');
				foreach($query->result() as $row): 
				
          		$response .= $row->mid== $post_data ? '<option value="'.$row->mid.'" selected="selected">': '<option value="'.$row->mid.'">';
				for ($i = 0; $i < ($level-1); $i++) $response .= '&nbsp;&nbsp;&nbsp;&nbsp;';
				$response .= '|___'.$row->mname;
				$response .= '</option>';
				$response .= $this->get_menu($row->mid,$level+1,$post_data);
     			endforeach;
      			return $response;      
}

/*Fungsi membuat tree menu */
function menu_widget($data,$parent){
  if(isset($data[$parent])){ 
	$str = ''; 
	foreach($data[$parent] as $value){
	  $child = $this->menu_widget($data,$value->mid); 
	 if ( $value->murl == '#' ) { $url=$this->CI->config->item('base_url').'/frame/frame_body'; } else { $url=$this->CI->config->item('base_url').'/'.$value->murl; }
	 $str .= '<li class="closed">';
	 //$str .= '<li class="open">';
	 $str .= ($child) ? '<span class="folder"><a href="'.$url.'" target="mainFrame">'.$value->mname.'</a></span><ul>' : '<span class="file"><a href="'.$url.'" target="mainFrame">'.$value->mname.'</a></span></li>';
	  if($child) $str .= $child;
	}
	$str .= '</ul>';
	return $str;
  }else return false;	  
}

/*Fungsi membuat tree menu utk menu admin role edit */
function menu_widget_role_edit($data,$parent,$chk){
  if(isset($data[$parent])){ 
	$str = ''; 
	foreach($data[$parent] as $value){
	  $child = $this->menu_widget_role_edit($data,$value->mid,$chk); 
	 // $str .= '<li class="closed">';
	 $str .= '<li>';
	 $str .= ($child) ? '<input type="checkbox" name="chk_menu[]" value="'.$value->mid.'"'.set_checkbox('chk_menu[]', $value->mid, isset($chk) && $this->search_array($chk, $value->mid)  ? TRUE : FALSE ).'><label>'.$value->mname.'</label><ul>' : '<input type="checkbox" name="chk_menu[]" value="'.$value->mid.'"'.set_checkbox('chk_menu[]', $value->mid, isset($chk) && $this->search_array($chk, $value->mid)  ? TRUE : FALSE ).'><label>'.$value->mname.'</label></li>';
	  if($child) $str .= $child;
	}
	$str .= '</ul>';
	return $str;
  }else return false;	  
}

/*Fungsi membuat tree menu utk menu input admin role */
function menu_widget_role($data,$parent){
  if(isset($data[$parent])){ 
	$str = ''; 
	foreach($data[$parent] as $value){
	  $child = $this->menu_widget_role($data,$value->mid); 
	 // $str .= '<li class="closed">';
	 $str .= '<li>';
	 $str .= ($child) ? '<input type="checkbox" name="chk_menu[]" value="'.$value->mid.'"'.set_checkbox('chk_menu[]', $value->mid, isset($default['chk_update']) && $default['chk_update'] == $value->mid  ? TRUE : FALSE ).'><label>'.$value->mname.'</label><ul>' : '<input type="checkbox" name="chk_menu[]" value="'.$value->mid.'"'.set_checkbox('chk_menu[]', $value->mid, isset($default['chk_update'] ) && $default['chk_update'] == $value->mid  ? TRUE : FALSE ).'><label>'.$value->mname.'</label></li>';
	  if($child) $str .= $child;
	}
	$str .= '</ul>';
	return $str;
  }else return false;	  
}

//Fungsi utk mendapatkan auto increment berikutnya
function get_last_id($table)
{
	$query = $this->CI->db->query(" SHOW TABLE STATUS LIKE '".$table."' ");
	return $query;
}

//Fungsi utk search array ( Tidak berlaku utk multidimensional array )
function search_array($array, $value)
{
	 if(in_array($value ,$array))
	 {
		 return true;
	 }
}

//Fungsi utk check array kosong
function is_array_empty($InputVariable)
{
   $Result = true;

   if (is_array($InputVariable) && count($InputVariable) > 0)
   {
      foreach ($InputVariable as $Value)
      {
         $Result = $Result && $this->is_array_empty($Value);
      }
   }
   else
   {
      $Result = empty($InputVariable);
   }

   return $Result;
}

/* Fungsi untuk convert status */
 	function convert_status($status)
	{
		
		switch ($status)
		{
			case 1:
			  $status = 'Yes';
			  break;
			case 0:
			  $status = 'No';
			  break;
		}
	
	return $status;
		
	}

/* Fungsi Untuk Enkripsi */
function encrypt1($string)
{
return $this->CI->encrypt->encode($string, $this->CI->config->item('encryption_key'));		
}

/* Fungsi Untuk Dekripsi */
function decrypt1($string)
{
return $this->CI->encrypt->decode($string, $this->CI->config->item('encryption_key'));		
}

/* Fungsi utk check session user */
function check_login()
{	
	
	if($this->CI->session->userdata('login')==FALSE)
	{
	$this->CI->session->set_flashdata('message_err', 'Please login to enter system');
	redirect('user/user_login/');
	}
}

/* Fungsi utk check otorisasi menu */
function menu_auth($mid)
{	
	$query_user_menu = $this->CI->db->query("select * from role_menu where roleid='".$this->CI->session->userdata('roleid')."' and mid='".$mid."'");
	
	if ($query_user_menu->num_rows() == 0 && $this->CI->session->userdata('rolename') != 'ADMIN')
		{
		$this->CI->session->set_flashdata('message_err', 'You do not have authorization to access menu');
		redirect('frame/frame_blank/');
		}
	
		

}

/* Fungsi utk check otorisasi transaksi */
function trans_auth($sess)
{	
	if ($sess == 0 && $this->CI->session->userdata('rolename') != 'ADMIN')
		{
		$this->CI->session->set_flashdata('message_err', 'You do not have authorization to do the transaction');
		redirect('frame/frame_blank/');
		}
}

/* Fungsi utk send email */
function send_email($to, $subject, $msg)
{
//GMAIL
/*$config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'wiguna.imam',
    'smtp_pass' => 'imam280785',
    'mailtype'  => 'html', 
    'charset'   => 'iso-8859-1'
);*/
//WGI
$config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'rajawali.ptwgi.com',
    'smtp_port' => 25,
/*    'smtp_user' => 'wiguna.imam',
    'smtp_pass' => 'imam280785',*/
    'mailtype'  => 'html', 
    'charset'   => 'iso-8859-1'
);
$this->CI->load->library('email', $config);

//$config = Array( 'mailtype'  => 'html' );
$this->CI->load->library('email', $config);

$this->CI->email->set_newline("\r\n");
$this->CI->email->from('sysadmin@evalube.com', 'System administrator');
$this->CI->email->to($to); 

$this->CI->email->subject($subject);
$this->CI->email->message($msg);	
$this->CI->email->send();
}


/* Fungsi Untuk Captcha */
function setChaptcha()
{
	
    $captcha_path = $this->CI->config->item('base_url').'/etc/captcha/';
    $vals = array(
            'img_path'       => './etc/captcha/' ,
            'img_url'        => $captcha_path,
            'expiration'     => 3600,// satu jam
            'img_width'    => '140' ,
            'word'    => random_string('numeric' , 6),
            );
    $cap = create_captcha($vals);
    $capdb = array(
            'captcha_id'       => NULL ,
            'captcha_time'     => $cap['time'],
            'ip_address'       => $this->CI->input->ip_address(),
            'word'             => $cap['word']
    );
    $query = $this->CI->db->insert_string('captcha' , $capdb);
    $this->CI->db->query($query);
    $data['cap'] = $cap;
    return $data;
 }
 
 //Fungsi utk menghapus data session pencarian
 function sess_search_segment()
 {
	if ($this->CI->session->userdata('sess_segment')=='')
	{
		$this->CI->session->set_userdata('sess_segment',$this->CI->uri->segment(3));
	}
	else
	{
		if($this->CI->session->userdata('sess_segment') != $this->CI->uri->segment(3))
		{
		//Hapus data session pencarian
		$this->CI->session->unset_userdata('sess_search');
		$this->CI->session->set_userdata('sess_segment',$this->CI->uri->segment(3));
		}
		
	}	 
 }

/*Fungsi untuk menghilangkan koma pada angka yang menggunakan number_format*/
function hapus_koma($angka)
{
return str_replace(",","",$angka);
} 

/*Fungsi untuk send notification email*/
function send_notif($idnotgrp, $arr_var)
{
	
//Get notification template
//Get data detail not group by id not group
		$sql_notgrp_get = $this->CI->admin_model->get_notgrp_detail($idnotgrp);
		foreach ($sql_notgrp_get->result() as $row_notgrp)
		{	
			$subject = $row_notgrp->subject;
			$messages = $row_notgrp->msg;
		}
//Format messages
		$i = 0;
		foreach ($arr_var as &$value) {
				$i = $i + 1;
				$messages = str_replace('$'.$i,$value,$messages);
		}
//Send email
		$sql_notgrpmem_get = $this->CI->admin_model->get_user_notgrp_bynotid($idnotgrp);
		foreach ($sql_notgrpmem_get->result() as $row_notgrpmem)
		{	
		
		$this->send_email($row_notgrpmem->email, $subject, nl2br($messages) );
		
		}

//return $messages;	
}
//Send notification cabang
function send_notif_cab($idcab, $sub, $msg)
{
	
//Get user by id cabang
		$sql_usrcab_get = $this->CI->admin_model->get_user_idcab($idcab);
		foreach ($sql_usrcab_get->result() as $row_usrcab)
		{	
			$this->send_email($row_usrcab->email, $sub, nl2br($msg) );
		}
}

//Format mata uang rupiah
function format_idr($amount)
{
	$amount = number_format($amount,0,"",".");
	
	return $amount;
}

//Convert format IDR ke format angka

function convert_idr_to_num($curr){
	$lv_found = 0;
	$lv_result = '';
	for ($i = 0; $i <= strlen($curr); $i++) {
		if ( ($lv_found == 0) and ($curr[$i] != ",") ){
			$lv_result = $lv_result.$curr[$i];
			}
		else{
			$lv_found = 1;
			//$lv_result = $lv_result.$string[$i];
		}
	}
	return str_replace(".","",$lv_result);
}

	//Get No. Counter CPV
	function get_no_count($idcab, $typ)
	{	
		$query_bpb = $this->CI->admin_model->get_lastnum_count($idcab);
		
		//Check apakah counter tersedia pada tahun berjalan ?
		if ($query_bpb->num_rows() == 0)
		{
			$this->CI->session->set_flashdata('message_err', 'Counter not available for '.$typ.' in year '. date('Y'));
			redirect('frame/frame_blank/');
			exit;	
		}
		
			//Get last number from BPB
			foreach ($query_bpb->result() as $row_count)
			{	
				switch ($typ) {
				case 'CPV':
				$counter = $row_count->bpb_count + 1;
				$count_arr = array('CPV/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'bpb_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;	
			case 'PC':
				$counter = $row_count->pc_count + 1;
				$count_arr = array('PC/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'pc_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;
			case 'OP':
				$counter = $row_count->op_count + 1;
				$count_arr = array('OP/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'op_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;	
			case 'OPC':
				$counter = $row_count->opc_count + 1;
				$count_arr = array('OPC/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'opc_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;	
			case 'BA':
				$counter = $row_count->ba_count + 1;
				$count_arr = array('BA/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'ba_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;
			case 'BPKK':
				$counter = $row_count->bpkk_count + 1;
				$count_arr = array('BPKK/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'bpkk_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;	
			case 'SJ':
				$counter = $row_count->sj_count + 1;
				$count_arr = array('SJ/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'sj_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;
			case 'RMB':
				$counter = $row_count->rmb_count + 1;
				$count_arr = array('RMB/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'rmb_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;	
			case 'OW':
				$counter = $row_count->ow_count + 1;
				$count_arr = array('OW/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'ow_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;	
			case 'STB':
				$counter = $row_count->stb_count + 1;
				$count_arr = array('STB/'.$counter.'/'.date('m').'/'.date('y').'/'.$idcab, $counter );
				
				//Update DB counter
					$count = array( 'stb_count' => $counter,
									'chby'		=> $this->CI->session->userdata('uid'),
									'chdate' 	=> date( 'Y-m-d H:i:s'),);
			break;	
						
						}
			
			$this->CI->admin_model->update_count($idcab, $count);
			}
	 return $count_arr;
	}
	
	
	
	/* Fungsi untuk convert status CPV */
 	function convert_status_cpv($status)
	{
		
		switch ($status)
		{
			case 1:
			  $status = '<font color="#00CC00"><b>APPROVE</b></font>';
			  break;
			case 0:
			  $status = '<font color="#FF0000"><b>PENDING</b></font>';
			  break;
		}
	
	return $status;
		
	}	
	
	/* Fungsi untuk convert status op */
 	function convert_status_op($status_op)
	{
		
		switch ($status_op)
		{
			case 1:
			  $status_op = '<font color="#00CC00"><b>CLOSED</b></font>';
			  break;
			case 0:
			  $status_op = '<font color="#FF0000"><b>OPEN</b></font>';
			  break;
		}
	
	return $status_op;
		
	}	
	
	/* Fungsi get saldo bank cabang */
	function get_bank_bal($pcglacc)
	{
		
		/*$this->CI->db->select_sum('amount');
		$this->CI->db->where('idcab', $idcab); 
		$query = $this->CI->db->get('t_bankbal');
		
		foreach ($query->result() as $row);
		
		$balance = $row->amount;
		
		
		return $balance;*/
		
			$sap = new SAPConnection();
			$sap->Connect($this->CI->fungsi_sap->sap_connection_string());
			if ($sap->GetStatus() == SAPRFC_OK ) $sap->Open();
			if ($sap->GetStatus() != SAPRFC_OK ) {
		   	$sap->PrintStatus();
		   	exit;
			}

		$fce = &$sap->NewFunction ("YFM_GETGLBAL_RLIS");
		if ($fce == false ) {
		   $sap->PrintStatus();
		   exit;
		}
		
		 $fce->GV_HKONT = $this->CI->fungsi_sap->fm_convert_vendor($pcglacc);
		 $fce->Call();
	   
	   if ($fce->GetStatus() == SAPRFC_OK) 
 		{	
			$balance = $this->convert_idr_to_num($fce->GV_TOTAL2);
		}
		else
		{
			 $fce->PrintStatus();
			 $sap->Close();
		}
		
		return $balance;
		
	}
	
	/* Fungsi get saldo bank cabang - saldo history pc op */
	function get_bank_bal1($pcglacc,$idcab)
	{
		
		/*$this->CI->db->select_sum('amount');
		$this->CI->db->where('idcab', $idcab); 
		$query = $this->CI->db->get('t_bankbal');
		
		foreach ($query->result() as $row);*/
		
		
		
		$balance =  $this->get_bank_bal($pcglacc) - $this->get_hist_pc_bal_op($idcab);
		
		
		return $balance;
		
	}
	
	/* Fungsi get volume total cabang OP */
	
	function get_vol($prnumb, $year)
	{
		$total = 0;
		$this->CI->db->select_sum('vol');
		$this->CI->db->where('prnumb', $prnumb); 
		$this->CI->db->where('year', $year);
		$this->CI->db->where('cancel', 0);
		$query = $this->CI->db->get('m_op');
		foreach ($query->result() as $row){
			if($row->vol!="")
				$total = $row->vol;
		}
		
		
		return $total;
		
		
	}
	
	
	/* Fungsi get saldo petty cash cabang */
	function get_pc_bal($idcab)
	{
		
		$this->CI->db->select_sum('amount');
		$this->CI->db->where('idcab', $idcab); 
		$query = $this->CI->db->get('t_pcbal');
		
		foreach ($query->result() as $row);
		
		$balance = $row->amount;
		
		
		return $balance;
		
	}
	
	/*Get Stock Balance */
function get_stock_bal($idcab)
	{
		
		$this->CI->db->select_sum('qty');
		$this->CI->db->where('idcab', $idcab); 
		$query = $this->CI->db->get('t_stockbal');
		
		foreach ($query->result() as $row);
		
		$balance = $row->qty;
		
		
		return $balance;
		
	}
	
	
	/*Cek CPV Bank exist pada history saldo bank*/
function check_cpv_bank($cpv)
{
	$query = $this->CI->db->query("select * from t_bankbal where rlis_ref='".$cpv."'");
	
	if ($query->num_rows() == 0)
		{
			return TRUE;
		}
	else
		{
			
			return FALSE;
		}
	
}

/*Cek CPV Bank exist pada history saldo PC*/
function check_cpv_pc($pc)
{
	$query = $this->CI->db->query("select * from t_pcbal where ref='".$pc."'");
	
	if ($query->num_rows() == 0)
		{
			return TRUE;
		}
	else
		{
			
			return FALSE;
		}
	
}

/* Fungsi get saldo petty cash opr cabang */
	function get_pc_bal_op($idcab)
	{
		
		$this->CI->db->select_sum('amount');
		$this->CI->db->where('idcab', $idcab); 
		$query = $this->CI->db->get('t_pcbal_op');
		
		foreach ($query->result() as $row);
		
		$balance = $row->amount;
		
		
		return $balance;
		
	}
	
/* Fungsi get saldo petty cash opr cabang */
	function get_waste_bal($idcab)
	{
		
		$this->CI->db->select_sum('price');
		$this->CI->db->where('idcab', $idcab); 
		$query = $this->CI->db->get('t_limbah');
		
		foreach ($query->result() as $row);
		
		$balance = $row->price;
		
		
		return $balance;
		
	}

/* Fungsi get history saldo petty cash opr cabang */
	function get_hist_pc_bal_op($idcab)
	{
		
		$this->CI->db->select_sum('amount');
		$this->CI->db->where('idcab', $idcab); 
		$query = $this->CI->db->get('h_pcop_trf');
		
		foreach ($query->result() as $row);
		
		$balance = $row->amount;
		
		
		return $balance;
		
	}	
	
	
}