<?php 
/*
Fungsi : Controller untuk accounting G/L
*/

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Acc_gl extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	
/*-------------Inisialisasi variabel--------------*/ 
	
	//Menu ID utk keperluan otorisasi
	var $menu_acc_gl_cpv_pending  = 75;
	var $menu_reverse_gl  = 123;

/*-------------Inisialisasi variabel--------------*/ 	

/*------------Fungsi lokal------------------------*/
	


/*------------Fungsi local------------------------*/	
	function __construct()
	{
		parent::__construct();
		
		$this->load->model('finance/fin_model', '', TRUE);
		$this->load->model('accounting/acc_model', '', TRUE);
		$this->load->model('admin/admin_model', '', TRUE);
		$this->fungsi->check_login();
	}
	
	
	public function index()
	{	
		$this->acc_cpv_gl_pending();
		
	}
	
	//Reverse G/L
	function reverse()
	{
		$data['prev'] = '';
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_reverse_gl);
		
		$data['menu_path'] = 'ACCOUNTING > REVERSE G/L';
		$data['form_action']= site_url('accounting/acc_gl/post_glreverse_prev');
		$this->load->view('accounting/acc_glreverse_form', $data);	
	}
	
	
	//Reverse G/L Prev
	function post_glreverse_prev()
	{
		
	//Config utk validasi
	$config = array(
               array(
                     'field'   => 'txt_gl',
                     'label'   => 'Accounting Document',
                     'rules'   => 'required'
                  ),
               array(
                     'field'   => 'txt_year',
                     'label'   => 'Fiscal Year',
                     'rules'   => 'required'
                  ),
               array(
                     'field'   => 'txt_postdate',
                     'label'   => 'Posting Date',
                     'rules'   => 'required'
                  ),
				   array(
                     'field'   => 'txt_cancel',
                     'label'   => 'Cancel reason',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'txt_fis',
                     'label'   => 'Fiscal Period',
                     'rules'   => 'required'
                  )
            );
	
	
		//Check validasi form
		$this->form_validation->set_rules($config); 
		
		if ($this->form_validation->run() == TRUE)
			{
				$data['prev'] = 1;
				
				$data['txt_gl'] = $this->input->post('txt_gl');
				$data['txt_year'] = $this->input->post('txt_year');
				$data['txt_reason'] = $this->input->post('cb_reason');
				$data['txt_postdate'] = $this->input->post('txt_postdate');
				$data['txt_cancel'] = $this->input->post('txt_cancel');
				$data['txt_fis'] = $this->input->post('txt_fis');
				
				$data['txt_obj'] = $this->fungsi_sap->fm_convert_vendor($this->input->post('txt_gl')).'WGI1'.$this->input->post('txt_year');
				
				$cpv = $this->acc_model->get_cpv_bynocpvform( $this->fungsi_sap->fm_get_cpv_num($this->fungsi_sap->fm_convert_vendor($this->input->post('txt_gl')), $this->input->post('txt_year'), '1'))->result();
				foreach ($cpv  as $cpvs);
				
				$data['txt_cpvno'] = $cpvs->nocpvform;
				$data['txt_cpv'] = $cpvs->nocpv;
				$data['txt_cpv_year'] = $cpvs->year;
				$data['txt_cpdu'] = $cpvs->nocpdu;
				$data['txt_amount'] = $cpvs->amount_trf;
				$data['txt_idcab'] = $cpvs->idcab;
				$data['txt_cpv_pctyp'] = $cpvs->pctyp;
				$data['txt_cpv_pctrans'] = $cpvs->pctrans;
				
				if($data['txt_cpvno'] == '')
				{
					//$data['prev'] = '';
					$this->session->set_flashdata('message_err', 'CPV Number For Acc. Doc. No '.$this->input->post('txt_gl').' Is Not Found!');
					redirect('accounting/acc_gl/reverse');
				}
				else
				{
					//Cek saldo
					$cpv  = $cpvs->nocpvform;
					$cpvss= explode("/", $cpv);
		
					//Jika merupakan CPV yang dibuat oleh pusat
					if($cpvss[4]==1)
					{
							//Jika nilai yang akan dicancel < dari saldo bank
							if($cpvs->amount_trf > $this->fungsi->get_bank_bal($cpvs->idcab))
							{
								$this->session->set_flashdata('message_err', 'Cannot cancel, your bank balances is insufficient!');
								redirect('accounting/acc_gl/reverse');	
							}	
						
					}
					else
					{
								//Jika merupakan CPV yang dibuat oleh cabang	
								$this->session->set_flashdata('message_err', 'Cannot cancel!');
								redirect('accounting/acc_gl/reverse');		
						
					}
					
					
				}
				
				$data['menu_path'] = 'ACCOUNTING > REVERSE G/L > '.$this->input->post('txt_gl');
				$data['form_action']= site_url('accounting/acc_gl/post_glreverse_proc');
				$this->load->view('accounting/acc_glreverse_form', $data);	
			}
		else
			{
				$this->reverse();
			}
			
		
	}

//Reverse G/L Proc
function post_glreverse_proc()
{

					$cpv  = $this->input->post('txt_nocpv');
					$cpvss= explode("/", $cpv);
		
					//Jika merupakan CPV yang dibuat oleh pusat
					if($cpvss[4]==1)
					{
							$this->fungsi_sap->fm_rev_glacc($this->input->post('txt_gl'),$this->input->post('txt_postdate'), $this->input->post('txt_reason'), $this->input->post('txt_fis'),  $this->input->post('txt_year'));
							
							
					if($this->session->userdata('sap_obj_key_rev') != '')
					{
		
						//Update saldo bank
						/* Insert data */
					$bankbal = array( 	'idcab'		 => $this->input->post('txt_idcab'),
										'sap_ref'	 => $this->session->userdata('sap_obj_key_rev'),
										'rlis_ref'	 => $this->input->post('txt_nocpv'),
										'amount'	 => $this->input->post('txt_amount') * -1,
										'addby'		 => $this->session->userdata('uid'),
										'adddate' 	 => date( 'Y-m-d H:i:s'),
										);
				
					$this->fin_model->add_bankbal($bankbal);
		
					//Update CPV 
					/* Update data CPV */	
						$cpv = array( 'accglpost' => '',
									  'accglno' => '',
									  'accglpostby'	=> '',
									  'accglpostdate' => '',
									);
				
						$this->fin_model->update_cpv($this->input->post('txt_cpv'), $this->input->post('txt_cpv_year'), $cpv);
		
				//Insert history
				//Insert to table MIRO history cancel
						$hglcan = array('nocpvform' => $this->input->post('txt_nocpv'),
										'year'	=>  date('Y'),
										'glacc' => $this->input->post('txt_gl'),
										'glacc_cancel' => $this->session->userdata('sap_obj_key_rev'),
										'reason' => $this->input->post('txt_cancel'),
										'canby' => $this->session->userdata('uid'),
										'candate' => date( 'Y-m-d H:i:s'),
									);	
							$this->acc_model->add_hglcancel($hglcan);
				
				
				//Check apakah ada no. CPV pada table history pc opr, jika ada maka dicancel juga
				$hpcop = $this->acc_model->get_h_pcop_bynocpvform($this->input->post('txt_nocpv'))->result();
				foreach ($hpcop  as $hpcops);
				
				if($hpcops->idcab != '')
				{
					$hpcop = array( 'idcab'		 => $this->input->post('txt_idcab'),
									'sap_ref'	 => $this->session->userdata('sap_obj_key_rev'),
									'rlis_ref'	 => $this->input->post('txt_nocpv'),
									'amount'	 => $hpcops->amount * -1,
									'addby'		 => $this->session->userdata('uid'),
									'adddate' 	 => date( 'Y-m-d H:i:s'),
									);
					
					$this->acc_model->add_h_pcop($hpcop);
				}
							$this->session->set_flashdata('message_ok', 'G/L data cancel, Number :'.$this->session->userdata('sap_obj_key_rev'));
							redirect('accounting/acc_gl/reverse');
						}
							
								
					}
					else
					{
								//Jika merupakan CPV yang dibuat oleh cabang	
								$this->session->set_flashdata('message_err', 'Cannot cancel!');
								redirect('accounting/acc_gl/reverse');		
						
					}
	
	
	
	
}
	
	
	
	
	function acc_cpv_gl_pending()
	{
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('view'));
		
		//print_r($this->fin_model->get_list_cpv_pend_paging($this->config->item('paging_limit'), $offset)->result());
		 
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_acc_gl_cpv_pending);
		
		/* Setting Parameter Untuk Paging */
		$uri_segment = 4;
		$offset =    $this->uri->segment($uri_segment);
		
		$cpv = $this->fin_model->get_list_cpv_gl_pend_pag($this->config->item('paging_limit'), $offset)->result();
		$num_rows = $this->fin_model->get_list_cpv_gl_pend_count();
		
		$config['base_url'] = site_url('accounting/acc_gl/acc_cpv_gl_pending/');
	
		if ($num_rows > 0) // Jika query menghasilkan data
				{
					
					// Membuat pagination			
					$config['total_rows'] = $num_rows;
					$config['per_page'] = $this->config->item('paging_limit');
					$config['uri_segment'] = $uri_segment;
					$this->pagination->initialize($config);
					$data['pagination'] = $this->pagination->create_links();
					$i = 0 + $offset;
					
					$tmpl = array( 'table_open'    => '<table border="0" cellpadding="1" cellspacing="1" id="list">',
								  'row_alt_start'  => '<tr class="zebra">',
								  'row_alt_end'    => '</tr>'
								  );
					$this->table->set_template($tmpl);
		
					// Set heading untuk tabel
					$this->table->set_empty("&nbsp;");
					$this->table->set_heading('No. CPV', 'Branch', 'Amount transfer', 'Desc', 'Petty cash typ', 'Trans typ', 'Status', 'Create by','Create date','Options');
					
					foreach ($cpv  as $cpvs)
					{	
						if($cpvs->pctrans == 1)
						{
							
							$link = 'accounting/acc_gl/post_gl_cpv/';
							
						}
						else if($cpvs->pctrans == 2 && $cpvs->clrno == '')
						{
							$link = 'accounting/postclr/postclr_form/';
							
						}
						else if($cpvs->pctrans == 2 && $cpvs->clrno != '')
						{
							$link = 'accounting/acc_gl/post_gl_cpv/';
							
						}
						else if($cpvs->pctrans == 3)
						{
							$link = 'accounting/postexp/postexp_form/';
							
						}
						$this->table->add_row($cpvs->nocpvform, $cpvs->cabname, $this->fungsi->format_idr($cpvs->amount_trf), $cpvs->desc, $cpvs->desc2, $cpvs->desc3, $this->fungsi->convert_status_cpv($cpvs->status), $cpvs->appby, $cpvs->appdate, anchor($link.$cpvs->nocpv.'/'.$cpvs->year.'/'.$cpvs->idcab.'/'.$cpvs->pctrans,'Posting',array('class' => 'update')));	
					}
					
					$data['table'] = $this->table->generate();
				}
				
				else
				{
					$data['message'] = 'No data';
				}
					
		$data['menu_path'] = 'ACCOUNTING > G/L POST FROM CPV';
		$this->load->view('accounting/acc_cpv_list', $data);
		
		
	}

function post_gl_cpv()
{	
	//Get data CPV by no cpv & year
		$query_cpv_edit = $this->fin_model->get_cpv_bynoyear($this->uri->segment(4),$this->uri->segment(5));
		foreach ($query_cpv_edit->result() as $row_cpv)
		{
			$data['default']['txt_nocpvform'] = $row_cpv->nocpvform;
			$data['txt_pctrans'] = $row_cpv->pctrans;
			$data['default']['txt_xblnr'] = $row_cpv->nocpdu;
			$data['default']['txt_bktxt'] = $row_cpv->nocpvform;
			$data['default']['txt_amount_trf'] =  $this->fungsi->format_idr($row_cpv->amount_trf);
		}
		
		//Get data cabang get_cab_detail($idcab)
		$query_get_cab = $this->admin_model->get_cab_detail($row_cpv->idcab);
		foreach ($query_get_cab->result() as $row_cab);
		$data['txt_max_pcop'] = $row_cab->max_pcop_trf;
		//Jika tipenya direct transfer
		//if($row_cpv->pctrans == 1)
		//{
			if($row_cpv->pctyp == 1)
			{
				$pctxt = 'P.Cash Used Oil';
			}
			else if($row_cpv->pctyp == 2)
			{
				$pctxt = 'P.Cash Oprsnl';
			}
			else if($row_cpv->pctyp == 0)
			{
				$pctxt = 'P.Cash';	
			}
			
			$data['default']['txt_hkont'] = $row_cab->pcbankglacc;
			$data['default']['txt_hkont2'] = '1112116'; //Bank pusat
			$data['default']['txt_sgtxt'] = '1401 -'.strtoupper($row_cab->cabshorttxt).'- '.$pctxt.' '.$row_cpv->nocpvform; //Bank pusat
			$data['default']['txt_sgtxt2'] = strtoupper($row_cab->cabshorttxt).'- '.$pctxt.' '.$row_cpv->nocpvform;
			
			
		//}
		
		$data['default']['txt_zounr'] = strtoupper($row_cab->cabshorttxt.' - '.date('M').'\''.date('y'));
		$data['default']['txt_zounr2'] = strtoupper($row_cab->cabshorttxt.' - '.date('M').'\''.date('y'));
		
		
	$data['menu_path'] = 'ACCOUNTING > G/L POST FROM CPV > POST G/L ACC CPV > '.$row_cpv->nocpvform;
	$data['form_action']= site_url('accounting/acc_gl/post_gl_cpv_proc'.'/'.$this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6));
	$data['link'] = array('link_back' => anchor('accounting/acc_gl','Back', array('class' => 'back')));
	$this->load->view('accounting/acc_postgl_form', $data);
	
}

//Posting G/L process
function post_gl_cpv_proc()
{
	
	//Cek dulu document CPV sudah ada pada database atau belom ?
	/*if($this->fungsi->check_cpv_bank($this->input->post('txt_nocpvform')) == TRUE)
	{*/
	$accountgl[] = array( 		'ITEMNO_ACC' => 1,
								'GL_ACCOUNT' => $this->input->post('txt_hkont'),
								'PSTNG_DATE' => $this->input->post('txt_budat'),
								'FIS_PERIOD' => $this->input->post('txt_budat'),
								'ALLOC_NMBR' => $this->input->post('txt_zounr'),
								'ITEM_TEXT'	 => $this->input->post('txt_sgtxt'),
								);
	$accountgl[] = array( 		'ITEMNO_ACC' => 2,
								'GL_ACCOUNT' => $this->input->post('txt_hkont2'),
								'PSTNG_DATE' => $this->input->post('txt_budat'),
								'FIS_PERIOD' => $this->input->post('txt_budat'),
								'ALLOC_NMBR' => $this->input->post('txt_zounr2'),
								'ITEM_TEXT'	 => $this->input->post('txt_sgtxt2'),
								);
								
	$curramount[] = array( 		'ITEMNO_ACC' => 1,
								'AMT_DOCCUR' => $this->fungsi->convert_idr_to_num($this->input->post('txt_wrbtr')),
								);
	$curramount[] = array( 		'ITEMNO_ACC' => 2,
								'AMT_DOCCUR' => $this->fungsi->convert_idr_to_num($this->input->post('txt_wrbtr2')) * -1,
								);
	
	//print_r($accountgl);
	//print_r($curramount);
	
	$this->fungsi_sap->fm_post_gl_acc($this->input->post('txt_bktxt'),$this->input->post('txt_budat'),$this->input->post('txt_bldat'),$this->input->post('txt_xblnr'),  $accountgl,$curramount);
	
	if ($this->session->userdata('sap_obj_key') != '')
	{
	/* Insert data */
			$bankbal = array( 	'idcab'		 => $this->uri->segment(6),
								'sap_ref'	 => $this->session->userdata('sap_obj_key'),
								'rlis_ref'	 => $this->input->post('txt_nocpvform'),
								'amount'	 => $this->fungsi->convert_idr_to_num($this->input->post('txt_wrbtr')),
								'addby'		 => $this->session->userdata('uid'),
								//postdate
								'postdate' 	 => date("Y-m-d",   strtotime($this->input->post('txt_budat'))),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
		
			$this->fin_model->add_bankbal($bankbal);
			
	/* Update data CPV */	
	$cpv = array( 				'accglpost'		=> 1,
								'accglno' => $this->session->userdata('sap_obj_key'),
								'accglpostby'	=> $this->session->userdata('uid'),
								'accglpostdate' => date( 'Y-m-d H:i:s'),
								);
				
			$this->fin_model->update_cpv($this->uri->segment(4), $this->uri->segment(5), $cpv);
			
	/*Jika tipe nya direct transfer maka insert ke db history pc op */
	/* Dicomment sementara dulu by: Imam 09.07.2013*/
	if($this->input->post('txt_pctrans')==1)
	{
			$hpcop = array( 	'idcab'		 => $this->uri->segment(6),
								'sap_ref'	 => $this->session->userdata('sap_obj_key'),
								'rlis_ref'	 => $this->input->post('txt_nocpvform'),
								'amount'	 => $this->input->post('txt_max_pcop'),
								//postdate
								'postdate' 	 => date("Y-m-d",   strtotime($this->input->post('txt_budat'))),
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
				
			$this->acc_model->add_h_pcop($hpcop);
		
	}
	/*
	Dicomment sementara dulu by: Imam 09.07.2013
	*/
	
			/*Set pesan sukses dan kembali ke menu add cabang*/
			$this->session->set_flashdata('message_ok', 'G/L data posted, Number :'.$this->session->userdata('sap_obj_key'));
			redirect('accounting/acc_gl');
	}
		/*}
		else
		{
			
			$this->session->set_flashdata('message_err', 'CPV No :'.$this->input->post('txt_nocpvform'). 'already in database!');
			redirect('accounting/acc_gl');
			
		}*/
}

}