<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Wahyu
 *	Tanggal : 08-08-2014	
 *	Revisi 	:  Fachri
 */
 
class Sales_invoice extends CI_Controller {
	// inisialisasi manual
	public $menu_id = 162;
	public $code = "Sales Invoice Number";
	public $name = "Sales Invoice";
	
    public function __construct() {
        parent::__construct();
		
		$this->load->helper('message');	
		$this->load->helper('status');			
		$this->load->helper('convert_date');
		$this->load->helper('approval');
		$this->load->helper('lables');
		$this->load->helper('custom_string_helper');
		
		$this->load->model('m_account_journal');
		$this->load->model('m_employee');
		$this->load->model('m_customer');
		$this->load->model('m_sales_invoice');		
		$this->load->model('m_sales_return');
		$this->load->model('m_sales_receipt');
				
		$this->load->model('m_sales_quotation');
		$this->load->model('m_sales_order');
		$this->load->model('m_delivery_order');	
		$this->load->model('custom/m_custom');
		$this->load->model('login/m_login');
		
		$is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
        if($is_login){

        }else{
            $username       = $this->session->userdata('username');
            $session_id     = $this->session->userdata('session_id');
            $this->m_login->delete_session($username,$session_id);
            $this->session->sess_destroy();

            $uri_func = $this->uri->segment(3);
            if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
                redirect(base_url() . 'login', 'refresh');
            }else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
                $result['status']   = 'session';
                $result['message']  = get_notification('session_destroy',0);
                echo json_encode($result);
                die();
            }
        }
	}
	
	//Function Index
    public function index()	{
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
            $arr_group_id           = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					$group_menu 	 = $this->session->userdata('group_menu');	
					// set data
					$data['menu_id'] =  $this->menu_id;
					
					// get link from tbl_menu 
					$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
					$data['list_cust'] = $this->m_sales_quotation->get_all_customer(); 
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$this->load->view('v_header');
					$this->load->view('sales/sales_invoice/v_salesinvoice', $data);	
					$this->load->view('v_footer');			
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
		
	}
	
	//Function Form Edit
	public function edit(){	
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
			/*
				untuk di index/list = get_menu_by_group, 
				untuk di add = get_menu_by_group_add
				untuk di edit = get_menu_by_group_edit
			*/
            $arr_group_id           = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
			//--------------------------end-----------------------------------------------------------
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					/*
						modul untuk akses add masing masing modul berebda 
						jangan lupa copy $data nya (jika dia bener langsung ke add)
					*/
					$group_menu 	 		= $this->session->userdata('group_menu');		
					// set data
					$data['menu_id'] 	=  $this->menu_id;
					
					// get link from tbl_menu 
					$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] 	= $this->m_menu->get_menulink($this->menu_id);
					
					// inisialisasi additional parameter
					$id 				= str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
					$data['detail'] 	= $this->m_sales_invoice->get_detail($id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					if($data['detail'] != false){
						// set for view
						$this->load->view('v_header');
						$this->load->view('sales/sales_invoice/v_edit_salesinvoice',$data);
						$this->load->view('v_footer');
					}
					//----------------------end--------------------------------------------------------		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
	}
	
	// Function Update
	public function update() {
		
		/*=====================================deklar variabel=====================================*/
		$result_insert		= 0;
		$result_edit		= 0;
		$result_delete		= 0;
		$CategoryAmount 	= array();
		$CategoryType 		= array();
		$CategoryPPNAmount 	= array();
		
		$CustomerCode		= $this->input->post('cmb_customer');
	  	$SInvNumber 		= $this->input->post('hdn_sinv_no');
		$SInvDate			= $this->input->post('txt_si_date');
		$CurrencyCode		= $this->input->post('txt_currency_code');
		$CurrencyRate		= $this->input->post('txt_rate');
		$FiscalRate			= $this->input->post('txt_fiscal_rate');
		$SInvDesc 			= $this->input->post('txa_description');
		$SInvSubTotal	 	= $this->input->post('txt_sub_total_hide');
		$SInvSubTotal_Real	= $this->input->post('txt_sub_total');
		$SInvDiscount		= $this->input->post('txt_discount_hide');
		$SInvPPNOut			= $this->input->post('txt_ppn_hide');
		$SInvPPNOut_Real	= $this->input->post('txt_ppn');
		$SInvPPNPcnt		= $this->input->post('txt_pcnt');
		$SInvPPH23		= $this->input->post('pph_value');
		
		$SInvEstFreight		= $this->input->post('txt_freight');
		$SInvTotalAmount	= $this->input->post('txt_total_amount_hide');
		$detail 			= json_decode($this->input->post('detail'));
		/*====================================end===================================================*/
		
		// Set Sales Invoice data.
		$data_si = array (
			'TransStatus'		=> 4,
			'Fiscalrate'		=> $FiscalRate,
			'SInvSubTotal'		=> $SInvSubTotal,
			'SInvDiscount'		=> $SInvDiscount,
			'SInvPPNOut'		=> $SInvPPNOut,
			'SInvEstFreight'	=> $SInvEstFreight,
			'SInvTotalAmount'	=> $SInvTotalAmount,
			'SInvDesc'			=> $SInvDesc,
			'SInvPPH23'		=> $SInvPPH23,
			'AppFinished' 		=> 2, 
			'LastUser'			=> $this->session->userdata('username')
		);
		
		$this->transaction['update_group']['data'] = $data_si;
		$this->transaction['update_group']['SInvNumber'] = $SInvNumber;
		
		foreach($detail as $row){
			@$CategoryAmount[$row->ItemCategoryID]    	+=doubleval($row->ItemAmountKoma);
            @$CategoryType[$row->ItemCategoryID]     	= $row->ItemType;
			@$CategoryPPNAmount[$row->ItemCategoryID] 	+= doubleval($row->ItemTax);
			@$CategoryDiscAmount[$row->ItemCategoryID] 	+= (doubleval($row->AmountDisc));
			@$CategoryTypeSum[$row->ItemCategoryID]     = $row->ItemType;
			@$CategoryAmountNew[$row->ItemCategoryID]    +=doubleval($row->ItemAmountKoma);
		}
		
		$this->transaction['delete_journal']['SInvNumber'] = $SInvNumber;
		
		$x = 100;
		$total_records  			= count(@$CategoryAmount);
		$total_loop     			= 0;
		$total_ratio    			= 0;
		$Persen 					= 100;
		$ItemRatio 				  	= 0;		
		$ReceivableAmountCurrency 	= 0;
		$RecivTotal 				= 0;
		$sub_total 					= 0;
		$ppn_total 					= 0;
		$payable_value 				= 0;
		$payable_currency 			= 0;
		$Total_Purchase 			= 0;
		$beban_pembulatan_auto 		= 0;
		/*
			Calculate beban pembulatan auto
		*/
		if(($SInvSubTotal_Real + $SInvEstFreight) > 0){
			$Total_BebanAuto 			= 0;
		}
		else{
			$Total_BebanAuto 			= $SInvSubTotal + $SInvEstFreight;
		}
		/*==================END===================*/
		
		/*
			Journal Receiveable End Unbill
		*/
		
		foreach($CategoryAmount as $key=>$value){
			$total_loop++;
			
			if($total_loop == $total_records){
				$ItemRatio = $Persen - $total_ratio;
			} 
			else {
				$ItemRatio = floor(abs((doubleval($value) / $SInvSubTotal) * 100));
			}
			$total_ratio  	= $total_ratio + $ItemRatio;
			
			$sub_total 		= $SInvSubTotal * ($ItemRatio / 100);
			$ppn_total 		= $SInvPPNOut * ($ItemRatio / 100);
			$FreightAmount 	= $SInvEstFreight * ($ItemRatio/100);
			
			$item_ppn       	 = ($CurrencyCode == 'IDR' && $SInvPPNPcnt > 0) ? $ppn_total : 0;    
			$Total_Purchase 	 = $sub_total + $item_ppn + $FreightAmount;
			/*
				Total Real View
			*/
			$sub_total_real 	= $SInvSubTotal_Real * ($ItemRatio / 100);
			$ppn_total_real 	= $SInvPPNOut_Real * ($ItemRatio / 100);
			$item_ppn_real      = ($CurrencyCode == 'IDR' && $SInvPPNPcnt > 0) ? $ppn_total_real : 0;    
			
			$Total_Purchase_Real = $sub_total_real + $item_ppn_real + $FreightAmount;
			/*================End================*/
			
			$payable_value      = $CurrencyCode == 'IDR' ? $Total_Purchase : $Total_Purchase * $CurrencyRate;
			$payable_currency   = $Total_Purchase;
			
			if($CategoryTypeSum[$key] == 0){
				$ReceivableAccount	= $this->m_account_journal->get_cat_sales_account('SRAccountReceivable',$key,$CurrencyCode);
				if($ReceivableAccount == false) {$this->trans_rollback('preference','Receivable Account,Sales','');}
			}
			else{
				$ReceivableAccount    	= $this->m_account_journal->get_sys_service_account('SalesUnbilled', $CurrencyCode);
				if($ReceivableAccount == false) {$this->trans_rollback('preference','Expense,Expense','');}
			}
			
			
			$journal_Unbilled        = array(
				'SInvDate'              => date('Y-m-d'),
				'SInvNumber'            => $SInvNumber,
				'SInvAccountNumber'     => $ReceivableAccount->AccountNumber,
				'SInvSaldoDebet'        => $payable_value, 
				'SInvSaldoCredit'       => 0,
				'AmountCurrency'        => $payable_currency,
				'SInvSignStatus'        => 0,
				'LastUser'              => $this->session->userdata("username")	
			);	
			
			if($Total_Purchase_Real > 0){
				$this->transaction['insert_journal']['data'][] = $journal_Unbilled;
			}
		}
		/*============================END========================*/
		
		/*
			Beban Pembulatan Auto
		*/
		
		if($Total_BebanAuto > 0){
			$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
			if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $CurrencyCode);}
								
			$payable_beban      = $CurrencyCode == 'IDR' ? $Total_BebanAuto : $Total_BebanAuto * $CurrencyRate;
			
			$beban_pembulatan_auto        = array(
				'SInvDate'              => date('Y-m-d'),
				'SInvNumber'            => $SInvNumber,
				'SInvAccountNumber'     => $BebanAccountAuto->AccountNumber,
				'SInvSaldoDebet'        => abs($payable_beban), 
				'SInvSaldoCredit'       => 0,
				'AmountCurrency'        => 0,
				'SInvSignStatus'        => 0,
				'LastUser'              => $this->session->userdata("username")	
			);	
			$this->transaction['insert_journal']['data'][] = $beban_pembulatan_auto;
		}
		else if($Total_BebanAuto < 0){
			$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
			if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $CurrencyCode);}
								
			$payable_beban      = $CurrencyCode == 'IDR' ? $Total_BebanAuto : $Total_BebanAuto * $CurrencyRate;
			
			$beban_pembulatan_auto        = array(
				'SInvDate'              => date('Y-m-d'),
				'SInvNumber'            => $SInvNumber,
				'SInvAccountNumber'     => $BebanAccountAuto->AccountNumber,
				'SInvSaldoDebet'        => 0, 
				'SInvSaldoCredit'       => abs($payable_beban),
				'AmountCurrency'        => 0,
				'SInvSignStatus'        => 1,
				'LastUser'              => $this->session->userdata("username")	
			);	
			$this->transaction['insert_journal']['data'][] = $beban_pembulatan_auto;
		}
		/*======================END======================*/
		
		/*
			Journal Sales Account End Sales Expense
		*/
		$x = 100;
		$total_records_new  			= count(@$CategoryAmountNew);
		$total_loop_new     			= 0;
		$total_ratio_new    			= 0;
		$Persen_new 					= 100;
		$ItemRatio_new 				  	= 0;	
		$payable_value 					= 0;
		$payable_currency 				= 0;	
		
		
		foreach($CategoryAmountNew as $key=>$value){
			$total_loop_new++;
			
			if($total_loop_new == $total_records_new){
				$ItemRatio_new = 100 - $total_ratio_new;
			} 
			else {
				$ItemRatio_new = floor(abs((doubleval($value) / $SInvSubTotal) * 100));
			}
			$total_ratio_new  	= $total_ratio_new + $ItemRatio_new;
			$sub_total 			= doubleval($SInvSubTotal) * ($ItemRatio_new / 100);
			
			if($CategoryTypeSum[$key] == 0){
				$SalesAccount = $this->m_account_journal->get_cat_item_account('Sales',$key,'IDR');
				if($SalesAccount == false) {$this->trans_rollback('preference','Sales Account,Sales','');}
			}
			else{
				$SalesAccount    = $this->m_account_journal->get_sys_service_account('SalesExpense', 'IDR', $key);
				if($SalesAccount == false) {$this->trans_rollback('preference','Sales Account,Expense','');}
			}
			
			$payable_value      = $CurrencyCode == 'IDR' ? $sub_total : $sub_total * $CurrencyRate;
			$payable_currency   = $sub_total;
		
			$journal_sales       = array(
				'SInvDate'              => date('Y-m-d'),
				'SInvNumber'            => $SInvNumber,
				'SInvAccountNumber'     => $SalesAccount->AccountNumber,
				'SInvSaldoDebet'        => 0, 
				'SInvSaldoCredit'       => $payable_value,
				'AmountCurrency'        => $payable_currency,
				'SInvSignStatus'        => 0,
				'LastUser'              => $this->session->userdata("username")	
			);	
			
			$this->transaction['insert_journal']['data'][] = $journal_sales;
		}
		/*=====================================END===============*/
		
		if($data_si['SInvEstFreight'] != 0){
			$FreightAccount		= $this->m_account_journal->get_sys_sales_account('SalesFreight','IDR');
			if($FreightAccount == false) {$this->trans_rollback('preference','Sales Freight Out','');}
				
			if($SInvEstFreight > 0){
				$debet_freight = 0;
				$credit_freight = abs(doubleval($SInvEstFreight)*doubleval($CurrencyRate));
				$sinv_sign_status = 1;
			}
			else{
				$debet_freight = abs(doubleval($SInvEstFreight)*doubleval($CurrencyRate));
				$credit_freight = 0;
				$sinv_sign_status = 0;
			}
			
			$freight_currency = abs(doubleval($SInvEstFreight));
			
			$data_freight_journal = array(
				'SInvDate'			=> date('Y-m-d'), 
				'SInvNumber'		=> $SInvNumber, 
				'SInvAccountNumber'	=> $FreightAccount->AccountNumber, 
				'SInvSaldoDebet'	=> $debet_freight, 
				'SInvSaldoCredit'	=> $credit_freight, 
				'AmountCurrency'	=> $freight_currency, 
				'SInvSignStatus'    => $sinv_sign_status,
				'LastUser'			=> $this->session->userdata('username')
			);
			
			$this->transaction['insert_journal']['data'][] = $data_freight_journal;
		}
		
		if($data_si['SInvPPNOut'] > 0){
			if($CurrencyCode != 'IDR'){
				//$PPnFiscalAccount   = $this->m_account_journal->get_account_number('2-1-12-000-00'); // Hutang PPn Fiscal
				$PPnFiscalAccount   = $this->m_account_journal->get_account_name('Piutang PPn Fiscal'); 
				if($PPnFiscalAccount == false) {$this->trans_rollback('journal','Piutang PPn Fiscal','');}
				
				$data_taxable_journal = array(
					'SInvDate'			=> date('Y-m-d'), 
					'SInvNumber'		=> $SInvNumber, 
					'SInvAccountNumber'	=> $PPnFiscalAccount->AccountNumber, 
					'SInvSaldoDebet'	=> (doubleval($SInvPPNOut)*doubleval($FiscalRate)), 
					'SInvSaldoCredit'	=> 0, 
					'AmountCurrency'	=> doubleval($SInvPPNOut), 
					'SInvSignStatus'    => 0, 
					'LastUser'			=> $this->session->userdata('username')
				);
				
				$this->transaction['insert_journal']['data'][] = $data_taxable_journal;
				
				$TaxableAccount		= $this->m_account_journal->get_sys_sales_account('SalesTaxable','IDR');
				if($TaxableAccount == false) {$this->trans_rollback('preference','Sales Taxable,Expense','');}
				
				$data_taxable_journal_credit = array(
					'SInvDate'			=> date('Y-m-d'), 
					'SInvNumber'		=> $SInvNumber, 
					'SInvAccountNumber'	=> $TaxableAccount->AccountNumber, 
					'SInvSaldoDebet'	=> 0, 
					'SInvSaldoCredit'	=> (doubleval($SInvPPNOut)*doubleval($FiscalRate)), 
					'AmountCurrency'	=> doubleval($SInvPPNOut), 
					'SInvSignStatus'    => 0, 
					'LastUser'			=> $this->session->userdata('username')
				);
				
				$this->transaction['insert_journal']['data'][] = $data_taxable_journal_credit;
			}
			else{
				$TaxableAccount		= $this->m_account_journal->get_sys_sales_account('SalesTaxable','IDR');
				if($TaxableAccount == false) {$this->trans_rollback('preference','Sales Taxable,Expense','');}
				
				$data_taxable_journal = array(
					'SInvDate'			=> date('Y-m-d'), 
					'SInvNumber'		=> $SInvNumber, 
					'SInvAccountNumber'	=> $TaxableAccount->AccountNumber, 
					'SInvSaldoDebet'	=> 0, 
					'SInvSaldoCredit'	=> (doubleval($SInvPPNOut)*doubleval($FiscalRate)), 
					'AmountCurrency'	=> $SInvPPNOut,
					'SInvSignStatus'    => 0,  
					'LastUser'			=> $this->session->userdata('username')
				);
				
				$this->transaction['insert_journal']['data'][] = $data_taxable_journal;
			}
		}

		/*
			PPH 23
		*/
		if($data_si['SInvPPH23'] > 0){
			$PPh23Account   = $this->m_account_journal->get_account_name('PPh Pasal 23 Dibayar Dimuka'); 
			if($PPh23Account == false) {$this->trans_rollback('preference','Piutang PPh 23,Expense','');}
			
			$journal_taxpph23 = array(
                'SInvDate' => date('Y-m-d'),
                'SInvNumber' => $SInvNumber,
                'SInvAccountNumber' => $PPh23Account->AccountNumber,
                'SInvSaldoDebet' => (doubleval($SInvPPH23)*doubleval($CurrencyRate)),
                'SInvSaldoCredit' => 0, 
                'AmountCurrency' => doubleval($SInvPPH23), 
                'SInvSignStatus' => 1,
                'LastUser' => $this->session->userdata("username")
            );

			
			$this->m_sales_invoice->insert_journal($journal_taxpph23);
		}
		/*=============================trans roll back dan trans commit============================/*/
		
		$result_update 	= $this->m_sales_invoice->update_transaction($this->transaction);
		$this->transaction 	= [];
			
		if ($result_update == 0) {
			$result['status'] 		= FALSE;
			$result['message']  	= get_notification_transaksi($this->name, 'update', 0, $SInvNumber);
		}
		else {
			$result['status'] 		= TRUE;
			$result['message']  	= get_notification_transaksi($this->name, 'update', 1, $SInvNumber);
		}
		echo json_encode($result);
	}
	
	function suspend_data(){
		$SInvNumber		= str_replace(".", "/", $this->input->post('id'));
		
		$data_si = array (			
			'TransStatus'   => 3,
			'LastUser'      => $this->session->userdata("username")
		);
            
		//1. Update Sales Order TransStatus
		$this->transaction['update_group']['data']= $data_si;
		$this->transaction['update_group']['SInvNumber'] = $SInvNumber;
		
		$get_sales_invoice = $this->m_sales_invoice->get_sales_invoice_group($SInvNumber);
		/*
			Update DO trans status 1
		*/
		$data_do = array(
			'TransStatus' 		=> 1,
			'LastUser'      => $this->session->userdata("username")
		);
		$this->transaction['update_group_do']['DOrdNumber'] 	= $get_sales_invoice->DOrdNumber;
		$this->transaction['update_group_do']['data'] 			= $data_do;
		/*========================End=========================*/
			
		$result_suspend = $this->m_sales_invoice->suspend_transaction($this->transaction);
		$this->transaction 	= [];
		
		/*=============================trans roll back dan trans commit============================/*/
		if ($result_suspend == 0) {
			$result['status'] 	= FALSE;
			$result['message']  = get_notification('cancel', 0);
		}
		else {
			$result['status'] 	= TRUE;
			$result['message']  = get_notification('cancel', 1);
		}
		/*==================================end======================================================*/
		
		echo json_encode($result);
	}
	
	function reverse_data_detail() {
		try{
			$txt_si_no  		= $this->input->post('txt_si_no');
			$txt_do_no  		= $this->input->post('txt_do_no');
			$txt_old_pinv  		= $this->input->post('txt_old_pinv');
			
			 /*
			 	Check SR,SRET,End Periode
			 */
			 if($txt_old_pinv != NULL){
			 	throw new Exception("Transaksi gagal di Reverse, karena data ini adalah import file tidak mempunyai No Delivery Order, silahkan Reverse transaki yang lain"); //Sudah dibuat di sr atau belum
			 }
			 
			 $date_transaction 	= check_end_periode($txt_si_no);
			
			 $get_detail_srec = $this->m_custom->check_item_reverse($txt_si_no, 'at_salesreceipt', 'at_srecdetail', 'SRecNumber', 'SInvNumber'); //Check sr
			 $get_detail_pret = $this->m_custom->check_item_reverse($txt_si_no, 'at_salesreturn', 'at_sretdetail', 'SRetNumber', 'SInvNumber'); //Check Pret
			 $get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);//Check Periode End
			 
			 if ($get_detail_srec) {
				throw new Exception(msg_check_po_reverse('Sales Receipt')); //Sudah dibuat di sr atau belum
			 } else if ($get_end_periode) {
                throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
             } else if($get_detail_pret) {
			 	throw new Exception(msg_check_po_reverse('Sales Return')); //Sudah dibuat di sret atau belum
			 }
			 /*==============================END=========================*/
			 
			 /*
				Delete invoice payment
			*/
			$this->transaction['delete_invoice_receipt']['InvoiceNumber'] = $txt_si_no;
			/*=========================End===============*/
			
			$data_si = array(
				'TransStatus' 		=> 4,
				'AppFinished' 		=> 0,
				'AppLevel1Status' 	=> 0,
				'AppLevel1Code' 	=> NULL,
				'AppLevel1Date' 	=> NULL,
				'LastUser' 			=> $this->session->userdata("username")
			);
			
			$this->transaction['update_group']['SInvNumber'] 	= $txt_si_no;
            $this->transaction['update_group']['data'] 			= $data_si;
			
			/*
				Update DO trans status 1
			*/
			$data_do = array(
				'TransStatus' => 1
			);
			$this->transaction['update_group_do']['DOrdNumber'] 	= $txt_do_no;
            $this->transaction['update_group_do']['data'] 			= $data_do;
			/*========================End=========================*/
			
			$result_approve = $this->m_sales_invoice->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_si_no);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_si_no);
            }
            echo json_encode($result);
		}
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
	}
	
	// Function Approval Manager
	public function approval_mgr() {
		/*=========================deklar variabel=========================================*/
		
		$SInvNumber 		= $this->input->post('hdn_sinv_no');
		$SInvDate			= date('Y-m-d', strtotime($this->input->post('txt_si_date')));
		$CustomerCode 		= $this->input->post('cmb_customer');
		$CurrencyCode 		= $this->input->post('txt_currency_code');
		$CurrencyRate		= $this->input->post('txt_rate');
		$FiscalRate 		= $this->input->post('txt_fiscal_rate');
		$SInvPPNOut			= $this->input->post('txt_ppn_hide');
		$SInvPPNcnt 		= $this->input->post('txt_pcnt');
		$SInvDiscount		= $this->input->post('txt_discount_hide');
		$SInvEstFreight		= $this->input->post('txt_freight');
		$SInvSubTotal		= $this->input->post('txt_sub_total_hide');
		$SInvSubTotal_Real	= $this->input->post('txt_sub_total');
		$SInvPPH23			= $this->input->post('pph_value');

		
		$SInvTotalAmount 		= $this->input->post('txt_total_amount_hide');
		$SInvTotalAmount_Real 	= $this->input->post('txt_total_amount');
		
		$DOrdNumber 		= $this->input->post('txt_do_no');
		$TermpId 			= $this->input->post('cmb_terms');
		$BranchCode 		= $this->input->post('txt_hide_branch');
		$result_edit 		= 0;
		
		$detail 			= json_decode($this->input->post('detail'));
		
		//due date
		$term 				= $this->m_customer->get_terms_by_row($TermpId);
		$term_waktu 		= $term->NetDueIn;
		$pecah 				= explode('-', $SInvDate);
		$tahun 				= $pecah[0];
		$bulan 	 			= $pecah[1];
		$tanggal 			= $pecah[2];
		$nextN 				= mktime(0,0,0, $bulan, $tanggal + $term_waktu, $tahun);
		$tgl_tempo 			= date('Y-m-d', $nextN);
		//end
		/*===============================end=====================================================*/
		
		//update do transstatus
		$data_do = array (	
					
			'TransStatus' 		=> 2, 
			'AppLevel1Status' 	=> 1,
			'AppLevel1Code'     => $this->session->userdata("username"), 
			'AppLevel1Date'		=> date("Y-m-d"), 
			'LastUser' 			=> $this->session->userdata("username")
		);
		
		$this->transaction['update_do']['data'] = $data_do;
		$this->transaction['update_do']['DOrdNumber'] = $DOrdNumber;
		//end
		
		//update outstanding dan temp outstanding
		if($CurrencyCode != 'IDR'){
			$SInvTotalAmount = $SInvTotalAmount - $SInvPPNOut;
		}
		else{
			$SInvTotalAmount = $SInvTotalAmount;
		}
		
		$CustOutstanding 		= $this->m_customer->get_OustStanding($CustomerCode);
		$TempOutstanding 		= $this->m_customer->get_TemOutstanding($CustomerCode);
		$CustOutstanding_Fiscal = $this->m_customer->get_OustStanding_fiscal($CustomerCode);
		
		if($SInvPPNOut > 0 && $CurrencyCode!='IDR'){
			$CustOutstanding_Fiscal = doubleval($CustOutstanding_Fiscal) + (doubleval($SInvPPNOut) * $FiscalRate);
			
			$data_customer_fiscal = array(
				'OutStandingFiscal'		=> $CustOutstanding_Fiscal,
				'LastUser'				=> $this->session->userdata("username")
			);
			
			$this->transaction['update_customer']['data'] = $data_customer_fiscal;
			$this->transaction['update_customer']['CustomerCode'] = $CustomerCode;
		}
		
		$CustOutstanding = doubleval($CustOutstanding) + doubleval($SInvTotalAmount);
		$TempOutstanding = doubleval($TempOutstanding) - doubleval($SInvSubTotal);
		
		$data_customer = array(
			'OutStanding'		=> $CustOutstanding,
			'TempOutStanding'	=> $TempOutstanding, 
			'LastUser'			=> $this->session->userdata("username")
		);
		
		$this->transaction['update_customer']['data'] = $data_customer;
		$this->transaction['update_customer']['CustomerCode'] = $CustomerCode;
		//end
		if($SInvTotalAmount_Real > 0){
			$CategoryIDCode         = array();
			$PPNCategoryAmount      = array();
			
			foreach($detail as $row){
				@$CategoryAmount[$row->ItemCategoryID] 		+= $row->ItemAmount;
				@$PPNCategoryAmount[$row->ItemCategoryID] 	+= $row->ItemTax;
				@$CategoryIDCode[$row->ItemCategoryID]      = $row->ItemCategoryID;
				@$CategoryIDType[$row->ItemCategoryID]      = $row->ItemType;
			}
			
			$total_records  			= count(@$CategoryAmount);
			$total_loop     			= 0;
			$total_ratio    			= 0;
			$FreightAmount  			= 0;
			$Persen 					= 100;
			$ItemRatio 				  	= 0;		
			$ReceivableAmountCurrency 	= 0;
			$RecivTotal 				= 0;
			
			
			foreach($CategoryAmount as $key=>$value){
			
				$total_loop++;
				
				if($total_loop == $total_records){
					$ItemRatio = $Persen - $total_ratio;
				} 
				else {
					$ItemRatio = floor(abs((doubleval($value) / $SInvSubTotal) * 100));
				}
				$total_ratio  		= $total_ratio + $ItemRatio;
				
				$FreightAmount 		= $SInvEstFreight * ($ItemRatio/100);
				$SubTotal 			= $SInvSubTotal * ($ItemRatio/100);
				$PPNAmount 			= $SInvPPNOut * ($ItemRatio/100);
				$PPHAmount 			= $SInvPPH23 * ($ItemRatio/100);

				$item_ppn       	= ($CurrencyCode == 'IDR' && $SInvPPNcnt > 0) ? $PPNAmount : 0;    
				$Total_Purchase 	= $SubTotal + $item_ppn + $FreightAmount-$PPHAmount;
				
				if(($SInvSubTotal_Real + $SInvEstFreight) > 0){
					$data_invoice_receipt = array(
						'BranchCode'		=> $BranchCode, 
						'CustomerCode'		=> $CustomerCode, 
						'InvoiceCurrCode'	=> $CurrencyCode, 
						'InvoiceCurrRate'	=> $CurrencyRate, 
						'InvoiceFiscalRate'	=> $FiscalRate, 
						'InvoiceNumber'		=> $SInvNumber, 
						'InvoiceDate'		=> $SInvDate, 
						'InvoiceAmount'		=> $Total_Purchase,
						'InvoiceOwing' 		=> $Total_Purchase, 
						'InvoiceCurrency'	=> $Total_Purchase, 
						'ItemCategoryRatio' => $ItemRatio, 
						'ItemCategoryID'	=> $key,
						'InvoiceType'		=> 0, 
						'ItemCategoryCode'  => $CategoryIDCode[$key],
						'ItemType' 			=> $CategoryIDType[$key],
														
						'PPnFiscalStatus'	=> 0, 
						'LastUser'			=> $this->session->userdata('username')
					);
					
					$this->transaction['insert_receipt']['data'][] = $data_invoice_receipt;
				}
			}
			
			if(($SInvPPNOut > 0) && ($CurrencyCode!='IDR')){
				$data_si_receipt_ppn = array(
					'BranchCode'		=> $BranchCode, 
					'CustomerCode'		=> $CustomerCode, 
					'InvoiceCurrCode'	=> $CurrencyCode, 
					'InvoiceCurrRate'	=> doubleval($CurrencyRate), 
					'InvoiceFiscalRate'	=> doubleval($FiscalRate), 
					'InvoiceNumber'		=> $SInvNumber, 
					'InvoiceDate'		=> $SInvDate, 
					'InvoiceAmount'		=> doubleval($SInvPPNOut) * doubleval($FiscalRate),
					'InvoiceOwing' 		=> doubleval($SInvPPNOut) * doubleval($FiscalRate), 
					'InvoiceCurrency'	=> doubleval($SInvPPNOut) * doubleval($FiscalRate), 
					'ItemCategoryRatio' => 100, 
					'ItemCategoryID'	=> -3,
					'ItemCategoryCode' 	=> 'PPn Fiscal',
					'InvoiceType'		=> 0, 
					'PPnFiscalStatus'	=> 1, 
					'LastUser'			=> $this->session->userdata('username')
				);
				$this->transaction['insert_receipt_fiscal']['data'] = $data_si_receipt_ppn;
			}
			
			//update status sales invoice
			$data_si_transstatus = array (		
				'TransStatus' 		=> 1,
				'SinvDueDate' 		=> $tgl_tempo,
				'AppLevel1Status' 	=> 1,
				'AppFinished' 		=> 1,
				'AppLevel1Code'     => $this->session->userdata("username"), 
				'AppLevel1Date'		=> date("Y-m-d"), 
				'LastUser' 			=> $this->session->userdata("username")
			);
			
			$this->transaction['update_group']['data'] = $data_si_transstatus;
			$this->transaction['update_group']['SInvNumber'] = $SInvNumber;
			//end
		}
		else{
			//update status sales invoice
			$data_si_transstatus = array (		
				'TransStatus' 		=> 2,
				'SinvDueDate' 		=> $tgl_tempo,
				'AppLevel1Status' 	=> 1,
				'AppFinished' 		=> 1,
				'AppLevel1Code'     => $this->session->userdata("username"), 
				'AppLevel1Date'		=> date("Y-m-d"), 
				'LastUser' 			=> $this->session->userdata("username")
			);
			
			$this->transaction['update_group']['data'] = $data_si_transstatus;
			$this->transaction['update_group']['SInvNumber'] = $SInvNumber;
			//end
			
			if(($SInvPPNOut > 0) && ($CurrencyCode!='IDR')){
				$data_si_receipt_ppn = array(
					'BranchCode'		=> $BranchCode, 
					'CustomerCode'		=> $CustomerCode, 
					'InvoiceCurrCode'	=> $CurrencyCode, 
					'InvoiceCurrRate'	=> doubleval($CurrencyRate), 
					'InvoiceFiscalRate'	=> doubleval($FiscalRate), 
					'InvoiceNumber'		=> $SInvNumber, 
					'InvoiceDate'		=> $SInvDate, 
					'InvoiceAmount'		=> doubleval($SInvPPNOut) * doubleval($FiscalRate),
					'InvoiceOwing' 		=> doubleval($SInvPPNOut) * doubleval($FiscalRate), 
					'InvoiceCurrency'	=> doubleval($SInvPPNOut) * doubleval($FiscalRate), 
					'ItemCategoryRatio' => 100, 
					'ItemCategoryID'	=> -3,
					'ItemCategoryCode' 	=> 'PPn Fiscal',
					'InvoiceType'		=> 0, 
					'PPnFiscalStatus'	=> 1, 
					'LastUser'			=> $this->session->userdata('username')
				);
				$this->transaction['insert_receipt_fiscal']['data'] = $data_si_receipt_ppn;
			}
			
		}
		
		$result_app = $this->m_sales_invoice->approval_transaction($this->transaction);
		$this->transaction 	= [];
			
		/*=============================trans roll back dan trans commit============================/*/
		if ($result_app == 0) {
			$result['status'] 		= FALSE;
			$result['message']  = get_notification('approval', 0);
		}
		else {
			$result['status'] 		= TRUE;
			$result['message']  = get_notification('approval', 1);
		}
		/*==================================end======================================================*/
		echo json_encode($result);
	}
	
	//Function preview data
	public function to_preview($obj_string = null){
	     // set data
		$data['menu_id'] =  $this->menu_id;
		$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data_filter            = arrayParamInUrlToStr($obj_string);
		$data['branch_code'] = $data_filter['cmb_branch'];
		$data['company_code'] = $data_filter['cmb_company'];
		
		$data['list'] = $this->m_sales_invoice->get_all_print($data_filter);
		
		$this->load->view('v_header');
		$this->load->view('sales/sales_invoice/v_preview_salesinvoice', $data);	
		$this->load->view('v_footer');	
	}
	
	//Function To Print
	public function to_print(){	
		 // set data
		$data['menu_id'] =  $this->menu_id;
		$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
		
		$data['list'] = $this->m_sales_invoice->get_all();
		
		$this->load->view('v_header');
		$this->load->view('sales/sales_invoice/v_print_salesinvoice', $data);	
		$this->load->view('v_footer');	
	}
	
	// Function Print
	function print_preview(){	
        $data['number']    = '0';	
		$data['filename']="Sales_invoice";
		$this->load->view('sales/sales_invoice/v_print_detail_salesinvoice', $data);
	}
	
	// Function Print
	function to_print_detail(){
	    // get link from tbl_menu 
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
		// get label from tbl_menu 
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data
		$id = str_replace($data['menu_link'].'/to_print_detail/',"",$this->uri->uri_string());
		if($id!=""){		
			$data['detail'] = $this->m_sales_invoice->get_detail_print($id);
			$data['list'] = $this->m_sales_invoice->get_detail_item_print($data['detail']->SInvNumber);		
			
			$this->load->view('v_header');
			$this->load->view('sales/sales_invoice/v_print_detail_salesinvoice', $data);	
			$this->load->view('v_footer');	
		}
	}
	
	//Function preview data
	function to_preview_detail(){
	    // get link from tbl_menu 
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
		// get label from tbl_menu 
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data
		$id = str_replace($data['menu_link'].'/to_preview_detail/',"",$this->uri->uri_string());
		if($id!=""){		
			$data['detail'] = $this->m_sales_invoice->get_detail($id);
			$data['list'] = $this->m_sales_invoice->get_detail_item($data['detail']->SInvNumber);		
			
			$this->load->view('v_header');
			$this->load->view('sales/sales_invoice/v_preview_detail_salesinvoice', $data);	
			$this->load->view('v_footer');	
		}
	}
	
	function to_print_journal(){	
	    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data	 
		$id = str_replace($data['menu_link'].'/to_print_journal/',"",$this->uri->uri_string());
		$data['detail'] = $this->m_sales_invoice->get_detail($id);
		$data['list']   = $this->m_sales_invoice->get_journal_by_number($id);		
		$this->load->view('v_header');
		$this->load->view('sales/sales_invoice/v_print_journal_salesinvoice',$data);	
		$this->load->view('v_footer');	
	}
	
	function to_preview_journal(){	
	    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data 
		$id = str_replace($data['menu_link'].'/to_preview_journal/',"",$this->uri->uri_string());
		$data['detail'] = $this->m_sales_invoice->get_detail($id);
		$data['list']   = $this->m_sales_invoice->get_journal_by_number($id);		
		$this->load->view('v_header');
		$this->load->view('sales/sales_invoice/v_preview_journal_salesinvoice',$data);	
		$this->load->view('v_footer');	
	}
	
	public function ajax(){
		$page	= ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
		$rows	= ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
		
		$hasil = array();
		/*===========rows*page tidak boleh melebihi dari jumlah data======= */
		
		/*=================================post dari find di kiri====================================================*/
		$param 			= $this->input->post('param');
		$Number			= isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : ''; 
		$Desc			= isset($param['txt_Description']) ? $param['txt_Description'] : ''; 
		
		$DateFrom		= isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
		$DateTo			= isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
		$TransStatus	= isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
		$BranchCode		= isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
		
		$cmb_CustomerCode	= isset($param['cmb_CustomerCode']) ? $param['cmb_CustomerCode'] : '';
		/*============================================end============================================================*/
		/*========================jika kondisi tidak sama dengan kosong di find lakukan proses di if=================*/
		if($BranchCode != ""){
			$this->db->where('BranchCode', $BranchCode);
		}
		else{
			$this->db->where('BranchCode', $this->session->userdata('branch'));
		}
		
		if($Number != ""){$this->db->like('SInvNumber', $Number);} 
		if($Desc != ""){$this->db->like('SInvDesc', $Desc);}
		if($cmb_CustomerCode != ""){$this->db->where('CustomerCode', $cmb_CustomerCode);} 
		 
		if($TransStatus!=''){ 
			$this->db->where_in('TransStatus', $TransStatus);
		}
		else{
			/*
				default adalah 2,6. Finished dan Need Approval
			*/
			$this->db->where_in('at_salesinvoice.TransStatus',array(0,1,4,5,6,7));
		}
		
		
		if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where('at_salesinvoice.SInvDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_salesinvoice.SInvDate <=', date("Y-m-d", strtotime($DateTo))); 
			}
        }
		/*==========================end=================================================================*/
		
		$count_data = $this->db->count_all_results('at_salesinvoice'); 
		$offset 	= $count_data - ($rows * $page);
		if($offset > 0){
			$rows = $rows;
		}
		else{
			$rows = $count_data - ($rows*($page-1));
		}
		/*========================end=======================================*/
		$result = $this->m_sales_invoice->get_all(); 
		
		for($i=0; $i<=($rows-1); $i++){
			// kalau master ambil dari get_status_master(), kalau transaksi get_status()
			$TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(
				'TransNumber' 	=>	$result[$i]->SInvNumber,
				'SInvDate' 		=>	$result[$i]->SInvDate, 
				'BranchName' 	=>	$result[$i]->BranchName, 
				'CustomerName' 	=>	$result[$i]->CustomerName, 
				'DOrdNumber' 	=>	$result[$i]->DOrdNumber, 
				'DOrdDate' 		=>	$result[$i]->DOrdDate, 
				'SOrdNumber' 	=>	$result[$i]->SOrdNumber, 
				'CustPONumber' 	=>	$result[$i]->CustPONumber, 
				'SInvDesc' 		=>	$result[$i]->SInvDesc, 
				'TransStatus' 	=>	$TransStatus,
				'CreatedBy' 	=> $result[$i]->CreatedBy 
			);
		}

		if(empty($hasil)){
			$emptyVar = array();
			echo json_encode($emptyVar);
		}
		else{
			$result = array();
			$result['total'] = $count_data;
			$result['rows'] = $hasil;
			echo json_encode($result);
		}
	}
	
	public function ajax_detail(){
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$id = str_replace($data['menu_link'].'/ajax_detail/',"",$this->uri->uri_string());
		
		$result = $this->m_sales_invoice->get_detail_item($id);
		
		foreach($result as $row) {
			$hasil[] = array(
				'SInvDetailID'		=> $row->SInvDetailID,
				'SInvNumber'		=> $row->SInvNumber,
				'ItemCategoryID'	=> $row->ItemCategoryID,
				'ItemCategoryCode'	=> $row->ItemCategoryCode,
				'ItemDesc'			=> $row->ItemDesc,
				'ItemCode'			=> $row->ItemCode,
				'ItemDesc'			=> $row->ItemDesc,
				'ItemQty'			=> $row->ItemQty,
				'ItemUnit'			=> $row->ItemUnit,
				'ItemPrice'			=> $row->ItemPrice, 
				'ItemDiscPcnt'		=> $row->ItemDiscPcnt,
				'ItemTax'			=> $row->ItemTax, 
				'ItemAmount'		=> $row->ItemAmount,
				'ItemAmountKoma'	=> $row->ItemAmountKoma,
				'ItemTaxtKoma'		=> $row->ItemTaxtKoma,
				'ItemType'			=> $row->ItemType,
				'ItemPph23'			=> $row->ItemPPH23,
				'ItemStatus'		=> $row->ItemType
			); 
		}
		
		echo json_encode($hasil);
	}
	
	public function ajax_filter(){
		$cust = $this->input->post('cust_code');
		
		if(!empty($cust)){
           echo json_encode($this->m_sales_invoice->get_si_detail_for_return($cust));
		}
		else{
			echo '[]';
		}
	}

	public function ajax_invoice(){
		$cust = $this->input->post('cust_code');
		
		if(!empty($cust)){
			$data_invoice = $this->m_sales_invoice->get_for_invoice_by_cust($cust);
			$data_order = $this->m_sales_order->get_for_invoice_by_cust($cust);
			$result = array_merge($data_invoice, $data_order);
			
			echo json_encode($result);
		}
		else{
			echo '[]';
		}
	}
	
	public function trans_rollback($modus, $AccounName, $Currency) {
        $this->db->trans_rollback();
        $result['status']   = false;

        if($modus == 'approval'){
            $result['message']  = get_notification($modus, 0);
        }
        else{
             $result['message']  = get_notification_preference($modus, 0, $AccounName, $Currency);               
        }
                
        echo json_encode($result);
        die();
    }
	
}
	