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

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

class Cabang_op_credit_pusat 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_op_credit_pusat  = 173;
	
/*-------------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_credit_pusat();
		
	}
	
	
	
	function cabang_add_op_credit_pusat()
	{	
		//Otorisasi menu
		$this->fungsi->menu_auth($this->menu_add_op_credit);
		
		$data['menu_path'] = 'BRANCH > OIL PURCHASE > ADD OIL PURCHASE WITH CENTRALIZED CREDIT';
		$data['form_action']= site_url('branch/cabang_op_credit/add_op_credit_pusat_proc');
		
		$this->load->view('branch/cabang_op_credit_pusat_form', $data);
		
	}

/* Insert OP with credit Process */
	function add_op_credit_pusat_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_credit');
		}
		
		//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_credit');
		}
		
		//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'   => 'pur2',
                     'label'   => 'Other Cost ',
                     '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
            );
		//Check validasi form
		$this->form_validation->set_rules($op); 
		
		if ($this->form_validation->run() == TRUE)
			{	
		//Data Type form
		//$this->load->helper('form'); 
		
		
		//Cek menggunakan pajak atau tidak
		if($this->input->post('cb_tax')==1)
		{
			//Get Tax
			$tax = $this->fungsi->convert_idr_to_num($this->input->post('pur')) * 10 / 100;
			$tax_stat = 1;
		}
		else
		{
			$tax = 0;
			$tax_stat = 0;
		}
			/*Get OP counter*/
			$count = array();
			$count = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'OP');
			$noopform = $count[0];
			$noop = $count[1];
			
			/* 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'	    => $tax_stat,
								'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,
								
						);
			
			/*Get OP fee counter*/
			$count2 = array();
			$count2 = $this->fungsi->get_no_count($this->session->userdata('idcab'), 'OP');
			$noopform2 = $count2[0];
			$noop2 = $count2[1];
			
			// Input OP Fee
			$op2 = array( 		'c_amt_bapi'=> $this->fungsi->convert_idr_to_num($this->input->post('c_amt_bapi')),
								'prnumb'	=> $this->input->post('prnumb'),
								'opnumb'	=> $noopform2,
								'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('pur2')),
								'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'	    => $tax_stat,
								'mnfst'	    => $this->input->post('mnfst'),
								'inf'	    => $this->input->post('inf2'),
								'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,
								
						);
									
			/*Insert to t_pcbal*/
			$pcbal = array( 	'idcab'		 => $this->session->userdata('idcab'),
								'ref'	     => $noopform2,
								'amount' 	 =>  $this->fungsi->convert_idr_to_num($this->input->post('pur2')) * -1,
								'addby'		 => $this->session->userdata('uid'),
								'postdate'  	=> date("Y-m-d", strtotime($this->input->post('adddate'))),
								'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'),
								);

			
/*-----------------------------------------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 == '')
	{
		//Cek menggunakan pajak atau tidak
		if($this->input->post('cb_tax')==1)
		{
	//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
		{
			//Create PO
	$this->fungsi_sap->fm_create_po($this->input->post('idsupp'), $this->session->userdata('lgort'), $this->fungsi->hapus_koma($this->input->post('vol')),'V0',$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'));
		$oa = $this->fungsi->convert_idr_to_num($this->input->post('pur2'));
		$this->fungsi_sap->fm_add_oa($this->session->userdata('sap_po_num'),$oa,'I');
	}
	else
	{
		//Ongkos Angkut
		$oa = $this->fungsi->convert_idr_to_num($this->input->post('pur2'));
		$this->fungsi_sap->fm_add_oa($ponum,$oa,'U');
	}
	//Sleep 1 detik
	sleep(1);
	//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'),
						'idtop' 	 => 1,
						'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'),
						);
	
				
	if( $this->session->userdata('sap_po_num') != '' )
	{
		$this->branch_model->update_pr($this->input->post('prnumb'),date('Y'),$pr);	
		$this->cabang_model->add_op($op);
		$this->cabang_model->add_op($op2);
		$this->cabang_model->update_stb($this->input->post('idstb'), $stb);
		$this->branch_model->add_pc_branch($pcbal);
		
		if($ponum == '')
		{						
			$this->branch_model->add_po($po);	
		}
		else
		{
			$this->branch_model->update_po($ponum, date('Y'),$po_edit);
		}
		
		
	}
	
	
	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' => $oa,
						'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.', '.$noopform2.' PO number :'.$this->session->userdata('sap_po_num'));
			redirect('branch/cabang_op_credit_pusat');
			
/*-----------------------------------------Add OP Process------------------------------------------------*/
			
			}
		else
			{
				$this->cabang_add_op_credit_pusat();
			}
	}
	
	
	
	
}