<?php 
/*
Fungsi : Controller untuk op
*/

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

class Cabang_op_det 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_list_op  = 62;
	var $menu_cancel_op  = 142 ;
	var $menu_add_op = 61;
	
/*-------------Inisialisasi variabel--------------*/

/*------------Fungsi local------------------------*/
//Cek valid Vol
public function valid_vol($volume)
{
	
	if( ($this->fungsi->hapus_koma($this->input->post('vol'))) > ($this->fungsi->hapus_koma($this->input->post('quantity')) - $this->fungsi->get_vol($this->input->post('prnumb'),date('Y'))))
	{
		$this->form_validation->set_message('valid_vol', 'Error, your Volume balances is bigger then Quantity');
		return false;
	}
	else
	{
		
		return true;
	}
	
}	

//Cek valid PR
public function valid_pr($prnumb)
{
	//Count PR
	$query = $this->db->query("SELECT count(*) as tot FROM `m_op` where prnumb ='".$prnumb."' and year = '".date('Y')."' AND cancel = 0");
	foreach($query->result() as $row);
	 
	if( $row->tot > 0)
	{
		$this->form_validation->set_message('valid_pr', 'Error, your PR cannot contain an item, please select another PR');
		return false;
	}
	else
	{
		
		return true;
	}
	
}	
		
/*------------Fungsi local------------------------*/
	
	function __construct()
	{
		parent::__construct();
		
		$this->load->model('finance/fin_model', '', TRUE);
		$this->load->model('branch/cabang_model', '', TRUE);
		$this->load->model('branch/branch_model', '', TRUE);
		$this->load->model('admin/admin_model', '', TRUE);
		$this->fungsi->check_login();
	}
	
	
	public function index()
	{	
		$this->cabang_add_op();
		
	}
	
	/* Cabang add op dan hitung pembelian oli dengan PPN*/
	function cabang_add_op_tax()
	{	
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_add_op);
		$data['menu_path'] = 'BRANCH > OIL PURCHASE > ADD OIL PURCHASE WITH PPN';
		$data['form_action']= site_url('branch/cabang_op_det/add_op_tax_proc');
		//$data['form_action2']= site_url('branch/cabang_op_det/add_po');
		$this->load->view('branch/cabang_op_tax_form', $data);
		
	}
	
	
	/* Insert OP with PPN Process */
	function add_op_tax_proc()
	{
		
		$data_po =  $this->branch_model->get_po_byprno($this->input->post('prnumb'), date('Y'));
		foreach ($data_po->result() as $row_po);

		$ponum = $row_po->ebeln;
		
		//Check vendor condition price
		if($this->fungsi_sap->fm_check_ppn($this->input->post('idsupp'))=='')
		{
			$this->session->set_flashdata('message_err', 'Error, Field Schema group, vend is empty!');
			redirect('branch/cabang_op_det/cabang_add_op_tax');
		}
		
		//Check vendor G/L
		if($this->fungsi_sap->fm_check_gl($this->input->post('idsupp'))=='')
		{
			$this->session->set_flashdata('message_err', 'Error, G/L Account must be 2121106!');
			redirect('branch/cabang_op_det/cabang_add_op_tax');
		}
		
		//Check dulu apakah PP sudah ada itemnya atau belum?
		//Config utk validasi form op
		$op = array(	
				  array(
                     'field'   => 'prnumb',
                     'label'   => 'PR Number',
                     'rules'   => 'required|callback_valid_pr'
                  ),
                  array(
                     'field'   => 'donumb',
                     'label'   => 'DO Number',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'invoice',
                     'label'   => 'Invoice',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'mnfst',
                     'label'   => 'Manifest',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'vnumb',
                     'label'   => 'Vehicle Number',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'vol',
                     'label'   => 'Volume',
                     'rules'   => 'required|callback_valid_vol'
                  ),
				  array(
                     'field'   => 'pur',
                     'label'   => 'Purchase Price ',
                     'rules'   => 'required'
                  )
				  ,
				  array(
                     'field'   => 'inf',
                     'label'   => 'Information',
                     'rules'   => 'required'
					 )
				  //Not validate form
				  ,array(
                     'field'   => 'idsupp',
                     'label'   => 'ID Supplier',
                     'rules'   => ''
                  )
				   ,array(
                     'field'   => 'idtrans',
                     'label'   => 'ID Transporter',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'adddate',
                     'label'   => 'Add Date',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'chdate',
                     'label'   => 'Change Date',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'chby',
                     'label'   => 'Change By',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'addby',
                     'label'   => 'Add By',
                     'rules'   => ''
                  )
				   //Not validate form
            );
			
		//Data Type form
		//$this->load->helper('form'); 
		
		//Get Tax
		$tax = $this->fungsi->convert_idr_to_num($this->input->post('pur')) * 10 / 100;
/*-----------------------------------------Check Saldo------------------------------------------------*/
			if($this->input->post('type2') == 2)
				{
			//Check Saldo Bank
					if($this->fungsi->get_bank_bal1($this->session->userdata('idcab')) < $this->fungsi->convert_idr_to_num($this->input->post('pur')) + $tax)
					{
						$this->session->set_flashdata('message_err', 'Error, Your Bank Balances Is Insufficient!');
						redirect('branch/cabang_op_det/cabang_add_op_tax');
						
					}
				}
			else
				{
			//Check Petty Cash
					if($this->fungsi->get_pc_bal($this->session->userdata('idcab')) < $this->fungsi->convert_idr_to_num($this->input->post('pur')) + $tax)
					{
						$this->session->set_flashdata('message_err', 'Error, Your Petty Cash Balances Is Insufficient!');
						redirect('branch/cabang_op_det/cabang_add_op_tax');
						
					}
				}
/*-----------------------------------------Check Saldo------------------------------------------------*/
				
		//Check validasi form
		$this->form_validation->set_rules($op); 
		
		if ($this->form_validation->run() == TRUE)
			{
		
			
/*-----------------------------------------Add OP Process------------------------------------------------*/
				
			/*Get OP counter*/
			$count = array();
			$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'OP');
			$noopform = $count[0];
			$noop = $count[1];
			
			/* Jika pilihan transfer dari Bank */
			if($this->input->post('type2') == 2)
			{
				
						/*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];
						
				//Journal SAP
				//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('adddate'),
								'FIS_PERIOD' => $this->input->post('adddate'),
								'ALLOC_NMBR' => strtoupper($row_cab->cabshorttxt.' - '.date("M",   strtotime($this->input->post('adddate'))).'\''.date("Y",   strtotime($this->input->post('adddate')))),
								'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('adddate'),
								'FIS_PERIOD' => $this->input->post('adddate'),
								'ALLOC_NMBR' => strtoupper($row_cab->cabshorttxt.' - '.date("M",   strtotime($this->input->post('adddate'))).'\''.date("Y",   strtotime($this->input->post('adddate')))),
								'ITEM_TEXT'	 => strtoupper($row_cab->cabshorttxt).'- P.Cash Used Oil '.$nocpvform,
								);
								
					$curramount[] = array( 		'ITEMNO_ACC' => 1,
												'AMT_DOCCUR' =>$this->fungsi->convert_idr_to_num($this->input->post('pur'))+ $tax,
												);
					$curramount[] = array( 		'ITEMNO_ACC' => 2,
												'AMT_DOCCUR' => ($this->fungsi->convert_idr_to_num($this->input->post('pur')) + $tax) * -1,
												);
					
						
									
					$this->fungsi_sap->fm_post_gl_acc($nopcform,$this->input->post('adddate'),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->fungsi->convert_idr_to_num($this->input->post('pur'))+ $tax) * -1,
										'addby'		 => $this->session->userdata('uid'),
										'postdate'  	=> date("Y-m-d", strtotime($this->input->post('adddate'))),
										'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->fungsi->convert_idr_to_num($this->input->post('pur'))+ $tax,
								'desc'		 => $this->input->post('inf'),
								'postdate'  	=> date("Y-m-d", strtotime($this->input->post('adddate'))),
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								'accglno' 	 => $this->session->userdata('sap_obj_key'),
								);
			
					$this->fin_model->add_bankbal($bankbal);
					$this->branch_model->add_cpv($cpv);	
				}
					
				
			}
		
		else
		{				
					/*Insert to t_pcbal*/
		$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	     => $noopform,
								'amount' 	 =>  ($this->fungsi->convert_idr_to_num($this->input->post('pur'))+ $tax) * -1,
								'addby'		 => $this->session->userdata('uid'),
								'postdate'  	=> date("Y-m-d", strtotime($this->input->post('adddate'))),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
			/*Insert to t_stockbal*/
		/*$salbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	 => $noopform,
								'qty'		 => $this->input->post('vol'),
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);*/
			$this->branch_model->add_pc_branch($pcbal);
		}	
		
			/* Insert data op */
			$op = array( 		'c_amt_bapi'=> $this->fungsi->convert_idr_to_num($this->input->post('c_amt_bapi')),
								'prnumb'	=> $this->input->post('prnumb'),
								'opnumb'	=> $noopform,
								'idcab'		=> $this->session->userdata('idcab'),
								'type'	    => $this->input->post('type'),
								'idsupp'	=> $this->input->post('idsupp'),
								'idtrans'	=> $this->input->post('idtrans'),
								'idstb'	    => $this->input->post('idstb'),
								'pur'		=> $this->fungsi->convert_idr_to_num($this->input->post('pur')) + $tax,
								'fee'		=> $this->fungsi->convert_idr_to_num($this->input->post('fee')),
								'quantity'	=> $this->fungsi->hapus_koma($this->input->post('quantity')),
								'invoice'	=> $this->input->post('invoice'),
								'vol'		=> $this->fungsi->hapus_koma($this->input->post('vol')),
								//'date'	    => date("Y-m-d", strtotime($this->input->post('date'))),
								'vnumb'  	=> $this->input->post('vnumb'),
								'total'	    => $this->fungsi->convert_idr_to_num($this->input->post('total')),
								'donumb'	=> $this->input->post('donumb'),
								'year'	    => date('Y'),
								'tax'	    => 1,
								'mnfst'	    => $this->input->post('mnfst'),
								'inf'	    => $this->input->post('inf'),
								'postdate'  => date("Y-m-d", strtotime($this->input->post('adddate'))),
								'adddate' 	=> date( 'Y-m-d H:i:s'),
								'chdate'	=> $this->input->post('chdate'),
								'chby'		=> $this->input->post('chby'),
								'addby'		=> $this->session->userdata('uid'),
								'ambil'		=> $this->input->post('type2'),
								'nocpvform'	=> $nocpvform,
								
						);
						
			$this->cabang_model->add_op($op);
			
			
			/*Update Data STB*/
			$stb = array( 		'closed'	 => 1,
							'chby'		 => $this->session->userdata('uid'),
							'chdate' 	 => date( 'Y-m-d H:i:s'),
								);

			$this->cabang_model->update_stb($this->input->post('idstb'), $stb);

/*-----------------------------------------Create PO Process------------------------------------------------*/
			
			//Get harga satuan
			$hargasatuan = ceil( $this->fungsi->convert_idr_to_num($this->input->post('pur')) / $this->fungsi->hapus_koma($this->input->post('vol')));
			
			//Get selisih harga satuan
			$a = ($hargasatuan * $this->fungsi->hapus_koma($this->input->post('vol'))) - $this->fungsi->convert_idr_to_num($this->input->post('pur'));
			
			
			//Edit PR
			$this->fungsi_sap->fm_edit_pr($this->input->post('prnumb'),$this->fungsi->hapus_koma($this->input->post('vol')),$hargasatuan,$this->session->userdata('pic'));
	
	if($ponum == '')
	{
	//Create PO
	$this->fungsi_sap->fm_create_po($this->input->post('idsupp'), $this->session->userdata('lgort'), $this->fungsi->hapus_koma($this->input->post('vol')),'V1',$hargasatuan,$this->input->post('prnumb'),$this->session->userdata('pic'),$a);
	}
	else
	{
		//Edit PO
		 $this->fungsi_sap->fm_change_po($ponum,$this->fungsi->hapus_koma($this->input->post('vol')),$hargasatuan,$a);
	}
	//Sleep 2 detik
	sleep(2);
	
	
	if($ponum == '')
	{
		//Ongkos Angkut
		$oa = $this->fungsi->get_oa_trf($this->session->userdata('idcab'),date('Y-m-d')) * $this->fungsi->hapus_koma($this->input->post('vol'));
		$this->fungsi_sap->fm_add_oa($this->session->userdata('sap_po_num'),$oa,'I');
	}
	else
	{
		//Ongkos Angkut
		$oa = $this->fungsi->get_oa_trf($this->session->userdata('idcab'),date('Y-m-d')) * $this->fungsi->hapus_koma($this->input->post('vol'));
		$this->fungsi_sap->fm_add_oa($ponum,$oa,'U');
	}
	
	//MIGO
	$this->fungsi_sap->fm_create_migo($this->session->userdata('sap_po_num'),$this->session->userdata('lgort'),$this->input->post('idsupp'),$this->session->userdata('cabshorttxt'),'Used Oil',$this->fungsi->hapus_koma($this->input->post('vol')),$this->session->userdata('sap_po_num'),$this->input->post('adddate'));
	
	//Update status PR = Close
	$pr = array(        'c_amt_bapi' => $hargasatuan,
						'quantity'	 => $this->fungsi->hapus_koma($this->input->post('vol')),
						'closed'	 => 1,
						'clby'		 => $this->session->userdata('uid'),
						'cldate' 	 => date( 'Y-m-d H:i:s'),
								);
	//Insert PO Data
	$po = array(		'ebeln' => $this->session->userdata('sap_po_num'),
						'idcab'	=> $this->session->userdata('idcab'),
						'preq_no' => $this->input->post('prnumb'),
						'vendor' => $this->input->post('idsupp'),
						'mblnr' => $this->session->userdata('sap_migo_num'),
						'year' => date('Y'),
				       	'net_price' => $hargasatuan,
						'tax' => $tax,
						'disc' => $a,
						'quantity'	 => $this->fungsi->hapus_koma($this->input->post('vol')),
						'addby'		 => $this->session->userdata('uid'),
						'postdate'  	=> date("Y-m-d", strtotime($this->input->post('adddate'))),
						'adddate' 	 => date( 'Y-m-d H:i:s'),
						'vendor_name' 	 => $this->input->post('nama_supp'),
						);
		//Edit PO Data
	$po_edit = array(	//'ebeln' => $this->session->userdata('sap_po_num'),
						//'idcab'	=> $this->session->userdata('idcab'),
						//'preq_no' => $this->input->get('nopr'),
						//'vendor' => $this->session->userdata('lifnr'),
						'mblnr' => $this->session->userdata('sap_migo_num'),
						//'year' => date('Y'),
				       	'net_price' => $hargasatuan,
						'disc' => $a,
						'tax' => $tax,
						'quantity'	 => $this->fungsi->hapus_koma($this->input->post('vol')),
						'addby'		 => $this->session->userdata('uid'),
						'adddate' 	 => date( 'Y-m-d H:i:s'),
						);
	/*Insert Saldo Petty cash cabang*/
		/*$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	 	 => $this->session->userdata('sap_po_num'),
								'amount' 	=> ( $row_pr->c_amt_bapi * $row_pr->quantity ) * -1,
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);*/
				
	if( $this->session->userdata('sap_po_num') != '' )
	{
		$this->branch_model->update_pr($this->input->post('prnumb'),date('Y'),$pr);	
		
		if($ponum == '')
		{						
			$this->branch_model->add_po($po);
			
			
		}
		else
		{
			$this->branch_model->update_po($ponum, date('Y'),$po_edit);
		}
		
		//Disable utk sementara
	/*	$a = ($this->input->get('totpur') + $this->input->get('totfee')) / $this->input->get('totvol');
		if($a != $this->input->get('average'))
		{
			
			
		$count = array();
		$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'OP');
		$noopform = $count[0];
		$noop = $count[1];

			$op_fee = array( 	'c_amt_bapi'=> $this->fungsi->hapus_koma($this->input->post('c_amt_bapi')),
								'prnumb'	=> $this->input->get('nopr'),
								'opnumb'	=> $noopform,
								'idcab'		=> $this->session->userdata('idcab'),
								'type'	    => $this->input->post('type'),
								'idsupp'	=> $this->input->post('idsupp'),
								'idtrans'	=> $this->input->post('idtrans'),
								'pur'		=> $this->fungsi->hapus_koma($this->input->post('pur')),
								'fee'		=>  abs(($a - $this->input->get('average')) * $this->input->get('totvol')),
								'quantity'	=> $this->fungsi->hapus_koma($this->input->post('quantity')),
								'invoice'	=> $this->input->post('invoice'),
								'vol'		=> $this->input->post('vol'),
								'vnumb'  	=> $this->input->post('vnumb'),
								'total'	    => $this->fungsi->hapus_koma($this->input->post('total')),
								'donumb'	=> $this->input->post('donumb'),
								'year'	    => date('Y'),
								'mnfst'	    => $this->input->post('mnfst'),
								'inf'	    => 'PEMBULATAN',
								'adddate' 	=> date( 'Y-m-d H:i:s'),
								'addby'		=> $this->session->userdata('uid'),
								);
		
					$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
											'ref'	 	 => $noopform,
											'amount' 	 => abs(($a - $this->input->get('average')) * $this->input->get('totvol')) * -1,
											'addby'		 => $this->session->userdata('uid'),
											'adddate' 	 => date( 'Y-m-d H:i:s'),
								);

			$this->cabang_model->add_op_fee($op_fee);
			$this->branch_model->add_pc_branch($pcbal);
		}*/
		
		
		//Update petty cash balance
		//$this->branch_model->add_pc_branch($pcbal);
	}
	
	
	if( $this->session->userdata('sap_migo_num') != '' )
	{
		$po_mutasi = array(	'ebeln' => $this->session->userdata('sap_po_num'),
						'idcab'	=> $this->session->userdata('idcab'),
						'qty' => $this->fungsi->hapus_koma($this->input->post('vol')),
						'oa' => $this->fungsi->get_oa_trf($this->session->userdata('idcab'),date('Y-m-d')),
						'addby'		 => $this->session->userdata('uid'),
						'adddate' 	 => date( 'Y-m-d H:i:s'),
						);
						
	/*if	($this->session->userdata('idcab')!=6)			
		{	*/			
		//Insert Table mutasi PO
		//$this->db->insert('t_po_mutasi',$po_mutasi); 		
	/*}*/
		//Insert ke table stock
		//Insert Stock
		$stock = array(	'ref' => $this->session->userdata('sap_migo_num'),
						'idcab'	=> $this->session->userdata('idcab'),
						'qty' => $this->fungsi->hapus_koma($this->input->post('vol')),
						'year' => date('Y'),
						'addby'	=> $this->session->userdata('uid'),
						'postdate'  	=> date("Y-m-d", strtotime($this->input->post('adddate'))),
						'adddate' => date( 'Y-m-d H:i:s'),
								);
		$this->branch_model->add_stock($stock);	
		
		//Email to accounting
		//send email notification
		$total = (($hargasatuan * $this->fungsi->hapus_koma($this->input->post('vol'))) - $a) + $tax;
			$var = array($this->session->userdata('sap_migo_num'), $this->session->userdata('uid'),$this->session->userdata('sap_po_num'),number_format($this->fungsi->hapus_koma($this->input->post('vol'))), $this->fungsi->format_idr($total), $this->fungsi->format_idr($a), $this->fungsi->format_idr($tax));
			$this->fungsi->send_notif(11, $var);
	}		
/*-----------------------------------------Create PO Process------------------------------------------------*/
			
			//$this->session->set_flashdata('prnumb', $this->input->post('prnumb'));
			$this->session->set_flashdata('message_ok', 'Data saved, Purchase number :'.$noopform.', PO number :'.$this->session->userdata('sap_po_num'));
			redirect('branch/cabang_op_det/cabang_add_op_tax');
			
/*-----------------------------------------Add OP Process------------------------------------------------*/
			
			}
		else
			{
				$this->cabang_add_op_tax();
			}
	}
	
	function add_po()
	
{
		//Get selisih pembulatan
		$a = ($this->input->get('average') * $this->input->get('totvol')) - ($this->input->get('totpur') + $this->input->get('totfee'));
		
		//Edit sementara
		//Cek Saldo Petty cash dulu jika ada pembualatan
		//pembulatan
		//$a = ($this->input->get('totpur') + $this->input->get('totfee')) / $this->input->get('totvol');
		/*if($a != $this->input->get('average'))
		{
			//Check Petty Cash
				if($this->fungsi->get_pc_bal($this->session->userdata('idcab')) < abs(($a - $this->input->get('average')) * $this->input->get('totvol')))
				{
					$this->session->set_flashdata('message_err', 'Error, Your Petty Cash Balances Is Insufficient!');
					redirect('branch/cabang_op_det');
					
				}
		}*/
	//Edit PR
	$this->fungsi_sap->fm_edit_pr($this->input->get('nopr'),$this->input->get('totvol'),$this->input->get('average'),$this->session->userdata('pic'));
	
	if($this->input->get('txt_po') == '')
	{
	//Create PO
	$this->fungsi_sap->fm_create_po($this->session->userdata('lifnr'), $this->session->userdata('lgort'), $this->input->get('totvol'),'V0',$this->input->get('average'),$this->input->get('nopr'),$this->session->userdata('pic'),$a);
	
	
	
	}
	else
	{
		//Edit PO
		 $this->fungsi_sap->fm_change_po($this->input->get('txt_po'),$this->input->get('totvol'),$this->input->get('average'),$a);
		 
	}
	//Sleep 2 detik
	sleep(2);
	
	if($this->input->get('txt_po') == '')
	{
		//Ongkos Angkut
	$oa = $this->fungsi->get_oa_trf($this->session->userdata('idcab'),date('Y-m-d')) * $this->input->get('totvol');
	$this->fungsi_sap->fm_add_oa($this->session->userdata('sap_po_num'),$oa,'I');
	}
	else
	{
		 //Ongkos Angkut
		$oa = $this->fungsi->get_oa_trf($this->session->userdata('idcab'),date('Y-m-d')) * $this->input->get('totvol');
		$this->fungsi_sap->fm_add_oa($this->input->get('txt_po'),$oa,'U');
	}
	//MIGO
	$this->fungsi_sap->fm_create_migo($this->session->userdata('sap_po_num'),$this->session->userdata('lgort'),$this->session->userdata('lifnr'),$this->session->userdata('cabshorttxt'),'Used Oil',$this->input->get('totvol'),$this->session->userdata('sap_po_num'),$this->input->get('txt_postdate'));
	
	//Update status PR = Close
	$pr = array(        'c_amt_bapi' => $this->input->get('average'),
						'quantity'	 => $this->input->get('totvol'),
						'closed'	 => 1,
						'clby'		 => $this->session->userdata('uid'),
						'cldate' 	 => date( 'Y-m-d H:i:s'),
								);
	////Update status OP = Close
//	$op = array(       	'closed'	 => 1,
//						'clby'		 => $this->session->userdata('uid'),
//						'cldate' 	 => date( 'Y-m-d H:i:s'),
//								);
	//Insert PO Data
	$po = array(		'ebeln' => $this->session->userdata('sap_po_num'),
						'idcab'	=> $this->session->userdata('idcab'),
						'preq_no' => $this->input->get('nopr'),
						'vendor' => $this->session->userdata('lifnr'),
						'mblnr' => $this->session->userdata('sap_migo_num'),
						'year' => date('Y'),
				       	'net_price' => $this->input->get('average'),
						'disc' => $a,
						'quantity'	 => $this->input->get('totvol'),
						'addby'		 => $this->session->userdata('uid'),
						//postdate
						'postdate' 	 => date("Y-m-d",   strtotime($this->input->get('txt_postdate'))),
						'adddate' 	 => date( 'Y-m-d H:i:s'),
						'vendor_name' 	 => '',
						);
	//Edit PO Data
	$po_edit = array(	//'ebeln' => $this->session->userdata('sap_po_num'),
						//'idcab'	=> $this->session->userdata('idcab'),
						//'preq_no' => $this->input->get('nopr'),
						//'vendor' => $this->session->userdata('lifnr'),
						'mblnr' => $this->session->userdata('sap_migo_num'),
						//'year' => date('Y'),
				       	'net_price' => $this->input->get('average'),
						'disc' => $a,
						'quantity'	 => $this->input->get('totvol'),
						'addby'		 => $this->session->userdata('uid'),
						'adddate' 	 => date( 'Y-m-d H:i:s'),
						);
	/*Insert Saldo Petty cash cabang*/
		/*$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	 	 => $this->session->userdata('sap_po_num'),
								'amount' 	=> ( $row_pr->c_amt_bapi * $row_pr->quantity ) * -1,
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);*/
	
	if( $this->session->userdata('sap_po_num') != '' )
	{
		$this->branch_model->update_pr($this->input->get('nopr'),$this->input->get('year'),$pr);	
		
		if($this->input->get('txt_po') == '')
		{						
			$this->branch_model->add_po($po);
		}
		else
		{
			$this->branch_model->update_po($this->input->get('txt_po'), $this->input->get('year'),$po_edit);
		}
		//Disable utk sementara
	/*	$a = ($this->input->get('totpur') + $this->input->get('totfee')) / $this->input->get('totvol');
		if($a != $this->input->get('average'))
		{
			
			
		$count = array();
		$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'OP');
		$noopform = $count[0];
		$noop = $count[1];

			$op_fee = array( 	'c_amt_bapi'=> $this->fungsi->hapus_koma($this->input->post('c_amt_bapi')),
								'prnumb'	=> $this->input->get('nopr'),
								'opnumb'	=> $noopform,
								'idcab'		=> $this->session->userdata('idcab'),
								'type'	    => $this->input->post('type'),
								'idsupp'	=> $this->input->post('idsupp'),
								'idtrans'	=> $this->input->post('idtrans'),
								'pur'		=> $this->fungsi->hapus_koma($this->input->post('pur')),
								'fee'		=>  abs(($a - $this->input->get('average')) * $this->input->get('totvol')),
								'quantity'	=> $this->fungsi->hapus_koma($this->input->post('quantity')),
								'invoice'	=> $this->input->post('invoice'),
								'vol'		=> $this->input->post('vol'),
								'vnumb'  	=> $this->input->post('vnumb'),
								'total'	    => $this->fungsi->hapus_koma($this->input->post('total')),
								'donumb'	=> $this->input->post('donumb'),
								'year'	    => date('Y'),
								'mnfst'	    => $this->input->post('mnfst'),
								'inf'	    => 'PEMBULATAN',
								'adddate' 	=> date( 'Y-m-d H:i:s'),
								'addby'		=> $this->session->userdata('uid'),
								);
		
					$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
											'ref'	 	 => $noopform,
											'amount' 	 => abs(($a - $this->input->get('average')) * $this->input->get('totvol')) * -1,
											'addby'		 => $this->session->userdata('uid'),
											'adddate' 	 => date( 'Y-m-d H:i:s'),
								);

			$this->cabang_model->add_op_fee($op_fee);
			$this->branch_model->add_pc_branch($pcbal);
		}*/
		
		
		//Update petty cash balance
		//$this->branch_model->add_pc_branch($pcbal);
	}
	
	
	if( $this->session->userdata('sap_migo_num') != '' )
	{
		//Insert table mutasi PO
		$po_mutasi = array(	'ebeln' => $this->session->userdata('sap_po_num'),
							'idcab'	=> $this->session->userdata('idcab'),
							'qty' => $this->input->get('totvol'),
							'oa' => $this->fungsi->get_oa_trf($this->session->userdata('idcab'),date('Y-m-d')),
							'addby'		 => $this->session->userdata('uid'),
							'adddate' 	 => date( 'Y-m-d H:i:s'),
						);
	/*if	($this->session->userdata('idcab')!=6)			
		{	*/					
		//Insert Table mutasi PO
		//$this->db->insert('t_po_mutasi',$po_mutasi); 
	/*}*/
		//Insert ke table stock
		//Insert Stock
		$stock = array(	'ref' => $this->session->userdata('sap_migo_num'),
						'idcab'	=> $this->session->userdata('idcab'),
						'qty' => $this->input->get('totvol'),
						'year' => date('Y'),
						'addby'	=> $this->session->userdata('uid'),
						//postdate
						'postdate' 	 => date("Y-m-d",   strtotime($this->input->get('txt_postdate'))),
						'adddate' => date( 'Y-m-d H:i:s'),
								);
		$this->branch_model->add_stock($stock);	
		
		//Email to accounting
		//send email notification
		$total = ($this->input->get('average') * $this->input->get('totvol')) - $a;
			$var = array($this->session->userdata('sap_migo_num'), $this->session->userdata('uid'),$this->session->userdata('sap_po_num'),number_format($this->input->get('totvol')), $this->fungsi->format_idr($total), $this->fungsi->format_idr($a),0 );
			$this->fungsi->send_notif(11, $var);
	}
	
	$this->session->set_flashdata('message_ok', 'PO Created, PO number :'.$this->session->userdata('sap_po_num'));
	redirect('branch/branch_po/list_po');
}


	
	/* Cabang add op dan hitung pembelian oli*/
	function cabang_add_op()
	{	
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_add_op);
		$data['menu_path'] = 'BRANCH > OIL PURCHASE > ADD OIL PURCHASE';
		$data['form_action']= site_url('branch/cabang_op_det/add_op_proc');
		$data['form_action2']= site_url('branch/cabang_op_det/add_po');
		$this->load->view('branch/cabang_op_form', $data);
		
	}
			
	/* Cabang add op process */
	function add_op_proc()
	{	
			
		//Check otorisasi transaksi
		$this->fungsi->trans_auth($this->session->userdata('add'));
		
		

/*-----------------------------------------Check Saldo------------------------------------------------*/


		if($this->input->post('type2') == 2)
			{
		//Check Saldo Bank
				if($this->fungsi->get_bank_bal1($this->session->userdata('idcab')) < $this->fungsi->convert_idr_to_num($this->input->post('pur')))
				{
					$this->session->set_flashdata('message_err', 'Error, Your Bank Balances Is Insufficient!');
					redirect('branch/cabang_op_det');
					
				}
			}
		else
			{
		//Check Petty Cash
				if($this->fungsi->get_pc_bal($this->session->userdata('idcab')) < $this->fungsi->convert_idr_to_num($this->input->post('pur')))
				{
					$this->session->set_flashdata('message_err', 'Error, Your Petty Cash Balances Is Insufficient!');
					redirect('branch/cabang_op_det');
					
				}
			}

/*-----------------------------------------Check Saldo------------------------------------------------*/
		
		
		$data['prev'] = '';
		
		//Config utk validasi form op
	$op = array(
                  array(
                     'field'   => 'donumb',
                     'label'   => 'DO Number',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'invoice',
                     'label'   => 'Invoice',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'mnfst',
                     'label'   => 'Manifest',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'vnumb',
                     'label'   => 'Vehicle Number',
                     'rules'   => 'required'
                  ),
				  array(
                     'field'   => 'vol',
                     'label'   => 'Volume',
                     'rules'   => 'required|callback_valid_vol'
                  ),
				  array(
                     'field'   => 'pur',
                     'label'   => 'Purchase Price ',
                     'rules'   => 'required'
                  )
				  //Not validate form
				  ,array(
                     'field'   => 'idsupp',
                     'label'   => 'ID Supplier',
                     'rules'   => ''
                  )
				   ,array(
                     'field'   => 'idtrans',
                     'label'   => 'ID Transporter',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'adddate',
                     'label'   => 'Add Date',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'chdate',
                     'label'   => 'Change Date',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'chby',
                     'label'   => 'Change By',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'addby',
                     'label'   => 'Add By',
                     'rules'   => ''
                  )
				   //Not validate form
            );
			
		//Data Type form
		$this->load->helper('form'); 
		
		
	
		//Check validasi form
		$this->form_validation->set_rules($op); 
		
		if ($this->form_validation->run() == TRUE)
			{
			
			
			/*Get OP counter*/
			$count = array();
			$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'OP');
			$noopform = $count[0];
			$noop = $count[1];
		
			
		/* Jika pilihan transfer dari Bank */
			if($this->input->post('type2') == 2)
			{
						/*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];
				//Journal SAP
				//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('posting'),
								'FIS_PERIOD' => $this->input->post('posting'),
								'ALLOC_NMBR' => strtoupper($row_cab->cabshorttxt.' - '.date("M",   strtotime($this->input->post('txt_postdate'))).'\''.date("Y",   strtotime($this->input->post('txt_postdate')))),
								'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('posting'),
								'FIS_PERIOD' => $this->input->post('posting'),
								'ALLOC_NMBR' => strtoupper($row_cab->cabshorttxt.' - '.date("M",   strtotime($this->input->post('txt_postdate'))).'\''.date("Y",   strtotime($this->input->post('txt_postdate')))),
								'ITEM_TEXT'	 => strtoupper($row_cab->cabshorttxt).'- P.Cash Used Oil '.$nocpvform,
								);
								
					$curramount[] = array( 		'ITEMNO_ACC' => 1,
												'AMT_DOCCUR' =>$this->fungsi->convert_idr_to_num($this->input->post('pur')),
												);
					$curramount[] = array( 		'ITEMNO_ACC' => 2,
												'AMT_DOCCUR' =>$this->fungsi->convert_idr_to_num($this->input->post('pur')) * -1,
												);
								
					$this->fungsi_sap->fm_post_gl_acc($nopcform,$this->input->post('posting'),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->fungsi->convert_idr_to_num($this->input->post('pur')) * -1,
										'postdate'  	=> date("Y-m-d", strtotime($this->input->post('posting'))),
										'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->fungsi->convert_idr_to_num($this->input->post('pur')),
								'desc'		 => $this->input->post('inf'),
								'postdate'  	=> date("Y-m-d", strtotime($this->input->post('posting'))),
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								'accglno' 	 => $this->session->userdata('sap_obj_key'),
								);
			
					$this->fin_model->add_bankbal($bankbal);
					$this->branch_model->add_cpv($cpv);	
				}
					
				
			}
		
		else
		{				
					/*Insert to t_pcbal*/
		$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	     => $noopform,
								'amount' 	 => $this->fungsi->convert_idr_to_num($this->input->post('pur')) * -1,
								'addby'		 => $this->session->userdata('uid'),
								'postdate'  	=> date("Y-m-d", strtotime($this->input->post('posting'))),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
			/*Insert to t_stockbal*/
		/*$salbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	 => $noopform,
								'qty'		 => $this->input->post('vol'),
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);*/
			$this->branch_model->add_pc_branch($pcbal);
		}	
		
			/* Insert data op */
			$op = array( 		'c_amt_bapi'=> $this->fungsi->convert_idr_to_num($this->input->post('c_amt_bapi')),
								'prnumb'	=> $this->input->post('prnumb'),
								'opnumb'	=> $noopform,
								'idcab'		=> $this->session->userdata('idcab'),
								'type'	    => $this->input->post('type'),
								'idsupp'	=> $this->input->post('idsupp'),
								'suppname'	=> $this->input->post('suppname'),
								'idtrans'	=> $this->input->post('idtrans'),
								'transname'	=> $this->input->post('transname'),
								'idstb'	    => $this->input->post('idstb'),
								'pur'		=> $this->fungsi->convert_idr_to_num($this->input->post('pur')),
								'fee'		=> $this->fungsi->convert_idr_to_num($this->input->post('fee')),
								'quantity'	=> $this->fungsi->hapus_koma($this->input->post('quantity')),
								'invoice'	=> $this->input->post('invoice'),
								'vol'		=> $this->fungsi->hapus_koma($this->input->post('vol')),
								'vnumb'  	=> $this->input->post('vnumb'),
								'total'	    => $this->fungsi->convert_idr_to_num($this->input->post('total')),
								'donumb'	=> $this->input->post('donumb'),
								'year'	    => date('Y'),
								'mnfst'	    => $this->input->post('mnfst'),
								'inf'	    => $this->input->post('inf'),
								'postdate'  	=> date("Y-m-d", strtotime($this->input->post('posting'))),
								'adddate' 	=> date( 'Y-m-d H:i:s'),
								'chdate'	=> $this->input->post('chdate'),
								'chby'		=> $this->input->post('chby'),
								'addby'		=> $this->session->userdata('uid'),
								'ambil'		=> $this->input->post('type2'),
								'nocpvform'	=> $nocpvform,	
						);
						
						/*Update Data STB*/
		$stb = array( 		'closed'	 => 1,
							'chby'		 => $this->session->userdata('uid'),
							'chdate' 	 => date( 'Y-m-d H:i:s'),
								);
								
			$this->cabang_model->add_op($op);
			$this->cabang_model->update_stb($this->input->post('idstb'), $stb);
			
			/*Set pesan sukses dan kembali ke menu add op*/
			
			$this->session->set_flashdata('prnumb', $this->input->post('prnumb'));
			$this->session->set_flashdata('message_ok', 'Data saved, Purchase number :'.$noopform);
			redirect('branch/cabang_op_det');
			}
		else
			{
				$this->cabang_add_op();
			}
	}
	
/*======================================================INSERT TO OP FEE=================================================*/
	
	
	/* Cabang add op fee*/
	function cabang_add_op_fee()
	{	
	
			
		if($this->session->flashdata('prnumb')!="")
			$data['data_op'] = $this->cabang_model->get_all_op($this->session->flashdata('prnumb'));
		
		$data['menu_path'] = 'BRANCH > OIL PURCHASE > ADD OIL PURCHASE FEE';
		$data['form_action']= site_url('branch/cabang_op_det/add_op_proc_fee');
		$data['form_action2']= site_url('branch/cabang_op_det/add_op_proc_fee');
		$this->load->view('branch/op_detail', $data);
		
	}
			
	/* Cabang add op process */
	function add_op_proc_fee()
	{	
			
		//Check otorisasi transaksi
		$this->fungsi->trans_auth($this->session->userdata('add'));
		
		/*-----------------------------------------Check Saldo------------------------------------------------*/

if($this->fungsi->get_pc_bal($this->session->userdata('idcab')) < $this->fungsi->convert_idr_to_num($this->input->post('fee')))
				{
					$this->session->set_flashdata('message_err', 'Error, Your PC UO Balances Is Insufficient!');
					redirect('branch/cabang_op_det/cabang_add_op_fee');
					
				}

/*-----------------------------------------Check Saldo------------------------------------------------*/
		$data['prev'] = '';
		
		/*Get OP counter*/
		$count = array();
		$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'OP');
		$noopform = $count[0];
		$noop = $count[1];
		
		//Data Type form
		$this->load->helper('form'); 
	
		
		
		$op_fee = array(
                  
				  array(
                     'field'   => 'invoice',
                     'label'   => 'Invoice',
                     'rules'   => 'required'
                  )
            );
		
		//Check validasi form
		$this->form_validation->set_rules($op_fee); 
		if ($this->form_validation->run() == TRUE)
			{
			/* Insert data op fee */
			$op_fee = array( 	'c_amt_bapi'=> $this->fungsi->convert_idr_to_num($this->input->post('c_amt_bapi')),
								'prnumb'	=> $this->input->post('prnumb'),
								'opnumb'	=> $noopform,
								'idcab'		=> $this->session->userdata('idcab'),
								'type'	    => $this->input->post('type'),
								'idsupp'	=> $this->input->post('idsupp'),
								'idtrans'	=> $this->input->post('idtrans'),
								'idstb'	    => $this->input->post('idstb'),
								'pur'		=> $this->fungsi->convert_idr_to_num($this->input->post('pur')),
								'fee'		=> $this->fungsi->convert_idr_to_num($this->input->post('fee')),
								'quantity'	=> $this->fungsi->hapus_koma($this->input->post('quantity')),
								'invoice'	=> $this->input->post('invoice'),
								'vol'		=> $this->fungsi->hapus_koma($this->input->post('vol')),
								'vnumb'  	=> $this->input->post('vnumb'),
								'total'	    => $this->fungsi->convert_idr_to_num($this->input->post('total')),
								'donumb'	=> $this->input->post('donumb'),
								'year'	    => date('Y'),
								'mnfst'	    => $this->input->post('mnfst'),
								'inf'	    => $this->input->post('inf'),
								'postdate'  => date("Y-m-d", strtotime($this->input->post('posting'))),
								'adddate' 	=> date( 'Y-m-d H:i:s'),
								'chdate'	=> $this->input->post('chdate'),
								'chby'		=> $this->input->post('chby'),
								'addby'		=> $this->session->userdata('uid'),
								
						);
						
			/*Insert to t_pcbal*/
					$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
											'ref'	 	 => $noopform,
											'postdate'  => date("Y-m-d", strtotime($this->input->post('posting'))),
											'amount' 	 =>  $this->fungsi->convert_idr_to_num($this->input->post('fee')) * -1,
											'addby'		 => $this->session->userdata('uid'),
											'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
								/*Update Data STB*/
		/*$stb = array( 		'closed'	 => 1,
							'chby'		 => $this->session->userdata('uid'),
							'chdate' 	 => date( 'Y-m-d H:i:s'),
								);*/
								
			/*Insert to t_stockbal*/
		/*$salbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	 => $noopform,
								'qty'		 => $this->input->post('vol'),
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);*/
								
								/*insert op fee detail  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> kerjain*/
				
			$opd = array( 		'opnumb'	=> $noopform,
								'type1'		=> $this->input->post('type1'),
								'type2'		=> $this->input->post('type2'),
								'type3'		=> $this->input->post('type3'),
								'type4'		=> $this->input->post('type4'),
								'jumlah1'	=> $this->input->post('jumlah1'),
								'jumlah2'	=> $this->input->post('jumlah2'),
								'jumlah3'	=> $this->input->post('jumlah3'),
								'jumlah4'	=> $this->input->post('jumlah4'),								
								'idcab'		=> $this->session->userdata('idcab'),
								'adddate' 	=> date( 'Y-m-d'),
								'year'	    => date('Y'),								
						);
						
			$this->cabang_model->add_opd($opd);
//			>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> kerjain*/
								
			$this->cabang_model->add_op_fee($op_fee);
			$this->branch_model->add_pc_branch($pcbal);
			//$this->cabang_model->stb($this->input->post('idstb'), $stb);
			//$this->cabang_model->add_saldo_branch($salbal);
			/*Set pesan sukses dan kembali ke menu add op*/
			$this->session->set_flashdata('prnumb', $this->input->post('prnumb'));
			$this->session->set_flashdata('message_ok', 'Data saved, Purchase number :'.$noopform);
			redirect('branch/cabang_op_det/cabang_add_op_fee');
			}
		else
			{
				$this->cabang_add_op_fee();
			}
	}
/*=============================================INSERT TO OP FEE===============================================================*/




/*Print OP*/
function print_op_popup()
{
	
	//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('view'));
	
	//Get data for print
	$query_op = $this->cabang_model->get_list_op_fee($this->uri->segment(4));
	foreach ($query_op->result() as $row_op);
	
	//Get PO number
	$query_po = $this->db->query("SELECT
			 *
			FROM
			  t_po
			WHERE
			 preq_no = '".$row_op->prnumb."'")->result();
			foreach ($query_po  as $row_po);
			if($row_po->idtop == 0)
			{
				$data['top_desc'] = '( CASH )';
			}
			else
			{
				$data['top_desc'] = '( CREDIT )';
			}
		//{
			//Jika pur = 0 maka select fee
			$data['ebeln'] = $row_po->ebeln;
			if( $row_op->pur <> 0 && $row_po->idtop <> 0)
			{
				$data['vendor_name'] = $row_po->vendor_name;
			}
			elseif( $row_op->fee <> 0 && $row_po->idtop <> 0)
			{
				$data['vendor_name'] = strtoupper($this->session->userdata('namacab'));	
			}
			
			if( $row_op->pur == 0 )
			{
				$data['prnumb'] = $row_op->prnumb;
				$data['opnumb'] = $row_op->opnumb;
				$data['adddate'] = date("d.m.Y",   strtotime($row_op->adddate));
				$data['pur'] = '';	
				$data['fee'] = $this->fungsi->format_idr($row_op->fee);
				$data['inf'] = $row_op->inf;
				$data['addby'] = $row_op->addby;
				$data['idcab'] = $row_op->idcab;
				$data['type'] = $row_op->type;
				$data['txt_terbilang'] = $this->fungsi->terbilang($row_op->fee).' RUPIAH';				
			
			}
						
			else
					
			{
				if( $row_op->tax = 1 )
					{
						$query_op = $this->cabang_model->get_list_op_print_paging_tax($this->uri->segment(4));
						//print_r($query_op->result());
						foreach ($query_op->result() as $row_op);
						$data['prnumb'] = $row_op->prnumb;
						$data['opnumb'] = $row_op->opnumb;
						$data['adddate'] = date("d.m.Y",   strtotime($row_op->adddate));	
						$data['pur'] = $this->fungsi->format_idr($row_op->pur);
						$data['fee'] = '';
						$data['inf'] = $row_op->inf;
						$data['vol'] = $row_op->vol;
						$data['suppname'] = $row_op->suppname;
						$data['suppnametax'] = $row_op->suppnametax;
						$data['idtrans'] = $row_op->idtrans;
						$data['addby'] = $row_op->addby;
						$data['idcab'] = $row_op->idcab;
						$data['type'] = $row_op->type;
						$data['txt_terbilang'] = $this->fungsi->terbilang($row_op->pur).' RUPIAH';
					}
				else
					{
					
				$query_op = $this->cabang_model->get_list_op_print_paging($this->uri->segment(4));
				//print_r($query_op->result());
				foreach ($query_op->result() as $row_op);
				$data['prnumb'] = $row_op->prnumb;
				$data['opnumb'] = $row_op->opnumb;
				$data['adddate'] = date("d.m.Y",   strtotime($row_op->adddate));	
				$data['pur'] = $this->fungsi->format_idr($row_op->pur);
				$data['fee'] = '';
				$data['inf'] = $row_op->inf;
				$data['vol'] = $row_op->vol;
				$data['suppname'] = $row_op->suppname;
				$data['suppnametax'] = $row_op->suppnametax;
				$data['idtrans'] = $row_op->idtrans;
				$data['addby'] = $row_op->addby;
				$data['idcab'] = $row_op->idcab;
				$data['type'] = $row_op->type;
				$data['txt_terbilang'] = $this->fungsi->terbilang($row_op->pur).' RUPIAH';		
						
					}
			}
		//}
//Get data detail cabang by id cabang
				$sql_cab_detail = $this->admin_model->get_cab_detail($row_op->idcab);
				foreach ($sql_cab_detail->result() as $row_cab)
				{	
					$data['cabname'] = $row_cab->cabname;
				}
$this->load->view('popup/popup_bpkk', $data);
	
}

/*Print OP*/
function print_stb_popup()
{
	
	//Check otorisasi
	$this->fungsi->trans_auth($this->session->userdata('view'));
	
	//Get data for print
	$query_stb = $this->cabang_model->get_list_stb_print_paging($this->uri->segment(4));
	foreach ($query_stb->result() as $row_stb)
		{
			$data['prnumb'] = $row_stb->prnumb;
			$data['opnumb'] = $row_stb->opnumb;
			$data['adddate'] = date("d.m.Y",   strtotime($row_stb->adddate));	
			$data['pur'] = $this->fungsi->format_idr($row_stb->pur);
			$data['fee'] = $this->fungsi->format_idr($row_stb->fee);
			$data['inf'] = $row_stb->inf;
			$data['vol'] = $row_stb->vol;
			$data['suppname'] = $row_stb->suppname;
			$data['idtrans'] = $row_stb->idtrans;
			$data['addby'] = $row_stb->addby;
			$data['idcab'] = $row_stb->idcab;
			$data['type'] = $row_stb->type;
			$data['txt_terbilang'] = $this->fungsi->terbilang($row_stb->pur).' RUPIAH';
			}
//Get data detail cabang by id cabang
				$sql_cab_detail = $this->admin_model->get_cab_detail($row_stb->idcab);
				foreach ($sql_cab_detail->result() as $row_cab)
				{	
					$data['cabname'] = $row_cab->cabname;
				}
$this->load->view('popup/popup_stb', $data);
	
}

	
	
	/* Display list op */
	function cabang_list_op()
	{	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('view'));
		
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_list_op);
		
		/* Setting Parameter Untuk Paging */
		$uri_segment = 4;
		$offset =    $this->uri->segment($uri_segment);
			
		$op = $this->cabang_model->get_op_paging($this->config->item('paging_limit'), $offset)->result();
		$num_rows = $this->cabang_model->count_all_op();
		$config['base_url'] = site_url('branch/cabang_op_det/cabang_list_op/');
		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.', 'PO Numb', 'PR Number',  'Receive No', 'No OP', 'Purchase', 'Fee', 'Vol', 'Info', 'Options');
				    
					$atts = array(
              'width'      => '100',
              'height'     => '100',
              'scrollbars' => 'yes',
              'status'     => 'yes',
              'resizable'  => 'yes',
              'screenx'    => '0',
              'screeny'    => '0'
            );
				
					foreach ($op  as $ops)
					{	
			//Get no PO
			$sqlpo = $this->db->query("SELECT ebeln FROM t_po WHERE preq_no = '".$ops->prnumb."'");
			foreach($sqlpo->result() as $row_po)
		
		$this->table->add_row($ops->idop,  $row_po->ebeln, $ops->prnumb, $ops->idstb, $ops->opnumb, number_format($ops->pur), $this->fungsi->format_idr($ops->fee),$this->fungsi->format_idr($ops->vol), $ops->inf, anchor('branch/cabang_op_det/edit_op/'.$ops->idop.'/'.$ops->year,'Edit',array('class' => 'update')).' '.anchor('branch/cabang_op_det/cancel_op/'.$ops->idop.'/'.$ops->year,'Cancel',array('class' => 'update')).''. anchor_popup('branch/cabang_op_det/print_op_popup/'.$ops->idop,'Print BPKK',array('class'=> 'print',$atts),$atts));
					}
					$data['table'] = $this->table->generate();
				}
			else
				{
					$data['message'] = 'No data';
				}		
		$data['menu_path'] = 'BRANCH > OP > OP LIST';
		$this->load->view('branch/cabang_op_list', $data);
		
	}
	

	
	
	/* Edit op */
	function edit_op()
	{
		
		//Get data detail op by id cabang
		$sql_op_edit = $this->cabang_model->get_op_detail($this->uri->segment(4));
		
		foreach ($sql_op_edit->result() as $row_op)
		{	
			$data['default']['idcab']   = $row_op->idcab;
			$data['default']['vol']     = $row_op->vol;
			$data['default']['type']    = $row_op->type;
			$data['default']['fee']    = $this->fungsi->format_idr($row_op->fee);
			$data['default']['pur']    = $this->fungsi->format_idr($row_op->pur);
			$data['default']['idsupp']  = $row_op->idsupp;
			$data['default']['idtrans'] = $row_op->idtrans;
			$data['default']['vnumb']   = $row_op->vnumb;
			$data['default']['prnumb']  = $row_op->prnumb;
			$data['default']['donumb']  = $row_op->donumb;
			$data['default']['mnfst']   = $row_op->mnfst;
			$data['default']['inf']     = $row_op->inf;
			$data['default']['invoice'] = $row_op->invoice;
			$data['default']['adddate'] = $row_op->adddate;
			$data['default']['chdate']  = $row_op->chdate;
			$data['default']['chby']    = $row_op->chby;
			$data['default']['addby']   = $row_op->addby;
		}
		$data['default']['readonly'] =  'readonly="readonly"';
		
		$data['menu_path'] = 'BRANCH > OIL PURCHASE > EDIT OIL PURCHASE';
		$data['form_action']= site_url('branch/cabang_op_det/edit_op_proc/'.$this->uri->segment(4));
		$data['link'] = array('link_back' => anchor('branch/cabang_op_det/cabang_list_op','Back', array('class' => 'back')));
		$this->load->view('branch/cabang_op_edit', $data);
	}
	
	
	/* Cabang edit op process */
	function edit_op_proc()
	{	
		//Check otorisasi transaksi
		$this->fungsi->trans_auth($this->session->userdata('edit'));
		
		//Config utk validasi form op
 $config = array(
 					array(
                     'field'   => 'idtrans',
                     'label'   => 'ID Transporter',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'chdate',
                     'label'   => 'Change Date',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'chby',
                     'label'   => 'Change By',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'addby',
                     'label'   => 'Add By',
                     'rules'   => ''
                  )
				   //Not validate form
            );
	
	
		$this->form_validation->set_rules($config); 
		
		
		if ($this->form_validation->run() == TRUE)
			{
			/* Insert data */
			$op_edit = array( 		/*'c_amt_bapi'=> $this->input->post('c_amt_bapi'),
								'prnumb'	=> $this->input->post('prnumb'),
								'opnumb'	=> $this->input->post('opnumb'),
								'idcab'		=> $this->input->post('idcab'),
								'type'	    => $this->input->post('type'),
								'idsupp'	=> $this->input->post('idsupp'),
								'idtrans'	=> $this->input->post('idtrans'),
								'pur'		=> $this->input->post('pur'),
								'fee'		=> $this->input->post('fee'),
								'freight'	=> $this->input->post('freight'),
								'other'		=> $this->input->post('other'),
								'quantity'	=> $this->input->post('quantity'),
								'invoice'	=> $this->input->post('invoice'),
								'vol'		=> $this->input->post('vol'),
								'vnumb'  	=> $this->input->post('vnumb'),
								'total'	    => $this->input->post('total'),
								'donumb'	=> $this->input->post('donumb'),
								'year'	    => $this->input->post('year'),
								'mnfst'	    => $this->input->post('mnfst'),
								'invoice'   => $this->input->post('invoice'),*/
								'inf'	    => $this->input->post('inf'),
								'year'	    => date('Y'),
								'chdate'	=> date( 'Y-m-d H:i:s'),
								'chby'		=> $this->session->userdata('uid'),
								
						);
						
			
								
			$this->cabang_model->update_op($this->uri->segment(4), $op_edit);
			
			
			/*Set pesan sukses dan kembali ke menu add op*/
			$this->session->set_flashdata('message_ok', 'Data Edited');
			redirect('branch/cabang_op_det/cabang_list_op');
			}
		else
			{
				$this->edit_op();
			}
	}
	
	function cabang_cancel_op()
	{	
		//Check otorisasi
		$this->fungsi->trans_auth($this->session->userdata('view'));
		
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_list_op);
		
		/* Setting Parameter Untuk Paging */
		$uri_segment = 4;
		$offset =    $this->uri->segment($uri_segment);
			
		$op = $this->cabang_model->get_op_paging($this->config->item('paging_limit'), $offset)->result();
		$num_rows = $this->cabang_model->count_all_op();
		$config['base_url'] = site_url('branch/cabang_op_det/cabang_list_op/');
		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.','ID OP', 'PR Number', 'Receive No', 'Purchase', 'Fee', 'Vol', 'Info', 'Options');
				    
					$atts = array(
              'width'      => '100',
              'height'     => '100',
              'scrollbars' => 'yes',
              'status'     => 'yes',
              'resizable'  => 'yes',
              'screenx'    => '0',
              'screeny'    => '0'
            );
				
					foreach ($op  as $ops)
					{	
			
		$this->table->add_row($ops->idop, $ops->opnumb, $ops->prnumb, $ops->idstb,number_format($ops->pur), $this->fungsi->format_idr($ops->fee),$this->fungsi->format_idr($ops->vol), $ops->inf,anchor('branch/cabang_op_det/cancel_op/'.$ops->idop.'/'.$ops->year,'Cancel',array('class' => 'update',$atts),$atts));
		
					}
					$data['table'] = $this->table->generate();
				}
			else
				{
					$data['message'] = 'No data';
				}		
		$data['menu_path'] = 'BRANCH > OP > OP LIST CANCEL';
		$this->load->view('branch/cabang_op_list', $data);
		
	}
	

	/* cancel op */
	function cancel_op()
	{
		
		//Get data detail op by id cabang
		$sql_op_cancel = $this->cabang_model->get_op_detail($this->uri->segment(4));
		
		foreach ($sql_op_cancel->result() as $row_op)
		{	
			$data['default']['idcab']   = $row_op->idcab;
			$data['default']['vol']     = $row_op->vol;
			$data['default']['type']    = $row_op->type;
			$data['default']['fee']    = $this->fungsi->format_idr($row_op->fee);
			$data['default']['pur']    = $this->fungsi->format_idr($row_op->pur);
			$data['default']['idsupp']  = $row_op->idsupp;
			$data['default']['idtrans'] = $row_op->idtrans;
			$data['default']['vnumb']   = $row_op->vnumb;
			$data['default']['prnumb']  = $row_op->prnumb;
			$data['default']['donumb']  = $row_op->donumb;
			$data['default']['mnfst']   = $row_op->mnfst;
			$data['default']['inf']     = $row_op->inf;
			$data['default']['invoice'] = $row_op->invoice;
			$data['default']['adddate'] = $row_op->adddate;
			$data['default']['chdate']  = $row_op->chdate;
			$data['default']['chby']    = $row_op->chby;
			$data['default']['addby']   = $row_op->addby;
			$data['default']['idstb']   = $row_op->idstb;
			
				$query_top = $this->db->query("SELECT * FROM t_pr
				WHERE preq_no = '".$row_op->prnumb."'")->result();
				foreach ($query_top  as $row_top);
				
				$data['idtop']   = $row_top->idtop;
		}
		$data['default']['readonly'] =  'readonly="readonly"';
		
		$data['menu_path'] = 'BRANCH > OIL PURCHASE > CANCEL OIL PURCHASE';
		$data['form_action']= site_url('branch/cabang_op_det/cancel_op_proc/'.$this->uri->segment(4));
		$data['link'] = array('link_back' => anchor('branch/cabang_op_det/cabang_list_op','Back', array('class' => 'back')));
		$this->load->view('branch/cabang_op_cancel', $data);
	}
	
	
	/* Cabang edit op process */
	function cancel_op_proc()
	{	
		//Check otorisasi transaksi
		$this->fungsi->trans_auth($this->session->userdata('edit'));
		
		//Config utk validasi form op
 $config = array(
 					array(
                     'field'   => 'idtrans',
                     'label'   => 'ID Transporter',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'reason',
                     'label'   => 'Reason',
                     'rules'   => 'required'
                  )
				    ,array(
                     'field'   => 'chdate',
                     'label'   => 'Change Date',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'chby',
                     'label'   => 'Change By',
                     'rules'   => ''
                  )
				    ,array(
                     'field'   => 'addby',
                     'label'   => 'Add By',
                     'rules'   => ''
                  )
				   //Not validate form
            );
	
	
		$this->form_validation->set_rules($config); 
		
		/*Get OP Cancel Counter*/
		$count = array();
		$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'OPC');
		$noopcform = $count[0];
		$noopc = $count[1];
		
		if ($this->form_validation->run() == TRUE)
			{
			/* Update ke m_op */
			$op_cancel = array( 'reason' 	=> $this->input->post('reason'),
								'year'	    => date('Y'),
								'chdate'	=> date( 'Y-m-d H:i:s'),
								
								'chby'		=> $this->session->userdata('uid'),
								'cancel'	=> 1,
								
						);
					
					if( $this->input->post('txt_idtop')	== 0 || $this->fungsi->convert_idr_to_num($this->input->post('fee')) != 0)
					{
						
						if($this->fungsi->convert_idr_to_num($this->input->post('pur')) != 0)
						{
							$amount = $this->fungsi->convert_idr_to_num($this->input->post('pur'));
						}
						else
						{
							$amount = $this->fungsi->convert_idr_to_num($this->input->post('fee'));
						}
						
					/*Insert to t_pcbal*/
					$pcbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
											'ref'	 	 => $noopcform,
											'amount' 	 =>  $amount,
											'status'	 => 1,
											'addby'		 => $this->session->userdata('uid'),
											'postdate'	=> date( 'Y-m-d'),
											'adddate' 	 => date( 'Y-m-d H:i:s'),
								);
					
					$this->branch_model->add_pc_branch($pcbal);
					}
			/*Insert to t_stockbal*/
		/*$salbal = array( 		'idcab'		 => $this->session->userdata('idcab'),
								'ref'	     => $noopcform,
								'year'	    => date('Y'),
								'qty'		 => $this->input->post('vol')* -1,
								'addby'		 => $this->session->userdata('uid'),
								'adddate' 	 => date( 'Y-m-d H:i:s'),
								);*/
								
			/*Update Data STB*/
		$stb = array( 		'closed'	 => 0,
							'chby'		 => $this->session->userdata('uid'),
							'chdate' 	 => date( 'Y-m-d H:i:s'),
								);
								
			$this->cabang_model->update_op($this->uri->segment(4), $op_cancel);
			
			if($this->input->post('idstb') != 0)
			{
				//$this->cabang_model->add_saldo_branch($salbal);
				$this->cabang_model->update_stb($this->input->post('idstb'), $stb);
			}
			/*Set pesan sukses dan kembali ke menu cancel op*/
			$this->session->set_flashdata('message_ok', 'Data CANCELED');
			redirect('branch/cabang_op_det/cabang_list_op');
			}
		else
			{
				$this->cancel_op();
			}
	}
	
	
}