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

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

class Branch_cpv 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_add_cpv  = 77;
	var $menu_print_cpv  = 78;
	
	var $menu_add_pc_op  = 102;

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

/*------------Fungsi lokal------------------------*/
	
//Cek valid amount
public function valid_amount($amount)
{
	
	if($this->fungsi->convert_idr_to_num($amount) > $this->fungsi->get_bank_bal1($this->session->userdata('pcbankglacc'),$this->session->userdata('idcab')))
	{
		$this->form_validation->set_message('valid_amount', 'Error, your bank balances is insufficient');
		return false;
	}
	else
	{
		
		return true;
	}
	
}

//Cek valid amount
public function valid_amount_opr($amount)
{
	if($this->fungsi->convert_idr_to_num($amount) <> $this->fungsi->get_hist_pc_bal_op($this->session->userdata('idcab')))
	{
		$this->form_validation->set_message('valid_amount_opr', 'Error, Your PC OPR Balance Or Rembursement Is '.$this->fungsi->format_idr($this->fungsi->get_hist_pc_bal_op($this->session->userdata('idcab'))) );
		return false;
	}
	else
	{
		
		return true;
	}
	
}

/*------------Fungsi local------------------------*/	
	function __construct()
	{
		parent::__construct();
		
		$this->load->model('branch/branch_model', '', TRUE);
		$this->load->model('finance/fin_model', '', TRUE);
		$this->load->model('admin/admin_model', '', TRUE);
		$this->load->model('accounting/acc_model', '', TRUE);
		$this->fungsi->check_login();
	}
	
	
	public function index()
	{	
		$this->branch_add_cpv();		
	}

//Create Petty Cash Operational
function create_pcop()
	{
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_add_pc_op);
	
		$data['prev'] = '';
		
		$data['bankbalance'] = $this->fungsi->get_bank_bal($this->session->userdata('pcbankglacc'));
		
		$data['menu_path'] = 'BRANCH > PETTY CASH > CREATE PETTY CASH OPERASIONAL';
		$data['form_action']= site_url('branch/branch_cpv/add_pcopr_prev');
		$this->load->view('branch/branch_pcopr_form', $data);
	}

//Create Petty Cash Operational Preview	
function add_pcopr_prev()
	{
		//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('add'));
	
	/* Set validasi */
		$config = array(
               array(
                     'field'   => 'txt_amount',
                     'label'   => 'Amount',
                     'rules'   => 'required|callback_valid_amount_opr'
                  ),
               array(
                     'field'   => 'txt_desc',
                     'label'   => 'Description',
                     'rules'   => 'required'
                  )
            );
		$this->form_validation->set_rules($config); 
		
		if ($this->form_validation->run() == TRUE)
			{
				$data['prev'] = 1;
				$data['bankbalance'] = $this->fungsi->get_bank_bal($this->session->userdata('pcbankglacc'));
				$data['txt_amount'] =  $this->fungsi->convert_idr_to_num($this->input->post('txt_amount'));
				$data['txt_desc'] = $this->input->post('txt_desc');
				$data['txt_postdate'] = $this->input->post('txt_postdate');
				$data['menu_path'] = 'BRANCH > CPV > PREVIEW PETTY CASH OPERASIONAL';
				$data['form_action']= site_url('branch/branch_cpv/add_pcopr_proc');
				$this->load->view('branch/branch_pcopr_form', $data);
				
			}
			else
			{
				$this->create_pcop();
			}	
	}

function add_pcopr_proc()
{
	
			//Cek dulu document CPV sudah ada pada database atau belom ?
		
	  		/*$this->db->trans_begin();
			
				$this->branch_model->add_cpv($cpv);	
				$this->branch_model->add_pc_branch($pcbal);
					
			$this->db->trans_complete(); */
			
			/*if ($this->db->trans_status() === FALSE)
				{
					$this->session->set_flashdata('message_err', 'Data input error');	
					$this->db->trans_rollback();
				} 
			else 
				{	*/
				
						/*Get CPV counter*/
						$count = array();
						$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'CPV');
						$nocpvform = $count[0];
						$nocpv = $count[1];
						
						/*Get PC counter*/
						$count1 = array();
						$count1 = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'PC');
						$nopcform = $count1[0];
						$nopc = $count1[1];
						
					//Get G/L Account info
					$query_get_cab = $this->admin_model->get_cab_detail($this->session->userdata('idcab'));
					foreach ($query_get_cab->result() as $row_cab);
				
					//Post G/L Account 
					$accountgl[] = array( 'ITEMNO_ACC' => 1,
								'GL_ACCOUNT' => $row_cab->pcglaccop,
								'PSTNG_DATE' => $this->input->post('txt_postdate2'),
								'FIS_PERIOD' => $this->input->post('txt_postdate2'),
								'ALLOC_NMBR' => strtoupper($row_cab->cabshorttxt.' - '.date("M",   strtotime($this->input->post('txt_postdate2'))).'\''.date("y",   strtotime($this->input->post('txt_postdate2')))),
								'ITEM_TEXT'	 => '4904 -'.strtoupper($row_cab->cabshorttxt).'- P.Cash Oprsnl '.$nocpvform,
								);
					$accountgl[] = array( 'ITEMNO_ACC' => 2,
								'GL_ACCOUNT' => $row_cab->pcbankglacc,
								'PSTNG_DATE' => $this->input->post('txt_postdate2'),
								'FIS_PERIOD' => $this->input->post('txt_postdate2'),
								'ALLOC_NMBR' => strtoupper($row_cab->cabshorttxt.' - '.date("M",   strtotime($this->input->post('txt_postdate2'))).'\''.date("y",   strtotime($this->input->post('txt_postdate2')))),
								'ITEM_TEXT'	 => strtoupper($row_cab->cabshorttxt).'- P.Cash Oprsnl '.$nocpvform,
								);
								
					$curramount[] = array( 		'ITEMNO_ACC' => 1,
												'AMT_DOCCUR' =>$this->input->post('txt_amount'),
												);
					$curramount[] = array( 		'ITEMNO_ACC' => 2,
												'AMT_DOCCUR' =>$this->input->post('txt_amount') * -1,
												);
					
						
									
					$this->fungsi_sap->fm_post_gl_acc($nopcform,$this->input->post('txt_postdate2'),date('d.m.Y'),$nocpvform,  $accountgl,$curramount);							
				if ($this->session->userdata('sap_obj_key') != '')
				{				
				
					/*Update Saldo bank*/
					$bankbal = array( 	'idcab'		 => $this->session->userdata('idcab'),
										'sap_ref'	 => $this->session->userdata('sap_obj_key'),
										'rlis_ref'	 => $nocpvform,
										'amount'	 => $this->input->post('txt_amount') * -1,
										//Postdate
										'postdate'	 => date("Y-m-d",   strtotime($this->input->post('txt_postdate2'))),
										'addby'		 => $this->session->userdata('uid'),
										'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
					
		
		/*Insert PC cabang*/
		$cpv = array( 			'idcab'		 => $this->session->userdata('idcab'),
								'nopcform'	 => $nocpvform,
								'nopc'	 	 => $nocpv,
								'year'		 => date('Y'),
								'pctyp'		 => 2,
								'amount' 	 => $this->input->post('txt_amount'),
								'desc'		 => $this->input->post('txt_desc'),
								'addby'		 => $this->session->userdata('uid'),
								//Postdate
								'postdate'	 => date("Y-m-d",   strtotime($this->input->post('txt_postdate2'))),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								'accglno' 	 => $this->session->userdata('sap_obj_key'),
								);

		
		/*Insert Saldo Petty cash operational cabang*/
		$pcbalopr = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	 	 => $nocpvform,
								'amount' => $this->input->post('txt_amount'),
								'addby'		 => $this->session->userdata('uid'),
								//Postdate
								'postdate'	 => date("Y-m-d",   strtotime($this->input->post('txt_postdate2'))),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
								
		/*Insert Saldo History Petty cash operational cabang*/
		$hpcop = array( 	'idcab'		 =>$this->session->userdata('idcab'),
								'sap_ref'	 => $this->session->userdata('sap_obj_key'),
								'rlis_ref'	 => $nocpvform,
								'amount'	 => $this->input->post('txt_amount') * -1,
								'addby'		 => $this->session->userdata('uid'),
								//Postdate
								'postdate'	 => date("Y-m-d",   strtotime($this->input->post('txt_postdate2'))),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
				
					$this->acc_model->add_h_pcop($hpcop);						
					$this->fin_model->add_bankbal($bankbal);
					$this->branch_model->add_cpv($cpv);	
					$this->branch_model->add_pcopr_branch($pcbalopr);
				}
					$this->session->set_flashdata('message_ok', 'Data saved, petty cash number :'.$nocpvform);
					//$this->db->trans_commit();
				/*}*/
	  	  
	  	redirect('branch/branch_cpv/create_pcop');
}	
	
/*Print CPV*/
function print_cpv_popup()
{
	
	//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('view'));
	
	//Get data PC by no cpv & year
	$query_pc_edit = $this->branch_model->get_pc_bynoyear($this->uri->segment(4),$this->uri->segment(5),$this->uri->segment(6));
	foreach ($query_pc_edit->result() as $row_pc)
		{
			$data['txt_nocpvform'] = $row_pc->nopcform;
			$data['txt_accglno'] = $row_pc->accglno;
			$data['txt_adddate'] = date("d.m.Y",   strtotime($row_pc->adddate));	
			$data['txt_addby'] = $row_pc->addby;
			$data['txt_idcab'] = $row_pc->idcab;
			$data['txt_amount_trf'] =  $this->fungsi->format_idr($row_pc->amount);
			$data['txt_desc'] = $row_pc->desc;
			$data['txt_terbilang'] = $this->fungsi->terbilang($row_pc->amount).' RUPIAH';
		}
//Get data detail cabang by id cabang
				$sql_cab_detail = $this->admin_model->get_cab_detail($row_pc->idcab);
				foreach ($sql_cab_detail->result() as $row_cab)
				{	
					$data['txt_cabname'] = $row_cab->cabname;
				}
$this->load->view('popup/popup_cpv_cab', $data);
	
}
	
	function branch_add_cpv()
	{
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_add_cpv);
	
		$data['prev'] = '';
		
		$data['bankbalance'] = $this->fungsi->get_bank_bal($this->session->userdata('pcbankglacc'));
		
		$data['menu_path'] = 'BRANCH > PETTY CASH > CREATE PETTY CASH USED OIL';
		$data['form_action']= site_url('branch/branch_cpv/add_cpv_prev');
		$this->load->view('branch/branch_cpv_form', $data);
	}
	
	
	function add_cpv_prev()
	{
		//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('add'));
	
	/* Set validasi */
		$config = array(
               array(
                     'field'   => 'txt_amount',
                     'label'   => 'Amount',
                     'rules'   => 'required|callback_valid_amount'
                  ),
               array(
                     'field'   => 'txt_desc',
                     'label'   => 'Description',
                     'rules'   => 'required'
                  )
            );
		$this->form_validation->set_rules($config); 
		
		if ($this->form_validation->run() == TRUE)
			{
				$data['prev'] = 1;
				$data['bankbalance'] = $this->fungsi->get_bank_bal($this->session->userdata('pcbankglacc'));
				$data['txt_amount'] =  $this->fungsi->convert_idr_to_num($this->input->post('txt_amount'));
				$data['txt_desc'] = $this->input->post('txt_desc');
				$data['txt_postdate'] = $this->input->post('txt_postdate');
				$data['menu_path'] = 'BRANCH > CPV > PREVIEW PETTY CASH USED OIL';
				$data['form_action']= site_url('branch/branch_cpv/add_cpv_proc');
				$this->load->view('branch/branch_cpv_form', $data);
				
			}
			else
			{
				$this->branch_add_cpv();
			}
		
		
	}
	
	
function add_cpv_proc()
{
	
			//Cek dulu document CPV sudah ada pada database atau belom ?
		
	  		/*$this->db->trans_begin();
			
				$this->branch_model->add_cpv($cpv);	
				$this->branch_model->add_pc_branch($pcbal);
					
			$this->db->trans_complete(); */
			
			/*if ($this->db->trans_status() === FALSE)
				{
					$this->session->set_flashdata('message_err', 'Data input error');	
					$this->db->trans_rollback();
				} 
			else 
				{	*/
				
						/*Get CPV counter*/
						$count = array();
						$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'CPV');
						$nocpvform = $count[0];
						$nocpv = $count[1];
						
						/*Get PC counter*/
						$count1 = array();
						$count1 = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'PC');
						$nopcform = $count1[0];
						$nopc = $count1[1];
						
					//Get G/L Account info
					$query_get_cab = $this->admin_model->get_cab_detail($this->session->userdata('idcab'));
					foreach ($query_get_cab->result() as $row_cab);
				
					//Post G/L Account 
					$accountgl[] = array( 'ITEMNO_ACC' => 1,
								'GL_ACCOUNT' => $row_cab->pcglaccuo,
								'PSTNG_DATE' => $this->input->post('txt_postdate2'),
								'FIS_PERIOD' => $this->input->post('txt_postdate2'),
								'ALLOC_NMBR' => strtoupper($row_cab->cabshorttxt.' - '.date("M",   strtotime($this->input->post('txt_postdate2'))).'\''.date("y",   strtotime($this->input->post('txt_postdate2')))),
								//$row_cab->cabshorttxt.date('M').'\''.date('y'),
								
								'ITEM_TEXT'	 => '4905 -'.strtoupper($row_cab->cabshorttxt).'- P.Cash Used Oil '.$nocpvform,
								);
					$accountgl[] = array( 'ITEMNO_ACC' => 2,
								'GL_ACCOUNT' => $row_cab->pcbankglacc,
								'PSTNG_DATE' => $this->input->post('txt_postdate2'),
								'FIS_PERIOD' => $this->input->post('txt_postdate2'),
								'ALLOC_NMBR' => strtoupper($row_cab->cabshorttxt.' - '.date("M",   strtotime($this->input->post('txt_postdate2'))).'\''.date("y",   strtotime($this->input->post('txt_postdate2')))),
								//$row_cab->cabshorttxt.date('M').'\''.date('y'),
								'ITEM_TEXT'	 => strtoupper($row_cab->cabshorttxt).'- P.Cash Used Oil '.$nocpvform,
								);
								
					$curramount[] = array( 		'ITEMNO_ACC' => 1,
												'AMT_DOCCUR' =>$this->input->post('txt_amount'),
												);
					$curramount[] = array( 		'ITEMNO_ACC' => 2,
												'AMT_DOCCUR' =>$this->input->post('txt_amount') * -1,
												);
									
					$this->fungsi_sap->fm_post_gl_acc($nopcform,$this->input->post('txt_postdate2'),date( 'd.m.Y'),$nocpvform,  $accountgl,$curramount);
												
				if ($this->session->userdata('sap_obj_key') != '')
				{				
				
					/*Update Saldo bank*/
					$bankbal = array( 	'idcab'		 => $this->session->userdata('idcab'),
										'sap_ref'	 => $this->session->userdata('sap_obj_key'),
										'rlis_ref'	 => $nocpvform,
										'amount'	 => $this->input->post('txt_amount') * -1,
										//Postdate
										'postdate'	 => date("Y-m-d",   strtotime($this->input->post('txt_postdate2'))),
										'addby'		 => $this->session->userdata('uid'),
										'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
					
		
		/*Insert PC cabang*/
		$cpv = array( 			'idcab'		 => $this->session->userdata('idcab'),
								'nopcform'	 => $nocpvform,
								'nopc'	 	 => $nocpv,
								'year'		 => date('Y'),
								'pctyp'		 => 1,
								'amount' 	 => $this->input->post('txt_amount'),
								'desc'		 => $this->input->post('txt_desc'),
								'addby'		 => $this->session->userdata('uid'),
								//Postdate
								'postdate'	 => date("Y-m-d",   strtotime($this->input->post('txt_postdate2'))),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								'accglno' 	 => $this->session->userdata('sap_obj_key'),
								);

		
		/*Insert Saldo Petty cash cabang*/
		$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	 	 => $nocpvform,
								'amount' => $this->input->post('txt_amount'),
								'addby'		 => $this->session->userdata('uid'),
								//Postdate
								'postdate'	 => date("Y-m-d",   strtotime($this->input->post('txt_postdate2'))),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
	
								
					$this->fin_model->add_bankbal($bankbal);
					$this->branch_model->add_cpv($cpv);	
					$this->branch_model->add_pc_branch($pcbal);
				}
					$this->session->set_flashdata('message_ok', 'Data saved, petty cash number :'.$nocpvform);
					$this->db->trans_commit();
				/*}*/
	  	  
	  	redirect('branch/branch_cpv/');
}

function list_cpv()
{	
	//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('view'));
	
	//Otorisasi menu
	$this->fungsi->menu_auth($this->menu_print_cpv);
	
	/* Setting Parameter Untuk Paging */
		$uri_segment = 4;
		$offset =    $this->uri->segment($uri_segment);
		
		$cpv = $this->branch_model->get_list_cpv($this->session->userdata('idcab'),$this->config->item('paging_limit'), $offset)->result();
		$num_rows = $this->branch_model->get_list_cpv_count($this->session->userdata('idcab'));
		
		$config['base_url'] = site_url('branch/branch_cpv/list_cpv/');
	
		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. PC', 'Branch','Petty Cash Type','Amount', 'Desc', 'Add by','Add date','Options');
					
					$atts = array(
              'width'      => '100',
              'height'     => '100',
              'scrollbars' => 'yes',
              'status'     => 'yes',
              'resizable'  => 'yes',
              'screenx'    => '0',
              'screeny'    => '0'
            );
					
					foreach ($cpv  as $cpvs)
					{	
						$this->table->add_row($cpvs->nopcform, $cpvs->cabname , $cpvs->pcdesc , $this->fungsi->format_idr($cpvs->amount), $cpvs->desc,$cpvs->addby, $cpvs->adddate, anchor_popup('branch/branch_cpv/print_cpv_popup/'.$cpvs->nopc.'/'.$cpvs->year.'/'.$cpvs->idcab,'Print',array('class' => 'print',$atts),$atts));	
					}
					
					$data['table'] = $this->table->generate();
		}		
		else
		{
			
			$data['message'] = 'No data';
			
		}
		
		$data['menu_path'] = 'BRANCH > CPV > PRINT CPV';
		$this->load->view('branch/branch_cpv_list', $data);
	
	
}

}