<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Ladur / 08-08-2014	
 *	Revisi 	: Ferry / 05-03-2015
 	Revisi 	: Fachri 
 */
 
class Sales_receipt extends CI_Controller {
    public $menu_id     	= 164;
    public $code        	= 'Sales Receipt Number';
    public $name        	= 'Sales Receipt';
    public $app1        	= array('MGR','SPV');
    public $app2       	 	= array('DIR');
    public $app_level   	= array('DIR','MGR','SPV');
	public $app_level_new   = array(0,1);
	
    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('regex');
			$this->load->helper('lables');
			$this->load->helper('custom_string_helper');

			$this->load->model('setup/m_branchinfo');
			$this->load->model('m_sales_receipt');
			$this->load->model('m_sales_invoice');
			$this->load->model('m_sales_quotation');
			$this->load->model('m_sales_order');
			$this->load->model('m_customer');
			$this->load->model('m_employee');
			$this->load->model('m_sales_dp');
			$this->load->model('m_account_journal');
			$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();
				}
			}
			
    }
	
    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_receipt/v_salesreceipt', $data);	
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
			
    }
	
    //Function Form Edit
    public function add($SInvNumber='',$CustomerCode='',$CurrencyCode='') {
		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_add($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);
					$data['SInvNumber'] 	= $SInvNumber;
					$data['CustomerCode'] 	= $CustomerCode; 
					$data['CurrencyCode'] 	= $CurrencyCode;

					$data['srec_date']  = date('d-m-Y');
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					// set for view
					$this->load->view('v_header');
					$this->load->view('sales/sales_receipt/v_new_salesreceipt', $data);
					$this->load->view('v_footer');
					//----------------------end--------------------------------------------------------		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
    
    // Function Insert
	public function insert(){
		/*=============Deklar variabel======================================================================*/
        $BranchCode         = $this->session->userdata('branch');
        $DepartmentCode     = $this->input->post('cbg_department');
		$CustomerCode       = $this->input->post('cbg_customer');
        
        $Currency_Code      = $this->input->post('hdn_cust_curr_code');
        $BankPayment        = $this->input->post('cbg_bank');
		
        $Bank_Curr_Code     = $this->input->post('hdn_bank_curr_code');
		$Bank_Number     	= $this->input->post('hdn_bank_number');
		
        $Bank_Curr_Rate     = $this->input->post('txt_bank_curr_rate');
		$SRecDate 			= date("Y-m-d", strtotime($this->input->post('txt_srec_date')));
		$SRecNumber  		= $this->m_sales_receipt->create_sr_number($SRecDate, $Bank_Number);
        $SRecDesc           = $this->input->post('txa_description');

        $ppnfiscal_status   = $this->input->post('chk_fiscal_payment');
        $ChequeNumber       = $this->input->post('txt_cheque_no');
        $ChequeAmount       = $this->input->post('txt_cheque_amount');
		$DPTotal 			= $this->input->post('txt_cust_dp_return');
		
		$TotalAmount 			= $this->input->post('txt_total_amount');
		$AmountCustomerDP 		= $this->input->post('txt_cust_dp_return');
		$CustomerDpPartial 		= $this->input->post('txt_cust_dp_part');
		$hdn_total_currency 	= $this->input->post('hdn_total_currency');
		$hdn_SInvTotalAmount 	= $this->input->post('hdn_SInvTotalAmount');
		$hdn_SRecTotalOwing 	= $this->input->post('hdn_SRecTotalOwing');
		$hdn_SRecTotalDPUsed 	= $this->input->post('hdn_SRecTotalDPUsed');
		$hdn_SRecTotalDiscount 	= $this->input->post('hdn_SRecTotalDiscount');
        /*=====================End=======================================================================*/
		
		$total_invoice      = 0;
        $total_owing        = 0;
		$invoice_loop 		= 0;
        $detail_post        = $this->input->post('detail');        
        $detail             = json_decode($detail_post);
		
		if(count($detail) > 0){
			$this->db->trans_begin();
			
			$get_customer_for_lock_status = $this->m_sales_receipt->get_customer_for_lock_status($CustomerCode);
			if($get_customer_for_lock_status->LockStatus == 1){
				$result['status']    = false;
            	$result['message']   = "Transaksi gagal, customer code sudah di lock silahkan proses transaksi dengan customer ".$get_customer_for_lock_status->CustomerName."";
				echo json_encode($result);
				$this->db->trans_rollback();
				die();
			}
			
			/*
				Insert Group
			*/
			$this->insert_group($DepartmentCode, $hdn_SRecTotalDPUsed, $hdn_SRecTotalDiscount, $hdn_SRecTotalOwing, $hdn_SInvTotalAmount, $TotalAmount,$AmountCustomerDP, $hdn_total_currency, $BranchCode, $CustomerCode, $SRecDate, $SRecDesc, $SRecNumber, $BankPayment, $Currency_Code, $Bank_Curr_Code, $Bank_Curr_Rate, $ChequeNumber, $ChequeAmount, $ppnfiscal_status);
			/*==============================End==============================*/
			
			foreach($detail as $row){
				if ($row->Paid == 'Yes') {
					$item_category_id   = $row->ItemCategoryID;
                    
                    $invoice_rate       = $row->InvoiceCurrRate;
                    $fiscal_rate        = $row->InvoiceFiscalRate;
                    $invoice_number     = $row->Invoice_Number;                    
                    $invoice_amount     = $row->Invoice_Amount;
                    $invoice_owing      = $row->Invoice_Owing;
					$invoice_owing_temp = $row->InvoiceOwingHiddenNew;
					
					$invoice_copy       = $row->InvoiceAmountCopy;
					$invoice_owing_copy = $row->InvoiceOwingHidden;
					
					$total_hutang 		=  $invoice_owing_copy - $invoice_owing_temp;
					
                    $payment_dp         = $row->Receipt_DP;
                    $payment_disc       = $row->Receipt_Discount;
                    $payment_amount     = $row->Receipt_Amount;
                    $payment_currency   = $row->Receipt_Currency;
					$Load_Rounding   	= $row->Load_Rounding;
					$Select_DP   		= $row->Select_DP;
					$Relized_all_trans 	= $payment_disc + $payment_amount;
					
					$Advanced 			= '';	
					$total_dp 			= 0;
					$relize_dp 			= 0;
					$total_relize 		= 0;
					
					$invoice_loop++; 
					
					$invoice_currency   = $Currency_Code == 'IDR' ? $payment_amount : $payment_amount * $invoice_rate;
					if($Currency_Code == 'IDR'){
						$invoice_currency    	= $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;
					}
					else{
						$invoice_currency    	= $Bank_Curr_Code == 'IDR' ? $payment_amount * $Bank_Curr_Rate : $payment_amount;	
					}
					
					$invoice_date       = date("Y-m-d", strtotime($row->Invoice_Date));
                    $total_invoice      += $invoice_amount;
                    $total_owing        += $invoice_owing;
					
					if($item_category_id == -3){
                        /*====================Fiscal Rate============================================================*/
						$total_amount_paid 		= 0;
						$total_currency_paid 	= 0;
							
						$data_payment 				= $this->m_sales_receipt->get_receipt($invoice_number, 0, 1);
						foreach($data_payment as $row_payment){
							$ipay_payment_id        = $row_payment->InvoicePaymentID;
							$ipay_category_code     = $row_payment->ItemCategoryCode;
							$ipay_category_id       = $row_payment->ItemCategoryID;
							$ipay_item_type       	= $row_payment->ItemType;
							$ipay_ItemCategoryRatio = $row_payment->ItemCategoryRatio;
							$ipay_category_amount   = $row_payment->InvoiceOwing;
							$inv_amount             = $row_payment->InvoiceAmount;
							$payment_total          = $payment_amount + $Load_Rounding;
						}
						
                        /*=======================Insert PPay Detail===================================================================*/
						$this->insert_detail(
							$SRecDate,1,NULL,$ipay_ItemCategoryRatio, NULL,$ipay_payment_id, $SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $invoice_owing_temp,
							$invoice_rate, $fiscal_rate, $Bank_Curr_Rate, NULL, '0', '0', $payment_amount, $payment_total, 
							$payment_currency, $invoice_currency, 0, $Load_Rounding, '1', $ipay_category_id, $ipay_category_code, $ipay_category_amount, $ipay_item_type
						);
						/*===========================End=============================================================================*/
                        
						
						/*
							Insert Journal Bank Acccount
						*/
						$BankAccount    = $BankPayment;	
						$bank_amount    = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;		
						$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_currency;
						
						$journal_bank = array(
											'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
											'SRecNumber'                => $SRecNumber,
											'SRecDesc'                  => $SRecDesc,
											'SRecAccountNumber'         => $BankAccount,
											'SRecSaldoDebet'            => $bank_amount,
											'SRecSaldoCredit'           => 0,
											'AmountCurrency'            => $bank_currency,
											'SRecSignStatus'            => 0, 
											'ItemCategoryID'            => $item_category_id,
											'SInvNumber' 				=> $invoice_number,
											'LastUser'                  => $this->session->userdata("username")
										 );
				
						$this->m_sales_receipt->insert_journal($journal_bank);
						/*=====================End=============================================================================*/
						
						/*
							Insert Journal PPn Fiscal
						*/
						$PPnFiscalAccount   = $this->m_account_journal->get_account_name('Piutang PPn Fiscal'); 
						if($PPnFiscalAccount == false) {$this->trans_rollback('journal','Sales Piutang PPn Fiscal, Taxable', $CurrencyCode_Cus);}
						
						$fiscal_value    	= $Bank_Curr_Code == 'IDR' ? $total_hutang : $total_hutang;	
						$fiscal_currency  	= $Bank_Curr_Code == 'IDR' ? $total_hutang : $total_hutang / $Bank_Curr_Rate;
						$fiscal_realize    	= $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;
						
						$journal_fiscal     = array(
												'SRecDate'              => date("Y-m-d", strtotime($SRecDate)),
												'SRecNumber'            => $SRecNumber,
												'SRecDesc'              => $SRecDesc,
												'SRecAccountNumber'     => $PPnFiscalAccount->AccountNumber,
												'SRecSaldoDebet'        => 0,
												'SRecSaldoCredit'       => $fiscal_value,
												'AmountCurrency'        => $fiscal_currency,
												'SRecSignStatus'        => 1, 
												'ItemCategoryID'        => $item_category_id,
												'SInvNumber' 			=> $invoice_number,
												'LastUser'              => $this->session->userdata("username")	
											 );
				
						$this->m_sales_receipt->insert_journal($journal_fiscal);
						/*=====================End=================================================================*/         
                        
						
						/*
							Beban Pembulatan Auto
						*/
						$Total_Beban 		= ($payment_amount + $Load_Rounding) - ($total_hutang);
						if($Total_Beban > 0){
							$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
							if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
							
							if($Currency_Code == 'IDR'){
								$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
							else{
								$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
							
							$beban_pembulatan_auto           = array(
								'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
								'SRecNumber'                => $SRecNumber,
								'SRecDesc'                  => $SRecDesc,
								'SRecAccountNumber'         => $BebanAccountAuto->AccountNumber,
								'SRecSaldoDebet'            => 0,
								'SRecSaldoCredit'           => abs($beban_amount_auto),
								'AmountCurrency'            => 0,
								'SRecSignStatus'            => 1, 
								'ItemCategoryID'            => $item_category_id,
								'SInvNumber' 				=> $invoice_number,
								'LastUser'                  => $this->session->userdata("username")
							 );
							 $this->m_sales_receipt->insert_journal($beban_pembulatan_auto);
						}
						else if($Total_Beban < 0){
							$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
							if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
							
							if($Currency_Code == 'IDR'){
								$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
							else{
								$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
						
							$beban_pembulatan_auto           = array(
								'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
								'SRecNumber'                => $SRecNumber,
								'SRecDesc'                  => $SRecDesc,
								'SRecAccountNumber'         => $BebanAccountAuto->AccountNumber,
								'SRecSaldoDebet'            => abs($beban_amount_auto),
								'SRecSaldoCredit'           => 0,
								'AmountCurrency'            => 0,
								'SRecSignStatus'            => 0, 
								'ItemCategoryID'            => $item_category_id,
								'SInvNumber' 				=> $invoice_number,
								'LastUser'                  => $this->session->userdata("username")
							 );
							 
							 $this->m_sales_receipt->insert_journal($beban_pembulatan_auto);
						}
						/*===============End=====================*/
							
						/*
							Beban Pembulatan
						*/
						if($Load_Rounding > 0){
							$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
							if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
							
							$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
							if($Currency_Code == 'IDR'){
								$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
							}
							else{
								$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
							}

							
							$beban_pembulatan         		= array(
								'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
								'SRecNumber'                => $SRecNumber,
								'SRecDesc'                  => $SRecDesc,
								'SRecAccountNumber'         => $BebanAccount->AccountNumber,
								'SRecSaldoDebet'            => abs($beban_amount),
								'SRecSaldoCredit'           => 0,
								'AmountCurrency'            => 0,
								'SRecSignStatus'            => 0, 
								'ItemCategoryID'            => $item_category_id,
								'LastUser'                  => $this->session->userdata("username")	
							 );
					
							$this->m_sales_receipt->insert_journal($beban_pembulatan);
						}
						else if($Load_Rounding < 0){
							$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
							if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
							
							$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
							if($Currency_Code == 'IDR'){
								$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
							}
							else{
								$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
							}
							
							$beban_pembulatan         		= array(
								'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
								'SRecNumber'                => $SRecNumber,
								'SRecDesc'                  => $SRecDesc,
								'SRecAccountNumber'         => $BebanAccount->AccountNumber,
								'SRecSaldoDebet'            => 0,
								'SRecSaldoCredit'           => abs($beban_amount),
								'AmountCurrency'            => 0,
								'SRecSignStatus'            => 1, 
								'ItemCategoryID'            => $item_category_id,
								'LastUser'                  => $this->session->userdata("username")	
							 );
					
							$this->m_sales_receipt->insert_journal($beban_pembulatan);
						}	
						/*========================End==========================*/
                        $total_amount_paid      += $payment_amount;
                        $total_currency_paid    += $payment_currency; 
					}
					else{
						$RealizedAccount  = $this->m_account_journal->get_sys_sales_account('RealizedGainedLoss', $Currency_Code);                     
                    	if($RealizedAccount == false) {$this->trans_rollback('journal','Realized G/L, Purchase','');}
						
						if(($row->Invoice_Type == 'SI') && ($item_category_id != -3)){
							$curr_account_no        = '';
							$CategoryIDDisc         = array();
							$CategoryIDCode         = array();
							$CategoryType 			= array();
							
							$payable_value          	= 0;
							$total_loop             	= 0;
							$payable_amount 			= 0;
							$payable_currency 			= 0;
							$total_ppay_realizedgl 		= 0;
							$total_ppay_realizedgl_new 	= 0;
							
							$total_hutang_beban  		= 0;
							$total_hutang_beban_new  	= 0;
		
							$total_amount_paid 			= 0;
							$total_currency_paid 		= 0;
								
							/*=====================Get Invoice Payment new Tabel=============================================*/
							$data_payment = $this->m_sales_receipt->get_receipt($invoice_number, 0, 0);
							foreach($data_payment as $row_payment){
								$total_loop++;
								
								$ipay_payment_id        = $row_payment->InvoicePaymentID;
								$ipay_category_id       = $row_payment->ItemCategoryID;
								$ipay_category_code     = $row_payment->ItemCategoryCode;
								$ipay_category_ratio    = $row_payment->ItemCategoryRatio;
								$ipay_category_amount   = $row_payment->InvoiceOwing;
								$ipay_InvoiceAmount   	= $row_payment->InvoiceAmount;
								$ipay_item_type       	= $row_payment->ItemType;
								$ipay_ItemCategoryRatio = $row_payment->ItemCategoryRatio;
								$ipay_InvoiceCurrRate 	= $row_payment->InvoiceCurrRate;
								
								
								if($ipay_item_type == 0){
									$SalesAccount    = $this->m_account_journal->get_cat_sales_account('SRAccountReceivable', $ipay_category_id, $Currency_Code);
									if($Currency_Code == 'IDR'){
										if($SalesAccount == false) {$this->trans_rollback('preference','Sales Account -> Account Receivable', $Currency_Code);}
									}
									else{
										if($SalesAccount == false) {$this->trans_rollback('journal','Piutang Dagang', $Currency_Code);}
									}
									
									$Advanced = 'AdvanceSales';                           
								}
								else{
									$SalesAccount    = $this->m_account_journal->get_sys_service_account('SalesUnbilled', $Currency_Code);                            
									if($Currency_Code == 'IDR'){
										if($SalesAccount == false) {$this->trans_rollback('preference','Expense Account -> Sales Unbilled (Owing)', $Currency_Code);}
									}
									else{
										if($SalesAccount == false) {$this->trans_rollback('journal','Piutang Expense', $Currency_Code);}
									}
									 
									$Advanced = 'SalesAdvance';                       
								}
								
								$amount_invoice         = $invoice_copy * ($ipay_category_ratio / 100);
								$amount_owing_real      = $invoice_owing * ($ipay_category_ratio / 100);
								$amount_owing_temp      = $invoice_owing_temp * ($ipay_category_ratio / 100);
								
								$amount_owing_copy      = $total_hutang * ($ipay_category_ratio / 100);
								
								$currency_payable       = $payment_currency * ($ipay_category_ratio / 100);
								$amount_payment         = $payment_amount * ($ipay_category_ratio / 100);
								$currency_payable       = $payment_currency * ($ipay_category_ratio / 100);
								
								$amount_dpused          = $payment_dp * ($ipay_category_ratio / 100);
								$amount_discount        = $payment_disc * ($ipay_category_ratio / 100);
								$amount_rounded        	= $Load_Rounding * ($ipay_category_ratio / 100);
								
								if($invoice_owing == 0){
									$amount_total_journal   = $amount_owing_copy;
								}
								else{
									$amount_total_journal   = $amount_dpused + $amount_discount + $amount_rounded + $amount_payment;
								}
								
								if($Currency_Code == 'IDR'){
									$amount_total           = $amount_dpused + $amount_discount + $amount_payment;
									$amount_total_selisih   = $amount_discount + $amount_payment;
								}
								else{
									if($Bank_Curr_Code == 'IDR'){
										$amount_total           = $amount_dpused + $amount_discount + ($currency_payable / $Bank_Curr_Rate);
										$amount_total_selisih   = $amount_discount + ($currency_payable / $Bank_Curr_Rate);
									}
									else{
										$amount_total           = $amount_dpused + $amount_discount + $amount_payment;
										$amount_total_selisih   = $amount_discount + $amount_payment;
									}
								}
								
								if($Currency_Code == 'IDR'){
									$inv_cat_curr_amount    = $amount_total;
									$pay_cat_curr_amount    = $amount_total;                                
								}
								else{
									$inv_cat_curr_amount    = $amount_total_selisih * $invoice_rate;
									$pay_cat_curr_amount    = $amount_total_selisih * $Bank_Curr_Rate;
								}
								
								$ppay_cat_realizedgl    = $pay_cat_curr_amount - $inv_cat_curr_amount;
								//$new_invoice_owing      = $amount_invoice - ($amount_total + $amount_rounded);
								
								if($total_loop == 1){$curr_account_no = $SalesAccount->AccountNumber;}
								
								if($payment_disc > 0){
									@$CategoryIDDisc[$ipay_category_id]     = $amount_discount;
									@$CategoryIDCode[$ipay_category_id]     = $ipay_category_code;
									@$CategoryType[$ipay_category_id]     	= $ipay_item_type;
								}     
								
								//2.Insert ppaydetail
								$this->insert_detail(
									$SRecDate,0,NULL,$ipay_ItemCategoryRatio, $Select_DP, $ipay_payment_id, $SRecNumber, $invoice_number, $invoice_date, $ipay_InvoiceAmount,
									$amount_owing_temp, $invoice_rate, $fiscal_rate, $Bank_Curr_Rate, $invoice_date, $amount_discount,
									$amount_dpused, $amount_payment, $amount_total, $currency_payable, $inv_cat_curr_amount,
									$ppay_cat_realizedgl, $amount_rounded, 0, $ipay_category_id, $ipay_category_code,$ipay_category_amount, $ipay_item_type
								);                            
								//---------------------------------------------------------------------------------------------//
								
								if($Currency_Code == 'IDR'){
									$payable_amount     	= $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal;
									$payable_currency   	= $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal / $Bank_Curr_Rate;
								}
								else{
									$payable_amount    		= $Bank_Curr_Code == 'IDR' ? $amount_total_journal * $ipay_InvoiceCurrRate : $amount_total_journal * $ipay_InvoiceCurrRate;	
									$payable_currency  		= $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal;
								}
								
								$get_journal_receipt = $this->m_sales_receipt->get_journal_recip_empty($SalesAccount->AccountNumber, $SRecNumber, $invoice_number);
								if(empty($get_journal_receipt->SRecAccountNumber)){
									$journal_reciv           = array(
										'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
										'SRecNumber'                => $SRecNumber,
										'SRecDesc'                  => $SRecDesc,
										'SRecAccountNumber'         => $SalesAccount->AccountNumber,
										'SRecSaldoDebet'            => 0,
										'SRecSaldoCredit'           => $payable_amount,
										'AmountCurrency'            => $payable_currency,
										'SRecSignStatus'            => 1, 
										'ItemCategoryID'            => $ipay_category_id,
										'SInvNumber' 				=> $invoice_number,
										'LastUser'                  => $this->session->userdata("username")
									 );
						
									$this->m_sales_receipt->insert_journal($journal_reciv);
								}
								else{
									$payable_amount      = $payable_amount + $get_journal_receipt->SRecSaldoCredit;
									$payable_currency    = $payable_currency + $get_journal_receipt->AmountCurrency;
									
									$journal_reciv           = array(
										'SRecSaldoDebet'            => 0,
										'SRecSaldoCredit'           => $payable_amount,
										'AmountCurrency'            => $payable_currency
									 );
						
									$this->m_sales_receipt->update_journal($journal_reciv, $SRecNumber, $SalesAccount->AccountNumber, $invoice_number);
								}
							}
							/*===============================END Hutang=========================================*/
							
							/*
								Journal Bank Payment - Invoice Payment
							*/
							$payment_val 	= doubleval($payment_amount);
							$bank_amount 	= 0; 
							$bank_currency 	= 0; 
							
							if($payment_val > 0){
								if($Currency_Code == 'IDR'){
									$bank_amount    = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;	
									$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val / $Bank_Curr_Rate;
								}
								else{
									$bank_amount    = $Bank_Curr_Code == 'IDR' ? ($payment_currency / $Bank_Curr_Rate) * $Bank_Curr_Rate : $payment_val * $Bank_Curr_Rate;	
									$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_currency / $Bank_Curr_Rate : $payment_val;
								}
								
								$journal_bank           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BankPayment,
									'SRecSaldoDebet'            => $bank_amount,
									'SRecSaldoCredit'           => 0,
									'AmountCurrency'            => $bank_currency,
									'SRecSignStatus'            => 0, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")
								 );
	
								$this->m_sales_receipt->insert_journal($journal_bank);
	
								$total_amount_paid      += $payment_amount;
								$total_currency_paid    += $payment_currency;                                
							}
							/*======================================================================================*/
							
							/*
								Journal Advance Purchase - Uang Muka Pembelian
							*/
							$total_dp 				= 0;
							$total_dp_no_currency 	= 0;
								
							if($payment_dp > 0) {
								
								/*===================Get Pordetail DP==========================================*/
								$sordetail_dp    		= $this->m_sales_receipt->get_saldo_detail_dp($CustomerCode, $Select_DP, 1);
								
								$saldo_dp 		 		= $payment_dp;
								$saldo_dp_new 		 	= $payment_dp;
								
								$jurnal_dp 				= 0;
								$jurnal_dp_currency 	= 0;
								$jurnal_dp_no_currency 	= 0;
								$currency_rate_detail 	= 0;
								$is_edit 				= "";
								$PaymentBefore 			= 0;
								$PaymentBefore_Sum 		= 0;
								$PaymentPlus			= 0;
								$PaymentPlus_Sum 		= 0;
								
								$relize_debet 			= 0;
								$relize_kredit 			= 0;
								$total_dp 				= 0;
								
								foreach($sordetail_dp as $row_detail_dp){
									$DPUsed					= $row_detail_dp->DPUsed;
									$JVoucherBalance 		= $row_detail_dp->JVoucherBalance; 
									$SaldoDPBalance 		= $row_detail_dp->SaldoDPBalance;
									$currency_rate_detail 	= $row_detail_dp->CurrencyRate;
									
									$DPUsed					= $DPUsed + $JVoucherBalance;
									if($DPUsed != $SaldoDPBalance){
										$dp_used_book 			= 0;
										$saldo_balance_detail 	=  $row_detail_dp->PaymentAmount ;
										$SOrdDetailDPID 		=  $row_detail_dp->SOrdDetailDPID;
										$SaldoDPBalance 		=  $row_detail_dp->SaldoDPBalance;
										
										if($saldo_dp > 0){
											//echo $saldo_dp;
											$saldo_dp 			= doubleval($saldo_dp_new - ($PaymentPlus_Sum + $saldo_balance_detail));
											
											if($saldo_dp < 0){
												$dp_used_old 			= $DPUsed;
												$dp_used_book 			= doubleval($DPUsed + ($saldo_dp_new - $PaymentBefore_Sum));
												$jurnal_dp 				= (doubleval(($saldo_dp_new - $PaymentBefore_Sum) * $currency_rate_detail));
												$jurnal_dp_currency 	= (doubleval($saldo_dp_new - $PaymentBefore_Sum / $currency_rate_detail));
												$jurnal_dp_no_currency 	= doubleval($saldo_dp_new - $PaymentBefore_Sum);
												$update_sordetail = array(
													'DPUsed' 				=> $dp_used_book
												);
												$this->m_sales_receipt->update_so_detail_dp_by_customer($update_sordetail, $CustomerCode, $SOrdDetailDPID, $Select_DP);
												
												$DPAccount  = $this->m_account_journal->get_account_name('Uang Muka Penjualan', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
												if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan','');}
												
												if($Currency_Code == 'IDR'){
													$dp_currency   	= $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_currency / $Bank_Curr_Rate;
												}
												else{
													$dp_currency  	= $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_no_currency;
												}
												
												$journal_dp          = array(
													'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
													'SRecNumber'                => $SRecNumber,
													'SRecDesc'                  => $SRecDesc,
													'SRecAccountNumber'         => $DPAccount->AccountNumber,
													'SRecSaldoDebet'            => $jurnal_dp,
													'SRecSaldoCredit'           => 0,
													'AmountCurrency'            => $dp_currency,
													'SRecSignStatus'            => 1, 
													'ItemCategoryID'            => $item_category_id,
													'SInvNumber' 				=> $invoice_number,
													'SOrdDetailDPID' 			=> $row_detail_dp->SOrdDetailDPID,
													'LastUser'                  => $this->session->userdata("username")
												);
												 
												if($jurnal_dp > 0){
													$this->m_sales_receipt->insert_journal($journal_dp);
												}
												
												if($Currency_Code != 'IDR'){
													$inv_dp_selisih_kurs	= doubleval($jurnal_dp) - doubleval($jurnal_dp_no_currency * $invoice_rate);
													if($inv_dp_selisih_kurs > 0){
														$RealizedAccount  	 	= $this->m_account_journal->get_sys_sales_account('RealizedGainedLoss', $Currency_Code);                     
														if($RealizedAccount == false) {$this->trans_rollback('journal','Realized, Sales',$Bank_Curr_Code);}
											
														$realized_amount    = abs($inv_dp_selisih_kurs);
														$realized_currency  = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;
														
														$journal_RealizedAccount           = array(
															'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
															'SRecNumber'                => $SRecNumber,
															'SRecDesc'                  => $SRecDesc,
															'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
															'SRecSaldoDebet'            => 0,
															'SRecSaldoCredit'           => $realized_amount,
															'AmountCurrency'            => 0,
															'SRecSignStatus'            => 1, 
															'ItemCategoryID'            => $item_category_id,
															'SInvNumber' 				=> $invoice_number,
															'LastUser'                  => $this->session->userdata("username")
														);
														
														$this->m_sales_receipt->insert_journal($journal_RealizedAccount);
													} 
													else if($inv_dp_selisih_kurs < 0){
														$RealizedAccount  	 	= $this->m_account_journal->get_sys_sales_account('RealizedGainedLoss', $Currency_Code);                     
														if($RealizedAccount == false) {$this->trans_rollback('journal','Realized, Sales',$Bank_Curr_Code);}
											
														$realized_amount    = abs($inv_dp_selisih_kurs);
														$realized_currency  = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;
														
														$journal_RealizedAccount           = array(
															'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
															'SRecNumber'                => $SRecNumber,
															'SRecDesc'                  => $SRecDesc,
															'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
															'SRecSaldoDebet'            => $realized_amount,
															'SRecSaldoCredit'           => 0,
															'AmountCurrency'            => 0,
															'SRecSignStatus'            => 0, 
															'ItemCategoryID'            => $item_category_id,
															'SInvNumber' 				=> $invoice_number,
															'LastUser'                  => $this->session->userdata("username")
														);
														
														$this->m_sales_receipt->insert_journal($journal_RealizedAccount);
													}
												}
												$total_dp 				+= $jurnal_dp;
												$total_dp_no_currency 	+= $jurnal_dp_no_currency;
											}
											else{
												$PaidStatus 			= $DPUsed;
												$dp_used_book 			= doubleval(($saldo_balance_detail - $DPUsed) + $PaidStatus);
												$jurnal_dp 				= (doubleval($saldo_balance_detail - $DPUsed) * doubleval($currency_rate_detail));
												$jurnal_dp_currency 	= (doubleval($saldo_balance_detail - $DPUsed) / doubleval($currency_rate_detail));
												$jurnal_dp_no_currency 	= doubleval($saldo_balance_detail - $DPUsed);
												
												$update_sordetail = array(
													'DPUsed' 				=> $dp_used_book
												);
												$this->m_sales_receipt->update_so_detail_dp_by_customer($update_sordetail, $CustomerCode, $SOrdDetailDPID, $Select_DP);
												$PaymentBefore 			= doubleval($saldo_balance_detail - $DPUsed);
												$PaymentBefore_Sum 		+= $PaymentBefore;
												$PaymentPlus 			=  doubleval($saldo_balance_detail + $DPUsed);
												$PaymentPlus_Sum 		+= $PaymentPlus;
												
												$DPAccount  = $this->m_account_journal->get_account_name('Uang Muka Penjualan', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
												if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan','');}
												
												if($Currency_Code == 'IDR'){
													$dp_currency   	= $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_currency / $Bank_Curr_Rate;
												}
												else{
													$dp_currency  	= $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_no_currency;
												}
												
												$journal_dp          = array(
													'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
													'SRecNumber'                => $SRecNumber,
													'SRecDesc'                  => $SRecDesc,
													'SRecAccountNumber'         => $DPAccount->AccountNumber,
													'SRecSaldoDebet'            => $jurnal_dp,
													'SRecSaldoCredit'           => 0,
													'AmountCurrency'            => $dp_currency,
													'SRecSignStatus'            => 1, 
													'ItemCategoryID'            => $item_category_id,
													'SInvNumber' 				=> $invoice_number,
													'SOrdDetailDPID' 			=> $row_detail_dp->SOrdDetailDPID,
													'LastUser'                  => $this->session->userdata("username")
												);
												
												if($jurnal_dp > 0){
													$this->m_sales_receipt->insert_journal($journal_dp);
												}
												
												if($Currency_Code != 'IDR'){
													$inv_dp_selisih_kurs	= doubleval($jurnal_dp) - doubleval($jurnal_dp_no_currency * $invoice_rate);
													if($inv_dp_selisih_kurs > 0){
														$RealizedAccount  	 	= $this->m_account_journal->get_sys_sales_account('RealizedGainedLoss', $Currency_Code);                     
														if($RealizedAccount == false) {$this->trans_rollback('journal','Realized, Sales',$Bank_Curr_Code);}
											
														$realized_amount    = abs($inv_dp_selisih_kurs);
														$realized_currency  = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;
														
														$journal_RealizedAccount           = array(
															'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
															'SRecNumber'                => $SRecNumber,
															'SRecDesc'                  => $SRecDesc,
															'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
															'SRecSaldoDebet'            => 0,
															'SRecSaldoCredit'           => $realized_amount,
															'AmountCurrency'            => 0,
															'SRecSignStatus'            => 1, 
															'ItemCategoryID'            => $item_category_id,
															'SInvNumber' 				=> $invoice_number,
															'LastUser'                  => $this->session->userdata("username")
														);
														
														$this->m_sales_receipt->insert_journal($journal_RealizedAccount);
													} 
													else if($inv_dp_selisih_kurs < 0){
														$RealizedAccount  	 	= $this->m_account_journal->get_sys_sales_account('RealizedGainedLoss', $Currency_Code);                     
														if($RealizedAccount == false) {$this->trans_rollback('journal','Realized, Sales',$Bank_Curr_Code);}
											
														$realized_amount    = abs($inv_dp_selisih_kurs);
														$realized_currency  = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;
														
														$journal_RealizedAccount           = array(
															'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
															'SRecNumber'                => $SRecNumber,
															'SRecDesc'                  => $SRecDesc,
															'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
															'SRecSaldoDebet'            => $realized_amount,
															'SRecSaldoCredit'           => 0,
															'AmountCurrency'            => 0,
															'SRecSignStatus'            => 0, 
															'ItemCategoryID'            => $item_category_id,
															'SInvNumber' 				=> $invoice_number,
															'LastUser'                  => $this->session->userdata("username")
														);
														
														$this->m_sales_receipt->insert_journal($journal_RealizedAccount);
													}
												}
												$total_dp 			+= $jurnal_dp;
												$total_dp_no_currency 	+= $jurnal_dp_no_currency;
											}
										}
									
										$update_isedit = array(
											'IsEdit' 				=> 1
										);
										$this->m_sales_receipt->update_so_detail_dp_by_customer($update_isedit, $CustomerCode, $SOrdDetailDPID, $Select_DP);
									}
								}
								/*========================End===================================================*/
							}
							/*=======================End==================================================================*/

							/*
								Journal Discount Invoice - Potongan Pembelian  
							*/   
							$total_discount = 0;                           
							if($payment_disc > 0){
								$total_loop         	= 0;
								$curr_account_no    	= '';
	
								$discount_amount      	= 0;
								$discount_currency   	= 0;
								$invoice_loop_disc 		= "";
								
								foreach($data_payment as $row_disc){
									$ipay_payment_id_disc        = $row_disc->InvoicePaymentID;
									$ipay_category_id_disc       = $row_disc->ItemCategoryID;
									$ipay_category_code_disc     = $row_disc->ItemCategoryCode;
									$ipay_category_ratio_disc    = $row_disc->ItemCategoryRatio;
									$ipay_category_amount_disc   = $row_disc->InvoiceOwing;
									$ipay_InvoiceAmount_disc   	 = $row_disc->InvoiceAmount;
									$ipay_item_type_disc       	 = $row_disc->ItemType;
									$ipay_InvoiceNumber       	 = $row_disc->InvoiceNumber;
									
									if($ipay_item_type_disc == 0){ 
										$DiscountAccount    = $this->m_account_journal->get_cat_sales_account('ReceiveDiscount', $ipay_category_id_disc, $Currency_Code); // Potongan Pembelian
										if($Currency_Code == 'IDR'){
											if($DiscountAccount == false) {$this->trans_rollback('preference','Sales Account -> Receive Discount',$Currency_Code);}
										}
										else{
											if($DiscountAccount == false) {$this->trans_rollback('journal', 'Discount Penjualan atau Retur Penjualan',$Currency_Code);}
										}
									}
									else{
										$DiscountAccount    = $this->m_account_journal->get_sys_service_account('SalesRecDiscount', $Currency_Code); // Potongan Pembelian
										if($Currency_Code == 'IDR'){
											if($DiscountAccount == false) {$this->trans_rollback('preference','Expense Account -> Sales Receipt Discount',$Currency_Code);}
										}
										else{
											if($DiscountAccount == false) {$this->trans_rollback('journal','Discount Penjualan atau Retur Penjualan',$Currency_Code);}
										}   
									}
									
									$amount_discount        = $payment_disc * ($ipay_category_ratio_disc / 100);
									if($Currency_Code == 'IDR'){
										$discount_amount     	= $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount;
										$discount_currency   	= $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount / $Bank_Curr_Rate;
									}
									else{
										$discount_amount    	= $Bank_Curr_Code == 'IDR' ? $amount_discount * $Bank_Curr_Rate : $amount_discount * $Bank_Curr_Rate;	
										$discount_currency  	= $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount;
									}
									
									$get_journal_disc = $this->m_sales_receipt->get_journal_recip_empty($DiscountAccount->AccountNumber, $SRecNumber, $ipay_InvoiceNumber);
									if(empty($get_journal_disc->SRecAccountNumber)){
										$journal_disc           = array(
											'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
											'SRecNumber'                => $SRecNumber,
											'SRecDesc'                  => $SRecDesc,
											'SRecAccountNumber'         => $DiscountAccount->AccountNumber,
											'SRecSaldoDebet'            => $discount_amount,
											'SRecSaldoCredit'           => 0,
											'AmountCurrency'            => $discount_currency,
											'SRecSignStatus'            => 0, 
											'ItemCategoryID'            => $item_category_id,
											'SInvNumber' 				=> $ipay_InvoiceNumber,
											'LastUser'                  => $this->session->userdata("username")
										 );
										
										if($discount_amount > 0){
											$this->m_sales_receipt->insert_journal($journal_disc);
										}
									}
									else{
										$discount_amount      	= $discount_amount + $get_journal_disc->SRecSaldoDebet;
										$discount_currency   	= $discount_currency + $get_journal_disc->AmountCurrency;
										
										$journal_discount           = array(
											'SRecSaldoDebet'            => $discount_amount,
											'SRecSaldoCredit'           => 0,
											'AmountCurrency'            => $discount_currency,
										 );

										if($discount_amount > 0){
											$this->m_sales_receipt->update_journal($journal_discount, $SRecNumber, $DiscountAccount->AccountNumber, $ipay_InvoiceNumber);
										}
									}
									
									$total_discount = $discount_amount;
								}                      
							}
							/*=====================End===================================================================*/
							
							/*
								Beban Pembulatan
							*/
							if($Load_Rounding > 0){
								$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
								if($Currency_Code == 'IDR'){
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								else{
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								
								$beban_pembulatan           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccount->AccountNumber,
									'SRecSaldoDebet'            => abs($beban_amount),
									'SRecSaldoCredit'           => 0,
									'AmountCurrency'            => 0,
									'SRecSignStatus'            => 0, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")
								 );
								$this->m_sales_receipt->insert_journal($beban_pembulatan);
							}
							else if($Load_Rounding < 0){
								$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
								if($Currency_Code == 'IDR'){
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								else{
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
							
								$beban_pembulatan           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccount->AccountNumber,
									'SRecSaldoDebet'            => 0,
									'SRecSaldoCredit'           => abs($beban_amount),
									'AmountCurrency'            => 0,
									'SRecSignStatus'            => 1, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")
								 );
								$this->m_sales_receipt->insert_journal($beban_pembulatan);
							}	
							/*========================End==========================*/
							
							
							/*
								Beban pembulatan auto
							*/
							if($invoice_owing == 0){
								$total_hutang_real = $total_hutang;
							}
							else{
								$total_hutang_real = $payment_dp + $payment_disc + $Load_Rounding + $payment_amount;
							}
							
							$total_relize 			  = ($Relized_all_trans * $Bank_Curr_Rate) - ($Relized_all_trans * $invoice_rate); 
							
							$realizegl_value_beban    = $total_relize / $Bank_Curr_Rate ;
							$realized_amount_beban    = $Currency_Code == 'IDR' ? abs($realizegl_value_beban) : abs($realizegl_value_beban) * $Bank_Curr_Rate;
							
							if($total_relize > 0){
								$total_relize_all_kredit = abs($realized_amount_beban);
								$total_relize_all_debet  = 0;
							}
							else{
								$total_relize_all_kredit = 0;
								$total_relize_all_debet  = abs($realized_amount_beban);
							}
							
							$Bank 				= empty($bank_amount) ? 0 : $bank_amount;
							$Disc 				= empty($total_discount) ? 0 : $total_discount;
							$Round 				= empty($Load_Rounding) ? 0 : $Load_Rounding;
							$Relize_Debet 		= empty($total_relize_all_debet) ? 0 : $total_relize_all_debet;
							$Relize_Kredit 		= empty($total_relize_all_kredit) ? 0 : $total_relize_all_kredit;
							$TotalDP_No_Curren 	= empty($total_dp_no_currency) ? 0 : $total_dp_no_currency;
							$TotalDP 			= empty($total_dp) ? 0 : $total_dp;
							$Beban 				= empty($total_hutang_real) ? 0 : $total_hutang_real;
							$selisih_kurs_dp	= doubleval($TotalDP) - doubleval($TotalDP_No_Curren * $invoice_rate);
							
							if($selisih_kurs_dp > 0){
								$RelizeDP_Debet 	= 0;
								$RelizeDP_Kredit 	= abs($selisih_kurs_dp);
							}
							else{
								$RelizeDP_Debet 	= abs($selisih_kurs_dp);
								$RelizeDP_Kredit 	= 0;
							}
							
							$Total_Beban 		= ($Bank + $Disc + $Round + $Relize_Debet + ($RelizeDP_Debet + $TotalDP)) - (($Beban * $invoice_rate) + $RelizeDP_Kredit + $Relize_Kredit);
							
							/*
								Beban Pembulatan Auto
							*/
							if($Total_Beban > 0){
								$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								if($Currency_Code == 'IDR'){
									$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
								}
								else{
									$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
								}
								
								$beban_pembulatan_auto           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccountAuto->AccountNumber,
									'SRecSaldoDebet'            => 0,
									'SRecSaldoCredit'           => abs($beban_amount_auto),
									'AmountCurrency'            => 0,
									'SRecSignStatus'            => 1, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")
								 );
								 $this->m_sales_receipt->insert_journal($beban_pembulatan_auto);
							}
							else if($Total_Beban < 0){
								$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								if($Currency_Code == 'IDR'){
									$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
								}
								else{
									$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
								}
							
								$beban_pembulatan_auto           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccountAuto->AccountNumber,
									'SRecSaldoDebet'            => abs($beban_amount_auto),
									'SRecSaldoCredit'           => 0,
									'AmountCurrency'            => 0,
									'SRecSignStatus'            => 0, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")
								 );
								 
								 $this->m_sales_receipt->insert_journal($beban_pembulatan_auto);
							}
							/*===============End=====================*/
							
							/*
								Insert Journal Payment Realized Account
							*/
							if($total_relize > 0){
								$realizegl_value    = $total_relize / $Bank_Curr_Rate ;                            
								$realized_amount    = $Currency_Code == 'IDR' ? abs($realizegl_value) : abs($realizegl_value) * $Bank_Curr_Rate;
								$realized_currency  = $Bank_Curr_Code == 'IDR' ? 0 : 0;
								
								
								$this->Insert_Journal_Realized(
									date("Y-m-d", strtotime($SRecDate)), $SRecNumber, $SRecDesc, $RealizedAccount->AccountNumber, 0, $realized_amount, $realized_currency, 1, $item_category_id                                 
								);                            
							}                        
							/*=====================End===================================================================*/ 
							
							/*
								Insert Journal Payment Realized Account
							*/
							if($total_relize < 0){
								$realizegl_value    = $total_relize / $Bank_Curr_Rate ;                            
								$realized_amount    = $Currency_Code == 'IDR' ? abs($realizegl_value) : abs($realizegl_value) * $Bank_Curr_Rate;
								$realized_currency  = $Bank_Curr_Code == 'IDR' ? 0 : 0;
								//$realized_currency  = 0;    //abs($realizegl_value);
								
								$this->Insert_Journal_Realized(
									date("Y-m-d", strtotime($SRecDate)), $SRecNumber, $SRecDesc, $RealizedAccount->AccountNumber, $realized_amount, 0, $realized_currency, 0, $item_category_id                                
								);                                                        
							}                        
							/*=====================End===================================================================*/
							
							
						}
						else if(($row->Invoice_Type == 'SO')){
							$data_payment 				= $this->m_sales_receipt->get_receipt($invoice_number, 1, 0);
							$total_ppay_realizedgl  	= 0;
							$ppay_realizedgl        	= 0;
							$advance_value 				= 0;
							$advance_currency 			= 0;
							$total_amount_advance 		= 0;
							
							/*
								Insert Journal Bank Acccount
							*/
							$payment_val 	= doubleval($payment_amount);
							$bank_amount 	= 0; 
							$bank_currency 	= 0; 
							
							if($Currency_Code == 'IDR'){
								$bank_amount    = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;	
								$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val / $Bank_Curr_Rate;
							}
							else{
								$bank_amount    = $Bank_Curr_Code == 'IDR' ? ($payment_currency / $Bank_Curr_Rate) * $Bank_Curr_Rate : $payment_val * $Bank_Curr_Rate;	
								$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_currency / $Bank_Curr_Rate : $payment_val;
							}
							
							$get_journal_receipt = $this->m_sales_receipt->get_journal_recip_empty($BankPayment, $SRecNumber, $invoice_number);
							if(empty($get_journal_receipt->SRecAccountNumber)){
								$journal_bank           = array(
														'SRecDate'                  => $SRecDate,
														'SRecNumber'                => $SRecNumber,
														'SRecDesc'                  => $SRecDesc,
														'SRecAccountNumber'         => $BankPayment,
														'SRecSaldoDebet'            => $bank_amount,
														'SRecSaldoCredit'           => 0,
														'AmountCurrency'            => $bank_currency,
														'SRecSignStatus'            => 0, 
														'ItemCategoryID'            => $item_category_id,
														'SInvNumber' 				=> $invoice_number,
														'LastUser'                  => $this->session->userdata("username")
													 );
	
								$this->m_sales_receipt->insert_journal($journal_bank);
							}
							else{
								$bank_amount      	= $bank_amount + $get_journal_receipt->SRecSaldoDebet;
								$bank_currency   	= $bank_currency + $get_journal_receipt->AmountCurrency;
								
								$journal_bank = array(
									'SRecSaldoDebet' 	=> $bank_amount,
									'SRecSaldoCredit' 	=> 0,
									'AmountCurrency' 	=> $bank_currency
								);
								$this->m_sales_receipt->update_journal($journal_bank, $SRecNumber, $get_journal_receipt->SRecAccountNumber, $invoice_number);
							}
							/*===================End========================================================================*/
							
							/*
								Get invoicepayment new table
							*/						
							foreach($data_payment as $row_payment){
								$ipay_payment_id        = $row_payment->InvoicePaymentID;
								$ipay_category_id       = $row_payment->ItemCategoryID;
								$ipay_category_code     = $row_payment->ItemCategoryCode;                            
								$ipay_category_ratio    = $row_payment->ItemCategoryRatio;
								$ipay_InvoiceAmount   	= $row_payment->InvoiceAmount;
								$ipay_category_amount   = $row_payment->InvoiceOwing;
								$ipay_item_type   		= $row_payment->ItemType;
								$ipay_ItemCategoryRatio = $row_payment->ItemCategoryRatio;
								
								$currency_payable       = $payment_currency * ($ipay_category_ratio / 100);							
								$amount_invoice         = $invoice_copy * ($ipay_category_ratio / 100);
								$amount_advance         = ($payment_amount) * ($ipay_category_ratio / 100);
								$amount_advance_curr    = ($payment_currency) * ($ipay_category_ratio / 100);
								$amount_owing_temp      = ($invoice_owing_temp) * ($ipay_category_ratio / 100);
								
								$amount_rounded       	= $Load_Rounding * ($ipay_category_ratio / 100);
								
								$amount_advance_owing   = ($payment_amount + $Load_Rounding) * ($ipay_category_ratio / 100);
								
								$BankAccount    		= $BankPayment;
								
								if($Currency_Code == 'IDR'){
									$total_amount_advance 	= $amount_advance + $amount_rounded;
								}
								else{
									if($Bank_Curr_Code == 'IDR'){
										$total_amount_advance 	= ($amount_advance_curr / $Bank_Curr_Rate) + $amount_rounded;
									}
									else{
										$total_amount_advance 	= $amount_advance + $amount_rounded;
									}
								}
								
								if($Currency_Code == 'IDR'){
									$inv_curr_amount    = $amount_advance;
									$ppay_curr_amount   = $amount_advance;                                
								}
								else{
									$inv_curr_amount    = $amount_advance * $invoice_rate;
									$ppay_curr_amount   = $amount_advance * $Bank_Curr_Rate;
								}
								
								$ppay_realizedgl        = $ppay_curr_amount - $inv_curr_amount;
								
								/*==========Insert PPayDetail=================================================================*/
								$this->insert_detail($SRecDate,0,NULL,$ipay_ItemCategoryRatio, $Select_DP,
									$ipay_payment_id, $SRecNumber, $invoice_number, $invoice_date, $ipay_InvoiceAmount, $amount_owing_temp, 
									$invoice_rate, $fiscal_rate, $Bank_Curr_Rate, NULL, '0', '0', $amount_advance, $amount_advance, 
									$currency_payable, $inv_curr_amount, $ppay_realizedgl, $amount_rounded, '1', $ipay_category_id, $ipay_category_code, $amount_invoice, $ipay_item_type
								);
								/*======================End====================================================================*/
								if($ipay_item_type == 0){
									$DPAccount  = $this->m_account_journal->get_cat_sales_account('AdvanceSales', $ipay_category_id, $Currency_Code); // Uang Muka Category -> 1-4-03-001-00                            
									if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan Inventory', $Currency_Code);}
								}
								else {
									$DPAccount  = $this->m_account_journal->get_sys_service_account('SalesAdvance', $Currency_Code); // Uang Muka Expense -> 1-4-03-001-00                            
									if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan Expense', $Currency_Code);}
								}
								
								if($Currency_Code == 'IDR'){
									$advance_value     		= $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance;
									$advance_currency   	= $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance / $Bank_Curr_Rate;
								}
								else{
									$advance_value    		= $Bank_Curr_Code == 'IDR' ? $total_amount_advance * $Bank_Curr_Rate : $total_amount_advance * $Bank_Curr_Rate;	
									$advance_currency  		= $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance;
								}
	
								/*
									Insert Journal DP Account Purchase
								*/
								$get_journal_receipt 			= $this->m_sales_receipt->get_journal_recip_empty($DPAccount->AccountNumber, $SRecNumber, $invoice_number);
								
								if(empty($get_journal_receipt->SRecAccountNumber)){
									$journal_dp         = array(
										'SRecDate'                  => $SRecDate,
										'SRecNumber'                => $SRecNumber,
										'SRecDesc'                  => $SRecDesc,
										'SRecAccountNumber'         => $DPAccount->AccountNumber,
										'SRecSaldoDebet'            => 0,
										'SRecSaldoCredit'           => $advance_value,
										'AmountCurrency'            => $advance_currency,
										'SRecSignStatus'            => 0, 
										'SInvNumber' 				=> $invoice_number,
										'ItemCategoryID'            => $item_category_id,
										'LastUser'                  => $this->session->userdata("username")	
									 );
									 
									if($advance_value > 0){
										$this->m_sales_receipt->insert_journal($journal_dp);
									}
								}
								else{
									$advance_value      	= $advance_value + $get_journal_receipt->SRecSaldoCredit;
									$advance_currency   	= $advance_currency + $get_journal_receipt->AmountCurrency;
								
									$journal_dp = array(
										'SRecSaldoDebet' 	=> 0,
										'SRecSaldoCredit' 	=> $advance_value,
										'AmountCurrency' 	=> $advance_currency
									);
									
									if($advance_value > 0){
										$this->m_sales_receipt->update_journal($journal_dp, $SRecNumber, $get_journal_receipt->SRecAccountNumber, $invoice_number);
									}
								}
								/*======================================================================================*/
							}
							
							/*
								RoundingLoad greater than 0 (Beban Pembulatan)
							*/
							if($Load_Rounding > 0){
								$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
								if($Currency_Code == 'IDR'){
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								else{
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
							
								$beban_pembulatan         		= array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccount->AccountNumber,
									'SRecSaldoDebet'            => abs($beban_amount),
									'SRecSaldoCredit'           => 0,
									'AmountCurrency'            => 0,
									'SRecSignStatus'            => 0, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")	
								 );
						
								$this->m_sales_receipt->insert_journal($beban_pembulatan);
							}
							else if($Load_Rounding < 0){
								$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
								if($Currency_Code == 'IDR'){
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								else{
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
							
								$beban_pembulatan         		= array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccount->AccountNumber,
									'SRecSaldoDebet'            => 0,
									'SRecSaldoCredit'           => abs($beban_amount),
									'AmountCurrency'            => 0,
									'SRecSignStatus'            => 1, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")	
								 );
						
								$this->m_sales_receipt->insert_journal($beban_pembulatan);
							}	
						}
					}
				}
			}
			
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$result['status'] 		= FALSE;
				$result['message']   = get_notification_transaksi($this->name, 'insert', 0,$SRecNumber);  
				
				 $result['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
            	$result['number']    = $PPayNumber;
			}
			else {
				$this->db->trans_commit();
				$result['status'] 		= TRUE;
				$result['message']   = get_notification_transaksi($this->name, 'insert', 1,$SRecNumber);
			}
		}
        else{
            $result['status']    = false;
            $result['message']   = get_notification_transaksi($this->name, 'insert', 0,$SRecNumber);            
        }

        echo json_encode($result);
	}
	
	
    //public function insert(){
//		
//		/*====================================================================================*/
//		/*
//			deklar variabel from sales recip dari group
//		*/
//		$DepartmentCode 	= $this->input->post('cbg_department');
//		$CustomerCode 		= $this->input->post('cbg_customer');
//		$SRecDate 			= $this->input->post('txt_sr_date');
//		$bank_code 			= $this->input->post('bank_number');
//		
//		/*=====================================jcos number==========================================*/
//		$SRecNumber  		= $this->m_sales_receipt->create_sr_number($SRecDate, $bank_code);
//		/*==========================================================================================*/
//		
//		$BankCode 			= $this->input->post('cbg_bank');
//		$CurrencyCode 		= $this->input->post('hdn_bank_curr'); //currency code bank
//		$CurrencyCode_Cus 	= $this->input->post('hdn_cust_curr'); //Currency code customer
//		$CurrencyRate 		= $this->input->post('txt_rate'); 
//		
//		$ChequeNumber		= $this->input->post('txt_cheque_no');
//		$ChequeAmount 		= $this->input->post('txt_cheque_amount');
//		$SRecDesc			= $this->input->post('txa_sr_desc');
//		$SInvTotalAmount 	= $this->input->post('hdn_si_total_amount');
//		$SRecTotalOwing 	= $this->input->post('hdn_sr_owing');
//		$SRecTotalDPUsed 	= $this->input->post('hdn_sr_dp_used');
//		$SRecTotalDiscount 	= $this->input->post('hdn_sr_discount');
//		$SRecTotalAmount 	= $this->input->post('txt_total_amount');
//		$SRecAmountCurr 	= $this->input->post('txt_total_amount_copy');
//		$DPPartial 			= $this->input->post('txt_cust_dp_part');
//		$DPTotal 			= $this->input->post('txt_cust_dp');
//		$PPnFiscalStatus 	= $this->input->post('chk_fiscal_payment');
//		$branch_code    	= $this->session->userdata('branch');
//		$detail 			= json_decode($this->input->post('detail'));
//		
//		
//		/*=====================================end================================================*/
//		
//		if(count($detail)>0){
//			$result_insert = 0;
//			$this->db->trans_begin();
//			
//			$get_customer_for_lock_status = $this->m_sales_receipt->get_customer_for_lock_status($CustomerCode);
//			if($get_customer_for_lock_status->LockStatus == 1){
//				$result['status']    = false;
//            	$result['message']   = "Transaksi gagal, customer code sudah di lock silahkan proses transaksi dengan customer ".$get_customer_for_lock_status->CustomerName."";
//				echo json_encode($result);
//				die();
//			}
//			
//			/*=========================================================================================*/
//			/*
//				insert group
//			*/
//			$insert_group = $this->insert_group($CustomerCode, $DepartmentCode, $SRecNumber, $SRecDate, $BankCode, $CurrencyCode, $CurrencyRate, $ChequeNumber, $SRecDate, $ChequeAmount, $SRecDesc, $SInvTotalAmount, $SRecTotalOwing, $SRecTotalDPUsed, $SRecTotalDiscount, $SRecTotalAmount, $SRecAmountCurr, $PPnFiscalStatus);
//			/*========================================end=============================================*/
//			
//			/*=========================================================================================*/
//			/*
//				ambil detail per grid
//			*/
//			
//			foreach($detail as $row){
//				
//				/*========================================================================================*/
//				/*
//					jika status paid yes(tombol chek disebalh kiri pada grid)
//				*/
//				if ($row->Paid == 'Yes') {
//					
//					/*=====================================================================================*/
//					/*
//						deklar variabel dari grid
//					*/
//					$item_categori_id   = $row->ItemCategoryID;
//					$item_category_code = $row->ItemCategoryCode;
//					$srec_disc_datee    = empty($row->ReceiptDiscDate) ? null: date("Y-m-d",strtotime($row->ReceiptDiscDate));
//					
//					$invoice_rate       = $row->InvoiceCurrRate;
//                    $fiscal_rate        = $row->InvoiceFiscalRate;
//                    $invoice_number     = $row->InvoiceNumber;                    
//                    $invoice_amount     = $row->InvoiceAmount;
//                    $invoice_owing      = $row->InvoiceOwing;
//					$invoice_type 		= $row->InvoiceType;
//					$invoice_date       = date("Y-m-d", strtotime($row->InvoiceDate));
//					
//					$Dp_Receipt         = $row->ReceiptTotalDP;		//Receipt Total DP From grid
//                    $receipt_disc       = $row->ReceiptDiscount; 	//Receipt Discount From grid
//                    $receipt_amount     = $row->PaymentAmount; 		//Receipt Amount no currency
//                    $receipt_currency   = $row->PaymentCurrency; 	//Receipt Amount Currecny jika dia bukan IDR
//					$CategoryName   	= $row->ItemCategoryName;
//					$RoundingLoad   	= $row->BebanPembulatan;	//BebanPembulatan from grid
//					$InvoiceAmountCopy 	= $row->InvoiceAmountCopy;
//					$DPStatus 			= $row->DPStatus;
//					$PPnFiscalStatus 	= $row->PPnFiscalStatus;
//					
//					/*=========================end=================================================================*/
//					
//					/*==============================================================================================
//						condition ppn fiscal = -3
//					*/
//					if($item_categori_id == -3){
//						$this->get_ppn_fiscal($PPnFiscalStatus, $CurrencyRate, $SRecDesc, $SRecDate, $BankCode, $CurrencyCode_Cus, $CurrencyCode, $srec_disc_datee, $InvoiceAmountCopy, $receipt_currency, $invoice_owing, $invoice_rate, $fiscal_rate, $DPStatus, $CategoryName, $Dp_Receipt, $invoice_amount, $invoice_number,$receipt_amount, $SRecTotalAmount, $receipt_disc, $RoundingLoad, $invoice_date, $SRecNumber);
//					}
//					else{
//						if($row->InvoiceType == "SO"){
//							/*==============================================================================*/
//							/*
//								this condition for DP down payment
//							*/
//							
//							/*====================================================================================*/
//							/*
//								ceking invoice receipt for jv balance
//								grouping table by no SO for DP, jika invoice receipt > total owing maka tidak bisa di proses artinya pembayaran sudah melebihi batas invoice/receipt
//								Total Owing sudah dikurangin sama jv balance di query
//							*/
//							$get_invoice_recive_distinc = $this->m_sales_receipt->get_invoice_recip_grouping($invoice_number, 1, NULL);
//							foreach($get_invoice_recive_distinc as $row_distinct){
//								if($row_distinct->TotalOwing == 0){
//									$this->db->trans_rollback();
//									$result['status'] 	= FALSE;
//									$result['message']  = msg_confirmation_blok('msg_sales_recip',$this->name, $SRecNumber);
//									echo json_encode($result);
//									die();
//								}
//							}
//							
//							/*=====================================end===============================================*/
//							$this->get_dp_by_sales_order($PPnFiscalStatus, $SRecAmountCurr, $SRecDate, $SRecDesc, $CurrencyRate, $Dp_Receipt, $CategoryName, $DPStatus, $receipt_disc, $srec_disc_datee, $fiscal_rate, $invoice_rate, $invoice_owing, $InvoiceAmountCopy, $invoice_amount, $invoice_date, $invoice_number, $BankCode, $CurrencyCode_Cus, $CurrencyCode, $receipt_amount, $receipt_currency, $SRecAmountCurr, $RoundingLoad, $SRecNumber);
//							/*=============================end==============================================*/
//						}
//						else if($row->InvoiceType == "SI"){
//							/*==============================================================================*/
//							/*
//								this condition for Bank sales receipt data from invoice
//							*/
//							
//							/*===================Get Sordetail DP==========================================*/
//							//if($Dp_Receipt > 0){
//								$sordetail_dp    = $this->m_sales_receipt->get_saldo_detail_dp($CustomerCode);
//								$saldo_dp 		 = $DPTotal;
//								
//								$jurnal_dp 				= 0;
//								$currency_rate_detail 	= 0;
//								$is_edit 				= "";
//								foreach($sordetail_dp as $row_detail_dp){
//									$DPUsed 				= $row_detail_dp->DPUsed;
//									$JVoucherBalance 		= $row_detail_dp->JVoucherBalance; 
//									$SaldoDPBalance 		= $row_detail_dp->SaldoDPBalance;
//									$DPUsed 				= $DPUsed + $JVoucherBalance;
//									
//									if($DPUsed != $SaldoDPBalance){
//										$dp_used_book 			= 0;
//										$saldo_balance_detail 	=  $row_detail_dp->PaymentAmount ;
//										$currency_rate_detail 	=  $row_detail_dp->CurrencyRate;
//										$SOrdDetailDPID 		=  $row_detail_dp->SOrdDetailDPID;
//										$DPUsedBook 			=  $row_detail_dp->DPUsedBook;
//										
//										$SaldoDPBalance 		=  $row_detail_dp->SaldoDPBalance;
//										
//										if($saldo_dp > 0){
//											$saldo_dp = $saldo_dp - ($saldo_balance_detail - $DPUsed);
//											
//											if($saldo_dp < 0){
//												$dp_used_old 	= $DPUsedBook - $DPUsed;
//												$dp_used_book 	= $DPUsedBook + ($saldo_balance_detail - $DPUsed + $saldo_dp - $dp_used_old);
//												//$dp_used_book 	= $saldo_balance_detail + $saldo_dp;
//												$jurnal_dp 		= $jurnal_dp + ($dp_used_book * $currency_rate_detail);
//												$is_edit 		= 1;
//											}
//											else{
//												$dp_used_old 	= $DPUsedBook - $DPUsed;
//												$dp_used_book 	= $saldo_balance_detail - ($DPUsedBook - $dp_used_old);
//												//$dp_used_book 	= $saldo_balance_detail;
//												$jurnal_dp 		= $jurnal_dp + ($dp_used_book * $currency_rate_detail);
//												$is_edit 		= 1;
//											}
//										}
//										
//										$update_sordetail = array(
//											'DPUsedBook' 			=> $dp_used_book,
//											'IsEdit' 				=> $is_edit
//										);
//										$this->m_sales_receipt->update_so_detail_dp_by_customer($update_sordetail, $CustomerCode, $SOrdDetailDPID);
//									}
//								}
//							//}
//							/*========================End===================================================*/
//							
//							$this->get_sales_invoice_from_receipt($jurnal_dp, $invoice_rate, $CurrencyRate, $PPnFiscalStatus, $SRecAmountCurr, $SRecDate, $SRecDesc, $CurrencyRate, $Dp_Receipt, $CategoryName, $DPStatus, $receipt_disc, $srec_disc_datee, $fiscal_rate, $invoice_rate, $invoice_owing, $InvoiceAmountCopy, $invoice_amount, $invoice_date, $invoice_number, $BankCode, $CurrencyCode_Cus, $CurrencyCode, $receipt_amount, $receipt_currency, $SRecAmountCurr, $RoundingLoad, $SRecNumber);
//							/*=============================end==============================================*/
//						}
//					}
//					/*=============================================================================================*/
//				}
//				/*=========================================end paid yes==========================================*/
//			}
//			/*====================================end foreach=====================================================*/
//			
//			/*=============================trans roll back dan trans commit============================/*/
//			if ($this->db->trans_status() === FALSE) {
//				$this->db->trans_rollback();
//				$result['status'] 	= FALSE;
//				$result['message']  = get_notification_transaksi($this->name, 'insert', 0, $SRecNumber);
//				
//				 $result['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
//            	$result['number']    = $SRecNumber;
//			}
//			else {
//				$this->db->trans_commit();
//				$result['status'] 	= TRUE;
//				$result['message']  = get_notification_transaksi($this->name, 'insert', 1, $SRecNumber);
//			}
//			/*==================================end======================================================*/
//		}
//		else{
//			$this->db->trans_rollback();
//			$result['status']    = false;
//            $result['message']   = get_notification_transaksi($this->name, 'insert', 0);
//		}
//		
//		echo json_encode($result);
//    }
	
	/*=======================================================================================*/
	/*
		insert group sales receipt
	*/
	function insert_group($DepartmentCode, $hdn_SRecTotalDPUsed, $hdn_SRecTotalDiscount, $hdn_SRecTotalOwing, $hdn_SInvTotalAmount, $TotalAmount,$AmountCustomerDP, $hdn_total_currency, $BranchCode, $CustomerCode, $SRecDate, $SRecDesc, $SRecNumber, $BankPayment, $Currency_Code, $Bank_Curr_Code, $Bank_Curr_Rate, $ChequeNumber, $ChequeAmount, $ppnfiscal_status){
		$data_sr = array(
			'BranchCode'		=> $BranchCode, 
			'CustomerCode'		=> $CustomerCode, 
			'DepartmentCode'	=> $DepartmentCode, 
			'SRecNumber'		=> $SRecNumber, 
			'SRecDate'			=> $SRecDate, 
			'BankReceipt'		=> $BankPayment,
			'BankCurrCode'      => $Bank_Curr_Code,
			'BankCurrRate'      => $Bank_Curr_Rate,
			'CurrencyCode'      => $Currency_Code,
			'ChequeNumber'		=> $ChequeNumber,
			'SRecDesc'			=> $SRecDesc, 
			'SInvTotalAmount'	=> doubleval($hdn_SInvTotalAmount), 
			'SRecTotalOwing'	=> doubleval($hdn_SRecTotalOwing), 
			'SRecTotalDPUsed'	=> doubleval($hdn_SRecTotalDPUsed), 
			'SRecTotalDiscount'	=> doubleval($hdn_SRecTotalDiscount), 
			'SRecTotalAmount'	=> doubleval($TotalAmount), 
			'SRecAmountCurr' 	=> doubleval($hdn_total_currency),
			'PPnFiscalStatus' 	=> $ppnfiscal_status,
			'TransStatus'		=> 4, 
			'CreatedBy' 		=> $this->session->userdata('username'),
			'CreatedAt' 		=> date('Y-m-d'),
			'LastUser'			=> $this->session->userdata('username')
		);
			
		/*=============================================*/
		/*
			insert receipt group
		*/
		$this->m_sales_receipt->insert($data_sr);
		/*=========================end==================*/
		
		/*===============================================================================*/
		/*
			Update customer for lock status
		*/
		$data_customer  = array (
			'LockStatus'    => 1,
			'LastUser'      => $this->session->userdata("username")
		);

		$this->m_customer->update($data_customer, $CustomerCode);
		/*===========================end=================================================*/
	}
	/*=========================================================================================*/
	
	 public function insert_detail($SRecDate,$Fiscalstatus, $PordetailDP,$ipay_ItemCategoryRatio, $Select_DP, $invoice_payment_id, $ppay_number, $invoice_number, $invoice_date, $invoice_amount,
                                  $invoice_owing, $invoice_rate, $fiscal_rate, $bank_curr_rate, $ppay_disc_date, $payment_disc,
                                  $payment_dp, $payment_amount, $payment_total, $payment_currency, $invoice_currency,  
                                  $payment_real_gl, $payment_rounded, $invoice_type, $item_category_id, $item_category_code, $ipay_category_amount, $ppay_item_type){
        $detail_data  = array(
                            'InvoicePaymentID'      => $invoice_payment_id, 
                            'SrecNumber'            => $ppay_number, 
                            'SInvNumber'            => $invoice_number,
							'SOrdNumber' 			=> $Select_DP,
                            'SInvDate'              => $invoice_date, 
                            'SInvAmount'            => $invoice_amount,
							'SInvAmountTemp'        => $ipay_category_amount,
                            'SRecOwing'             => $invoice_owing,
                            'SInvCurrRate'          => $invoice_rate,
                            'SInvFiscalRate'        => $fiscal_rate,                        
                            'SRecCurrRate'          => $bank_curr_rate,
                            'SRecDiscDate'          => $ppay_disc_date, 
                            'SRecDiscount'          => $payment_disc, 
                            'SRecDPUsed'            => $payment_dp, 
                            'SRecAmount'            => $payment_amount, 
                            'SRecTotalAmnt'         => $payment_total,
							 
                            'SRecCurrency'          => $payment_currency,
                            'SInvCurrency'          => $invoice_currency,
                            'SRecRealizedGL'        => $payment_real_gl,
							
                            'SrecRounded'           => $payment_rounded,                                
                            'SRecPaidStatus'        => 1, 
                            'SRecInvoiceType'       => $invoice_type,
                            'ItemCategoryID'        => $item_category_id, 
                            'ItemCategoryCode'      => $item_category_code, 
							'ItemCategoryRatio'     => $ipay_ItemCategoryRatio, 
							'SRecItemType' 			=> $ppay_item_type,
							'FiscalStatus' 			=> $Fiscalstatus,
							'SRecTime' 				=> date('His'),
							'SRecDate' 				=> $SRecDate,
                            'LastUser'              => $this->session->userdata("username")				
                        );

        $this->m_sales_receipt->insert_detail($detail_data);
    }
	
	
	/*===========================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');

					// 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['app1']       = $this->app1;
					$data['app2']       = $this->app2;
					$TotalSuming 		= 0; 
					// inisialisasi additional parameter
					$id = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
					
					$data['detail'] = $this->m_sales_receipt->get_detail($id);
					
					$result 		= $this->m_sales_receipt->get_saldo_detail_dp_update($data['detail']->CustomerCode);
					foreach($result as $row_detail_dp){
						$get_detail = $this->m_sales_receipt->get_saldo_detail($row_detail_dp->SOrdDetailDPID, $data['detail']->CustomerCode, $id);
						
						if($data['detail']->CurrencyCode == 'IDR'){
							if(empty($get_detail->AmountCurrency)){
								$DPUsed = 0;
							}
							else{
								$DPUsed    = $data['detail']->BankCurrCode == 'IDR' ? $get_detail->AmountCurrency : $get_detail->SRecSaldoDebet;
							}
						}
						else{
							if(empty($get_detail->AmountCurrency)){
								$DPUsed = 0;
							}
							else{
								$DPUsed    = $data['detail']->BankCurrCode == 'IDR' ? $get_detail->AmountCurrency : $get_detail->AmountCurrency;
							}
						}
						
						$Total_Balance = $row_detail_dp->PaymentAmount_SUM + $DPUsed;
						$TotalSuming += $Total_Balance;
					}
					$data['po_detail_dp'] 		= $TotalSuming;
					
					$result_dp_invoice 			= $this->m_sales_receipt->get_sordetail_dp_balance_invoice($data['detail']->CustomerCode);
					if(empty($result_dp_invoice->DownPayment)){
						$data['po_detail_dp_invoice']	= 0;
					}
					else{
						$data['po_detail_dp_invoice']	= $result_dp_invoice->DownPayment;
					}
					
					if(empty($result_dp_invoice->DownPayment_Partial)){
						$data['DownPayment_Partial']	= 0;
					}
					else{
						$data['DownPayment_Partial']	= $result_dp_invoice->DownPayment_Partial;
					}
					
					//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_receipt/v_edit_salesreceipt',$data);
						$this->load->view('v_footer');
					}
					//----------------------end--------------------------------------------------------		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
		
    }
	/*====================end===========================================================*/
	
	public function update(){
		/*================Deklar variabel============================================================*/
        $Customer_Code            = $this->input->post('cbg_customer'); 
        
        $SRecNumber             = $this->input->post('txt_srec_no');
        $SRecDate               = date("Y-m-d", strtotime($this->input->post('txt_srec_date')));
        $SRecDesc               = $this->input->post('txa_description');
        $BankPayment            = $this->input->post('cbg_bank');        
        
        $Currency_Code          = $this->input->post('hdn_cust_curr_code');
        $Bank_Curr_Code         = $this->input->post('hdn_bank_curr_code');
        $Bank_Curr_Rate         = $this->input->post('txt_bank_curr_rate');        
        $ChequeNumber           = $this->input->post('txt_cheque_no');	        
        $ChequeAmount           = $this->input->post('txt_cheque_amount');
		
		$ppnfiscal_status   	= $this->input->post('chk_fiscal_payment');
		$DPTotal 				= $this->input->post('txt_customer_dp_return');
		
		$hdn_total_currency 	= $this->input->post('hdn_total_currency');
		$hdn_SInvTotalAmount 	= $this->input->post('hdn_SInvTotalAmount');
		$hdn_SRecTotalOwing 	= $this->input->post('hdn_SRecTotalOwing');
		$hdn_SRecTotalDPUsed 	= $this->input->post('hdn_SRecTotalDPUsed');
		$hdn_SRecTotalDiscount 	= $this->input->post('hdn_SRecTotalDiscount');
		$txt_total_amount 		= $this->input->post('txt_total_amount');
        
        $total_dp_used          = 0;
        $total_disc_used        = 0;
        $total_amount_paid      = 0;
        $total_currency_paid    = 0;
        $total_ppay_realizedgl  = 0;
		$total_ppay_realizedgl_new 	= 0;
		$total_hutang_beban  	= 0;
		$total_hutang_beban_new = 0;
					
        $total_invoice          = 0;
        $total_owing            = 0;
		$invoice_loop 			= 0;
        
        $detail_post            = $this->input->post('detail');        
        $detail                 = json_decode($detail_post);
		/*=====================End=========================================================================*/
        
        if (count($detail) > 0){   
            $this->db->trans_begin();
            
			/*
				Jika Select dp dirubah
			*/
			if($hdn_SRecTotalDPUsed > 0){
				$DPAccount  		= $this->m_account_journal->get_account_name('Uang Muka Penjualan', $Currency_Code);
				$sordetail_dp_new 	= $this->m_sales_receipt->get_receipt_detail_dp_update($Customer_Code, $DPAccount->AccountNumber);
				
				foreach($sordetail_dp_new as $row_dp_suspend){
					$DPUsed 		 		=  $row_dp_suspend->DPUsed;
					$SOrdDetailDPID 		=  $row_dp_suspend->SOrdDetailDPID;
					$SOrdNumber_DP 			=  $row_dp_suspend->SOrdNumber; 
					$total_pordetail 		=  $row_dp_suspend->AmountCurrency - $DPUsed;
					$total_pordetail_new 	=  $row_dp_suspend->SRecSaldoDebet - $DPUsed;
					
					if($Currency_Code == 'IDR'){
						$dp_total_amount    = $Bank_Curr_Code == 'IDR' ? $total_pordetail : $total_pordetail_new;
					}
					else{
						$dp_total_amount    = $Bank_Curr_Code == 'IDR' ? $total_pordetail : $total_pordetail;
					}
					
					$update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => abs($dp_total_amount));
					$this->m_sales_receipt->update_so_detail_dp_for_sr($update_sordstatus, $Customer_Code, $SOrdDetailDPID);
				}
			}
			
			/*====================End=====================================================================*/
				
			/*
				Delete Journal Transaction.
			*/
            $this->m_sales_receipt->delete_journal($SRecNumber);
			/*===============End=======================================*/
			
            foreach($detail as $row){
                $invoice_number         = $row->Invoice_Number;
                
                if ($row->Paid == 'Yes') {
                    $ppay_detail_id     	= $row->SRecDetailID;
                    $item_category_id   	= $row->ItemCategoryID;
                    $invoice_rate       	= $row->InvoiceCurrRate;
                    $invoice_amount    	 	= $row->Invoice_Amount;
                    $invoice_owing      	= $row->Invoice_Owing;
					$invoice_temp_owing     = $row->InvoiceOwingHiddenNew;
					
                    $invoice_amount_copy	= $row->InvoiceAmountCopy;
					$InvoiceOwingHidden		= $row->InvoiceOwingHidden;
					
					$total_hutang 			= $InvoiceOwingHidden - $invoice_temp_owing;
					$Invoice_Number			= trim($row->Invoice_Number);
					
                    $payment_dp         	= $row->Receipt_DP;
                    $payment_disc       	= $row->Receipt_Discount;
                    $payment_amount     	= $row->Receipt_Amount;
                    $payment_currency   	= $row->Receipt_Currency;
					$Load_Rounding   		= $row->Load_Rounding;
					$fiscal_rate 			= $row->InvoiceFiscalRate; 
					$Select_DP 				= $row->Select_DP;
					$Relized_all_trans 		= $payment_disc + $payment_amount;
					 
                    $invoice_currency   	= $Currency_Code == 'IDR' ? $payment_amount : $payment_amount * $invoice_rate;
                    $payment_realizedgl 	= ($Bank_Curr_Rate == 'IDR' ? $payment_currency : $payment_currency * $Bank_Curr_Rate) - $invoice_currency;
					$invoice_date     		= empty($row->Invoice_Date) ? null: date("Y-m-d",strtotime($row->Invoice_Date)); 
					$Advanced 				= '';
					$total_dp 				= 0;
					$relize_dp 				= 0;
					$total_relize 			= 0;
					
					$invoice_loop++; 
					
                    $total_invoice      += $invoice_amount;
                    $total_owing        += $invoice_owing;
                    //-----------------------------------------------------------------------------------------------------------//
                    
                    //Insert Journal Transaction
					if($item_category_id == -3){
						$payment_total          = $payment_amount + $Load_Rounding;
                        //$payment_rounded        = ($payment_currency / $Bank_Curr_Rate) - $payment_amount;
                        
                        /*
							Update ppaydetail
						*/
                        $this->update_detail(
                            $Select_DP, $ppay_detail_id, $invoice_temp_owing, $Bank_Curr_Rate, NULL, 0, 0, $payment_amount, 
                            $payment_total, $payment_currency, $invoice_currency, $payment_realizedgl, $Load_Rounding
                        );
                        /*===============End===================================================================================*/
                        		
                        $BankAccount        = $BankPayment;
						/*
							Insert Journal Bank Acccount
						*/
								
						$bank_amount    = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;		
						$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_currency;
						
						$journal_bank = array(
											'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
											'SRecNumber'                => $SRecNumber,
											'SRecDesc'                  => $SRecDesc,
											'SRecAccountNumber'         => $BankAccount,
											'SRecSaldoDebet'            => $bank_amount,
											'SRecSaldoCredit'           => 0,
											'AmountCurrency'            => $bank_currency,
											'SRecSignStatus'            => 0, 
											'ItemCategoryID'            => $item_category_id,
											'SInvNumber' 				=> $Invoice_Number,
											'LastUser'                  => $this->session->userdata("username")
										 );
				
						$this->m_sales_receipt->insert_journal($journal_bank);
						/*=====================End=============================================================================*/
						
						/*
							Insert Journal Hutang PPn Fiscal
						*/
						$PPnFiscalAccount   = $this->m_account_journal->get_account_name('Piutang PPn Fiscal'); 
						if($PPnFiscalAccount == false) {$this->trans_rollback('journal','Sales Piutang PPn Fiscal, Taxable', $Currency_Code);}
						
						$fiscal_value    	= $Bank_Curr_Code == 'IDR' ? $total_hutang : $total_hutang;	
						$fiscal_currency  	= $Bank_Curr_Code == 'IDR' ? $total_hutang : $total_hutang / $Bank_Curr_Rate;
						$fiscal_realize    	= $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;
						
						$journal_fiscal     = array(
												'SRecDate'              => date("Y-m-d", strtotime($SRecDate)),
												'SRecNumber'            => $SRecNumber,
												'SRecDesc'              => $SRecDesc,
												'SRecAccountNumber'     => $PPnFiscalAccount->AccountNumber,
												'SRecSaldoDebet'        => 0,
												'SRecSaldoCredit'       => $fiscal_value,
												'AmountCurrency'        => $fiscal_currency,
												'SRecSignStatus'        => 1, 
												'ItemCategoryID'        => $item_category_id,
												'SInvNumber' 			=> $Invoice_Number,
												'LastUser'              => $this->session->userdata("username")	
											 );
				
						$this->m_sales_receipt->insert_journal($journal_fiscal);
						/*=====================End=================================================================*/         
                        
						/*
							Beban Pembulatan Auto
						*/
						$Total_Beban 		= ($payment_amount + $Load_Rounding) - ($total_hutang);
						if($Total_Beban > 0){
							$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
							if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
							
							if($Currency_Code == 'IDR'){
								$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
							else{
								$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
							
							$beban_pembulatan_auto           = array(
								'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
								'SRecNumber'                => $SRecNumber,
								'SRecDesc'                  => $SRecDesc,
								'SRecAccountNumber'         => $BebanAccountAuto->AccountNumber,
								'SRecSaldoDebet'            => 0,
								'SRecSaldoCredit'           => abs($beban_amount_auto),
								'AmountCurrency'            => 0,
								'SRecSignStatus'            => 1, 
								'ItemCategoryID'            => $item_category_id,
								'SInvNumber' 				=> $Invoice_Number,
								'LastUser'                  => $this->session->userdata("username")
							 );
							 $this->m_sales_receipt->insert_journal($beban_pembulatan_auto);
						}
						else if($Total_Beban < 0){
							$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
							if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
							
							if($Currency_Code == 'IDR'){
								$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
							else{
								$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
						
							$beban_pembulatan_auto           = array(
								'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
								'SRecNumber'                => $SRecNumber,
								'SRecDesc'                  => $SRecDesc,
								'SRecAccountNumber'         => $BebanAccountAuto->AccountNumber,
								'SRecSaldoDebet'            => abs($beban_amount_auto),
								'SRecSaldoCredit'           => 0,
								'AmountCurrency'            => 0,
								'SRecSignStatus'            => 0, 
								'ItemCategoryID'            => $item_category_id,
								'SInvNumber' 				=> $Invoice_Number,
								'LastUser'                  => $this->session->userdata("username")
							 );
							 
							 $this->m_sales_receipt->insert_journal($beban_pembulatan_auto);
						}
						/*===============End=====================*/
						
						/*
							Beban Pembulatan
						*/
						if($Load_Rounding > 0){
							$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
							if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
							
							$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
							if($Currency_Code == 'IDR'){
								$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
							}
							else{
								$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
							}
							
							$beban_pembulatan         		= array(
								'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
								'SRecNumber'                => $SRecNumber,
								'SRecDesc'                  => $SRecDesc,
								'SRecAccountNumber'         => $BebanAccount->AccountNumber,
								'SRecSaldoDebet'            => abs($beban_amount),
								'SRecSaldoCredit'           => 0,
								'AmountCurrency'            => 0,
								'SRecSignStatus'            => 0, 
								'ItemCategoryID'            => $item_category_id,
								'LastUser'                  => $this->session->userdata("username")	
							 );
					
							$this->m_sales_receipt->insert_journal($beban_pembulatan);
						}
						else if($Load_Rounding < 0){
							$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
							if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
							
							$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
							if($Currency_Code == 'IDR'){
								$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
							}
							else{
								$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
							}
							
							$beban_pembulatan         		= array(
								'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
								'SRecNumber'                => $SRecNumber,
								'SRecDesc'                  => $SRecDesc,
								'SRecAccountNumber'         => $BebanAccount->AccountNumber,
								'SRecSaldoDebet'            => 0,
								'SRecSaldoCredit'           => abs($beban_amount),
								'AmountCurrency'            => 0,
								'SRecSignStatus'            => 1, 
								'ItemCategoryID'            => $item_category_id,
								'LastUser'                  => $this->session->userdata("username")	
							 );
					
							$this->m_sales_receipt->insert_journal($beban_pembulatan);
						}	
						/*========================End==========================*/
                        $total_amount_paid      += $payment_amount;
                        $total_currency_paid    += $payment_currency;  
					}
					else{
						$RealizedAccount  = $this->m_account_journal->get_sys_sales_account('RealizedGainedLoss', $Currency_Code);                     
                    	if($RealizedAccount == false) {$this->trans_rollback('journal','Realized G/L, Purchase', ' ');}  
					
						if(($row->Invoice_Type == 'SI') && ($item_category_id != -3)){
							//PI and not PPn Fiscal
							$curr_account_no        = '';
							$CategoryIDDisc         = array();
							$CategoryIDCode         = array();
							$CategoryType 			= array();
							
							$payable_value          	= 0;
							$total_loop             	= 0;
							$invoice_number_loop 		= "";
							$payable_amount 			= 0;
							$payable_currency 			= 0;
							$ppay_beban_pembulatan_auto = 0;
							
							/*
								Get tabel invoice payment
							*/
							$data_ppay_detail   = $this->m_sales_receipt->get_receipt_detail($invoice_number, $SRecNumber);
	
							foreach($data_ppay_detail as $row_ppay){
								$total_loop++;
								$payament_ratio         = $this->m_sales_receipt->get_receipt_by_id($row_ppay->InvoicePaymentID);
								$ipay_category_ratio    = $payament_ratio[0]->ItemCategoryRatio;
								$ipay_ItemType    		= $payament_ratio[0]->ItemType;
								
								$ppay_detail_id         = $row_ppay->SRecDetailID;
								$ppay_category_id       = $row_ppay->ItemCategoryID;
								$ppay_category_code     = $row_ppay->ItemCategoryCode;
								$ppay_ItemCategoryRatio = $row_ppay->ItemCategoryRatio;
								$ppay_PInvCurrRate 		= $row_ppay->SInvCurrRate;
								
								$amount_invoice         = $invoice_amount_copy * ($ppay_ItemCategoryRatio / 100);
								$amount_owing_real      = $invoice_owing * ($ppay_ItemCategoryRatio / 100);
								$amount_owing_temp      = $invoice_temp_owing * ($ppay_ItemCategoryRatio / 100);
								
								$amount_owing_copy    	= $total_hutang * ($ppay_ItemCategoryRatio / 100);
								
								$amount_dpused          = $payment_dp * ($ppay_ItemCategoryRatio / 100);
								$amount_discount        = $payment_disc * ($ppay_ItemCategoryRatio / 100);
								$amount_payable         = $payment_amount * ($ppay_ItemCategoryRatio / 100);
								$currency_payable       = $payment_currency * ($ppay_ItemCategoryRatio / 100);
								
								$amount_rounded       	= $Load_Rounding * ($ppay_ItemCategoryRatio / 100);
								
								
								if($invoice_owing == 0){
									$amount_total_journal   = $amount_owing_copy;
								}
								else{
									$amount_total_journal   = $amount_dpused + $amount_discount + $amount_rounded + $amount_payable;
								}
								
								if($ipay_ItemType == 0){
									$SalesAccount    = $this->m_account_journal->get_cat_sales_account('SRAccountReceivable', $ppay_category_id, $Currency_Code);
									if($Currency_Code == 'IDR'){
										if($SalesAccount == false) {$this->trans_rollback('preference','Sales Account -> Account Receivable', $Currency_Code);}
									}
									else{
										if($SalesAccount == false) {$this->trans_rollback('journal','Piutang Dagang', $Currency_Code);}
									}
									$Advanced = 'AdvanceSales';                          
								}
								else{
									$SalesAccount    = $this->m_account_journal->get_sys_service_account('SalesUnbilled', $Currency_Code);   
									if($Currency_Code == 'IDR'){
										if($SalesAccount == false) {$this->trans_rollback('preference','Expense Account -> Sales Unbilled (Owing)', $Currency_Code);}
									}
									else{
										if($SalesAccount == false) {$this->trans_rollback('journal','Piutang Expense', $Currency_Code);}
									}   
									
									$Advanced = 'SalesAdvance';                        
								}
								
								if($Currency_Code == 'IDR'){
									$amount_total           = $amount_dpused + $amount_discount + $amount_payable;
									$amount_total_selisih   = $amount_discount + $amount_payable;
								}
								else{
									if($Bank_Curr_Code == 'IDR'){
										$amount_total           = $amount_dpused + $amount_discount + ($currency_payable / $Bank_Curr_Rate);
										$amount_total_selisih   = $amount_discount + ($currency_payable / $Bank_Curr_Rate);
									}
									else{
										$amount_total           = $amount_dpused + $amount_discount + $amount_payable;
										$amount_total_selisih   = $amount_discount + $amount_payable;
									}
								}
								
								if($Currency_Code == 'IDR'){
									$inv_cat_curr_amount    = $amount_total;
									$pay_cat_curr_amount    = $amount_total;                           
								}
								else{
									$inv_cat_curr_amount    = $amount_total_selisih * $invoice_rate;
									$pay_cat_curr_amount    = $amount_total_selisih * $Bank_Curr_Rate;
								}
								$ppay_cat_realizedgl    	= $pay_cat_curr_amount - $inv_cat_curr_amount;
								//$new_invoice_owing      = $amount_invoice - ($amount_total + $amount_rounded);
								
								if($total_loop == 1){$curr_account_no = $SalesAccount->AccountNumber;}
								
								if($payment_disc > 0){
									@$CategoryIDDisc[$ppay_category_id]     = $amount_discount;
									@$CategoryIDCode[$ppay_category_id]     = $ppay_category_code;
									@$CategoryType[$ppay_category_id]     	= $ipay_ItemType;
								}                                                       
								
								/*
									Update ppaydetail
								*/
								$this->update_detail(
									$Select_DP, $ppay_detail_id, $amount_owing_temp, $Bank_Curr_Rate, $invoice_date, $amount_discount, $amount_dpused, 
									$amount_payable, $amount_total, $currency_payable, $inv_cat_curr_amount, $ppay_cat_realizedgl, $amount_rounded
								);                            
								/*=====================End===================================================================*/
								
								if($Currency_Code == 'IDR'){
									$payable_amount     = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal;
									$payable_currency   = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal / $Bank_Curr_Rate;
								}
								else{
									$payable_amount    = $Bank_Curr_Code == 'IDR' ? $amount_total_journal * $ppay_PInvCurrRate : $amount_total_journal * $ppay_PInvCurrRate;	
									$payable_currency  = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal;
								}
								
								$get_journal_receipt = $this->m_sales_receipt->get_journal_recip_empty($SalesAccount->AccountNumber, $SRecNumber, $Invoice_Number);
								if(empty($get_journal_receipt->SRecAccountNumber)){
									$journal_reciv           = array(
										'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
										'SRecNumber'                => $SRecNumber,
										'SRecDesc'                  => $SRecDesc,
										'SRecAccountNumber'         => $SalesAccount->AccountNumber,
										'SRecSaldoDebet'            => 0,
										'SRecSaldoCredit'           => $payable_amount,
										'AmountCurrency'            => $payable_currency,
										'SRecSignStatus'            => 1, 
										'ItemCategoryID'            => $ppay_category_code,
										'SInvNumber' 				=> $Invoice_Number,
										'LastUser'                  => $this->session->userdata("username")
									 );
						
									$this->m_sales_receipt->insert_journal($journal_reciv);
								}
								else{
									$payable_amount      	= $payable_amount + $get_journal_receipt->SRecSaldoCredit;
									$payable_currency     = $payable_currency + $get_journal_receipt->AmountCurrency;
									
									$journal_reciv           = array(
										'SRecSaldoDebet'            => 0,
										'SRecSaldoCredit'           => $payable_amount,
										'AmountCurrency'            => $payable_currency
									 );
						
									$this->m_sales_receipt->update_journal($journal_reciv, $SRecNumber, $SalesAccount->AccountNumber, $Invoice_Number);
								}
							}
							/*=============================END===========================================================*/
							//echo $total_beban_auto;
							/*
								Journal Bank Payment - Invoice Payment
							*/
							$payment_val 	= doubleval($payment_amount);
							$bank_amount 	= 0; 
							$bank_currency 	= 0; 
							
							if($payment_val > 0){
								if($Currency_Code == 'IDR'){
									$bank_amount    = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;	
									$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val / $Bank_Curr_Rate;
								}
								else{
									$bank_amount    = $Bank_Curr_Code == 'IDR' ? ($payment_currency / $Bank_Curr_Rate) * $Bank_Curr_Rate : $payment_val * $Bank_Curr_Rate;	
									$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_currency / $Bank_Curr_Rate : $payment_val;
								}
								
								$journal_bank           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BankPayment,
									'SRecSaldoDebet'            => $bank_amount,
									'SRecSaldoCredit'           => 0,
									'AmountCurrency'            => $bank_currency,
									'SRecSignStatus'            => 0, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $Invoice_Number,
									'LastUser'                  => $this->session->userdata("username")
								 );
	
								$this->m_sales_receipt->insert_journal($journal_bank);
	
								$total_amount_paid      += $payment_amount;
								$total_currency_paid    += $payment_currency;                                
							}
							/*======================================================================================*/
							
							/*
								Journal Advance Purchase - Uang Muka Pembelian
							*/
							$total_dp 					= 0;
							$total_dp_no_currency 		= 0;
								
							if($payment_dp > 0) {
								/*
									rumus sordetail untuk save dan edit
								*/
								$sordetail_dp    			= $this->m_sales_receipt->get_saldo_detail_dp($Customer_Code, $Select_DP, 1);
								$saldo_dp 					= $payment_dp;
								$saldo_dp_new 				= $payment_dp;
								
								$jurnal_dp 					= 0;
								$jurnal_dp_currency 		= 0;
								$jurnal_dp_no_currency 		= 0;
								$inv_dp_selisih_kurs 		= 0;
								
								$currency_rate_detail 		= 0;
								$is_edit 					= "";
								$PaymentBefore 				= 0;
								$PaymentBefore_Sum 			= 0;
								$PaymentPlus				= 0;
								$PaymentPlus_Sum 			= 0;
																
								foreach($sordetail_dp as $row_detail_dp){
									
									$DPUsed 				=  $row_detail_dp->DPUsed;
									$SaldoDPBalance 		=  $row_detail_dp->SaldoDPBalance;
									$JVoucherBalance 		=  $row_detail_dp->JVoucherBalance;
									$DPUsed 				=  $DPUsed + $JVoucherBalance;
									$currency_rate_detail 	=  $row_detail_dp->CurrencyRate;
									
									if($DPUsed != $SaldoDPBalance){
										$dp_used_book 			= 0;
										$saldo_balance_detail 	=  $row_detail_dp->PaymentAmount;
										
										//$DPUsedBook 			=  $row_detail_dp->DPUsedBook;
										$SOrdDetailDPID 		=  $row_detail_dp->SOrdDetailDPID;
										$SaldoDPBalance 		=  $row_detail_dp->SaldoDPBalance;
										
										if($saldo_dp > 0){
											$saldo_dp 			= doubleval($saldo_dp_new - ($PaymentPlus_Sum + $saldo_balance_detail));
											if($saldo_dp < 0){
												
												$dp_used_old 	= $DPUsed;
												$dp_used_book 	= doubleval($DPUsed + ($saldo_dp_new - $PaymentBefore_Sum));
												
												$jurnal_dp 				= (doubleval(($saldo_dp_new - $PaymentBefore_Sum) * $currency_rate_detail));
												$jurnal_dp_currency 	= (doubleval($saldo_dp_new - $PaymentBefore_Sum / $currency_rate_detail));
												$jurnal_dp_no_currency 	= (doubleval($saldo_dp_new - $PaymentBefore_Sum));
												$total_dp 				+= $jurnal_dp;
												$total_dp_no_currency 	+= $jurnal_dp_no_currency;
												
												$update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => $dp_used_book);
												$this->m_sales_receipt->update_so_detail_dp_by_customer($update_sordstatus, $Customer_Code, $SOrdDetailDPID, $Select_DP);
												
												$DPAccount  = $this->m_account_journal->get_account_name('Uang Muka Penjualan', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
												if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan', $Currency_Code);}
												
												if($Currency_Code == 'IDR'){
													$dp_currency   	= $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_currency / $Bank_Curr_Rate;
												}
												else{
													$dp_currency  	= $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_no_currency;
												}
												
												$journal_dp           = array(
													'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
													'SRecNumber'                => $SRecNumber,
													'SRecDesc'                  => $SRecDesc,
													'SRecAccountNumber'         => $DPAccount->AccountNumber,
													'SRecSaldoDebet'            => $jurnal_dp,
													'SRecSaldoCredit'           => 0,
													'AmountCurrency'            => $dp_currency,
													'SRecSignStatus'            => 1, 
													'ItemCategoryID'            => $item_category_id,
													'SInvNumber' 				=> $Invoice_Number,
													'SOrdDetailDPID' 			=> $row_detail_dp->SOrdDetailDPID,
													'LastUser'                  => $this->session->userdata("username")
												);
										
												if($jurnal_dp > 0){
													$this->m_sales_receipt->insert_journal($journal_dp);
												}
												
												if($Currency_Code != 'IDR'){
													$inv_dp_selisih_kurs	= doubleval($jurnal_dp) - doubleval($jurnal_dp_no_currency * $invoice_rate);
													if($inv_dp_selisih_kurs > 0){
														$RealizedAccount  	 	= $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);                     
														if($RealizedAccount == false) {$this->trans_rollback('journal','Realized, Purchase',$Currency_Code);}
											
														$realized_amount    = abs($inv_dp_selisih_kurs);
														$realized_currency  = $Currency_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;
														
														$journal_RealizedAccount           = array(
															'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
															'SRecNumber'                => $SRecNumber,
															'SRecDesc'                  => $SRecDesc,
															'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
															'SRecSaldoDebet'            => 0,
															'SRecSaldoCredit'           => $realized_amount,
															'AmountCurrency'            => 0,
															'SRecSignStatus'            => 1, 
															'ItemCategoryID'            => $item_category_id,
															'SInvNumber' 				=> $Invoice_Number,
															'LastUser'                  => $this->session->userdata("username")
														);
														
														$this->m_sales_receipt->insert_journal($journal_RealizedAccount);
													} 
													else if($inv_dp_selisih_kurs < 0){
														$RealizedAccount  	 	= $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);                     
														if($RealizedAccount == false) {$this->trans_rollback('journal','Realized, Purchase',$Currency_Code);}
											
														$realized_amount    = abs($inv_dp_selisih_kurs);
														$realized_currency  = $Currency_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;
														
														$journal_RealizedAccount           = array(
															'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
															'SRecNumber'                => $SRecNumber,
															'SRecDesc'                  => $SRecDesc,
															'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
															'SRecSaldoDebet'            => $realized_amount,
															'SRecSaldoCredit'           => 0,
															'AmountCurrency'            => 0,
															'SRecSignStatus'            => 0, 
															'ItemCategoryID'            => $item_category_id,
															'SInvNumber' 				=> $Invoice_Number,
															'LastUser'                  => $this->session->userdata("username")
														);
														
														$this->m_sales_receipt->insert_journal($journal_RealizedAccount);
													}
												}
											}
											else{
												$PaidStatus 	= $DPUsed;
												$dp_used_book 	= ($saldo_balance_detail - $DPUsed) + $PaidStatus;
												
												$jurnal_dp 				= (doubleval($saldo_balance_detail - $DPUsed) * doubleval($currency_rate_detail));
												$jurnal_dp_currency 	= (doubleval($saldo_balance_detail - $DPUsed) / doubleval($currency_rate_detail));
												$jurnal_dp_no_currency 	= (doubleval($saldo_balance_detail - $DPUsed));
												$total_dp 				+= $jurnal_dp;
												$total_dp_no_currency 	+= $jurnal_dp_no_currency;
												
												$update_sordstatus = array('SOrdStatus' => 1,'DPUsed' => $dp_used_book);
												$this->m_sales_receipt->update_so_detail_dp_by_customer($update_sordstatus, $Customer_Code, $SOrdDetailDPID, $Select_DP);
												$PaymentBefore 		=  doubleval($saldo_balance_detail - $DPUsed);
												$PaymentPlus 		=  doubleval($saldo_balance_detail + $DPUsed);
												$PaymentBefore_Sum 	+= $PaymentBefore;
												$PaymentPlus_Sum 	+= $PaymentPlus;
												
												$DPAccount  = $this->m_account_journal->get_account_name('Uang Muka Penjualan', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
												if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan', $Currency_Code);}
												
												if($Currency_Code == 'IDR'){
													$dp_currency   	= $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_currency / $Bank_Curr_Rate;
												}
												else{
													$dp_currency  	= $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_no_currency;
												}
												
												$journal_dp           = array(
													'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
													'SRecNumber'                => $SRecNumber,
													'SRecDesc'                  => $SRecDesc,
													'SRecAccountNumber'         => $DPAccount->AccountNumber,
													'SRecSaldoDebet'            => $jurnal_dp,
													'SRecSaldoCredit'           => 0,
													'AmountCurrency'            => $dp_currency,
													'SRecSignStatus'            => 1, 
													'ItemCategoryID'            => $item_category_id,
													'SInvNumber' 				=> $Invoice_Number,
													'SOrdDetailDPID' 			=> $row_detail_dp->SOrdDetailDPID,
													'LastUser'                  => $this->session->userdata("username")
												);
											
												if($jurnal_dp > 0){
													$this->m_sales_receipt->insert_journal($journal_dp);
												}
												
												if($Currency_Code != 'IDR'){
													$inv_dp_selisih_kurs	= doubleval($jurnal_dp) - doubleval($jurnal_dp_no_currency * $invoice_rate);
													if($inv_dp_selisih_kurs > 0){
														$RealizedAccount  	 	= $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);                     
														if($RealizedAccount == false) {$this->trans_rollback('journal','Realized, Purchase',$Currency_Code);}
											
														$realized_amount    = abs($inv_dp_selisih_kurs);
														$realized_currency  = $Currency_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;
														
														$journal_RealizedAccount           = array(
															'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
															'SRecNumber'                => $SRecNumber,
															'SRecDesc'                  => $SRecDesc,
															'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
															'SRecSaldoDebet'            => 0,
															'SRecSaldoCredit'           => $realized_amount,
															'AmountCurrency'            => 0,
															'SRecSignStatus'            => 1, 
															'ItemCategoryID'            => $item_category_id,
															'SInvNumber' 				=> $Invoice_Number,
															'LastUser'                  => $this->session->userdata("username")
														);
														
														$this->m_sales_receipt->insert_journal($journal_RealizedAccount);
													} 
													else if($inv_dp_selisih_kurs < 0){
														$RealizedAccount  	 	= $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);                     
														if($RealizedAccount == false) {$this->trans_rollback('journal','Realized, Purchase',$Currency_Code);}
											
														$realized_amount    = abs($inv_dp_selisih_kurs);
														$realized_currency  = $Currency_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;
														
														$journal_RealizedAccount           = array(
															'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
															'SRecNumber'                => $SRecNumber,
															'SRecDesc'                  => $SRecDesc,
															'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
															'SRecSaldoDebet'            => $realized_amount,
															'SRecSaldoCredit'           => 0,
															'AmountCurrency'            => 0,
															'SRecSignStatus'            => 0, 
															'ItemCategoryID'            => $item_category_id,
															'SInvNumber' 				=> $Invoice_Number,
															'LastUser'                  => $this->session->userdata("username")
														);
														
														$this->m_sales_receipt->insert_journal($journal_RealizedAccount);
													}
												}
											}
										}
										
										$update_isedit = array(
											'IsEdit' 				=> 1
										);
										$this->m_sales_receipt->update_so_detail_dp_by_customer($update_isedit, $Customer_Code, $SOrdDetailDPID, $Select_DP);
									}								}
								/*======================End================================================================================*/
							}
							/*=====================End===================================================================*/ 
							
							/*
								Journal Discount Invoice - Potongan Pembelian  
							*/    
							$total_discount      	= 0;                          
							if($payment_disc > 0){
								$total_loop         	= 0;
								$curr_account_no    	= '';
	
								$discount_amount      	= 0;
								$discount_currency   	= 0;
								$invoice_loop_disc 		= "";
								
								foreach($data_ppay_detail as $row_disc){
									$payament_ratio_disc    = $this->m_sales_receipt->get_receipt_by_id($row_disc->InvoicePaymentID);
									$ipay_category_ratio    = $payament_ratio_disc[0]->ItemCategoryRatio;
									$ipay_ItemType    		= $payament_ratio_disc[0]->ItemType;
									$ipay_InvoiceNumber    	= $payament_ratio_disc[0]->InvoiceNumber;
								
									$ppay_detail_id_disc         = $row_disc->SRecDetailID;
									$ppay_category_id_disc       = $row_disc->ItemCategoryID;
									$ppay_category_code_disc     = $row_disc->ItemCategoryCode;
									
									if($ipay_ItemType == 0){ 
										$DiscountAccount    = $this->m_account_journal->get_cat_sales_account('ReceiveDiscount', $ppay_category_id_disc, $Currency_Code); // Potongan Pembelian
										if($Currency_Code == 'IDR'){
											if($DiscountAccount == false) {$this->trans_rollback('preference','Sales Account -> Receive Discount',$Currency_Code);}
										}
										else{
											if($DiscountAccount == false) {$this->trans_rollback('journal','Discount Penjualan atau Retur Penjualan',$Currency_Code);}
										}
									}
									else{
										$DiscountAccount    = $this->m_account_journal->get_sys_service_account('SalesRecDiscount', $Currency_Code); // Potongan Pembelian
										if($Currency_Code == 'IDR'){
											if($DiscountAccount == false) {$this->trans_rollback('preference','Expense Account -> Sales Receipt Discount',$Currency_Code);}
										}
										else{
											if($DiscountAccount == false) {$this->trans_rollback('journal','Discount Penjualan atau Retur Penjualan',$Currency_Code);}
										}   
									}
									
									$amount_discount        = $payment_disc * ($ipay_category_ratio / 100);
									
									if($Currency_Code == 'IDR'){
										$discount_amount     	= $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount;
										$discount_currency   	= $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount / $Bank_Curr_Rate;
									}
									else{
										$discount_amount    	= $Bank_Curr_Code == 'IDR' ? $amount_discount * $Bank_Curr_Rate : $amount_discount * $Bank_Curr_Rate;	
										$discount_currency  	= $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount;
									}
									
									$get_journal_disc = $this->m_sales_receipt->get_journal_recip_empty($DiscountAccount->AccountNumber, $SRecNumber, $Invoice_Number);
									if(empty($get_journal_disc->SRecAccountNumber)){
										$journal_disc           = array(
											'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
											'SRecNumber'                => $SRecNumber,
											'SRecDesc'                  => $SRecDesc,
											'SRecAccountNumber'         => $DiscountAccount->AccountNumber,
											'SRecSaldoDebet'            => $discount_amount,
											'SRecSaldoCredit'           => 0,
											'AmountCurrency'            => $discount_currency,
											'SRecSignStatus'            => 0, 
											'ItemCategoryID'            => $item_category_id,
											'SInvNumber' 				=> $Invoice_Number,
											'LastUser'                  => $this->session->userdata("username")
										 );
										
										if($discount_amount > 0){
											$this->m_sales_receipt->insert_journal($journal_disc);
										}
									}
									else{
										$discount_amount      	= $discount_amount + $get_journal_disc->SRecSaldoDebet;
										$discount_currency   	= $discount_currency + $get_journal_disc->AmountCurrency;
										
										$journal_discount           = array(
											'SRecSaldoDebet'            => $discount_amount,
											'SRecSaldoCredit'           => 0,
											'AmountCurrency'            => $discount_currency,
										 );

										if($discount_amount > 0){
											$this->m_sales_receipt->update_journal($journal_discount, $SRecNumber, $DiscountAccount->AccountNumber, $Invoice_Number);
										}
									}
									
									$total_discount = $discount_amount;
								}                    
							}
							/*=====================End===================================================================*/
							
							/*
								Beban Pembulatan
							*/
							if($Load_Rounding > 0){
								$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
								if($Currency_Code == 'IDR'){
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								else{
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								
								$beban_pembulatan           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccount->AccountNumber,
									'SRecSaldoDebet'            => abs($beban_amount),
									'SRecSaldoCredit'           => 0,
									'AmountCurrency'            => abs($beban_currency),
									'SRecSignStatus'            => 0, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $Invoice_Number,
									'LastUser'                  => $this->session->userdata("username")
								 );
								$this->m_sales_receipt->insert_journal($beban_pembulatan);
							}
							else if($Load_Rounding < 0){
								$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
								if($Currency_Code == 'IDR'){
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								else{
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
							
								$beban_pembulatan           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccount->AccountNumber,
									'SRecSaldoDebet'            => 0,
									'SRecSaldoCredit'           => abs($beban_amount),
									'AmountCurrency'            => abs($beban_currency),
									'SRecSignStatus'            => 1, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $Invoice_Number,
									'LastUser'                  => $this->session->userdata("username")
								 );
								$this->m_sales_receipt->insert_journal($beban_pembulatan);
							}	
							/*========================End==========================*/
							
							/*
								Beban Pembulatan Auto
							*/
							if($invoice_owing == 0){
								$total_hutang_real = $total_hutang;
							}
							else{
								$total_hutang_real = $payment_dp + $payment_disc + $Load_Rounding + $payment_amount;
							}
							
							$total_relize 			  = ($Relized_all_trans * $Bank_Curr_Rate) - ($Relized_all_trans * $invoice_rate); 
							
							$realizegl_value_beban    = $total_relize / $Bank_Curr_Rate ;
							$realized_amount_beban    = $Currency_Code == 'IDR' ? abs($realizegl_value_beban) : abs($realizegl_value_beban) * $Bank_Curr_Rate;
							
							if($total_relize > 0){
								$total_relize_all_kredit = abs($realized_amount_beban);
								$total_relize_all_debet  = 0;
							}
							else{
								$total_relize_all_kredit = 0;
								$total_relize_all_debet  = abs($realized_amount_beban);
							}
							 
							$Bank 				= empty($bank_amount) ? 0 : $bank_amount;
							$Disc 				= empty($total_discount) ? 0 : $total_discount;
							$Round 				= empty($Load_Rounding) ? 0 : $Load_Rounding;
							$Relize_Debet 		= empty($total_relize_all_debet) ? 0 : $total_relize_all_debet;
							$Relize_Kredit 		= empty($total_relize_all_kredit) ? 0 : $total_relize_all_kredit;
							$TotalDP_No_Curren 	= empty($total_dp_no_currency) ? 0 : $total_dp_no_currency;
							$TotalDP 			= empty($total_dp) ? 0 : $total_dp;
							$Beban 				= empty($total_hutang_real) ? 0 : $total_hutang_real;
							$selisih_kurs_dp	= doubleval($TotalDP) - doubleval($TotalDP_No_Curren * $invoice_rate);
							
							if($selisih_kurs_dp > 0){
								$RelizeDP_Debet 	= 0;
								$RelizeDP_Kredit 	= abs($selisih_kurs_dp);
							}
							else{
								$RelizeDP_Debet 	= abs($selisih_kurs_dp);
								$RelizeDP_Kredit 	= 0;
							}
							
							$Total_Beban 		= ($Bank + $Disc + $Round + $Relize_Debet + ($RelizeDP_Debet + $TotalDP)) - (($Beban * $invoice_rate) + $RelizeDP_Kredit + $Relize_Kredit);

							if($Total_Beban > 0){
								$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								if($Currency_Code == 'IDR'){
									$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
								}
								else{
									$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
								}
								
								$beban_pembulatan_auto           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccountAuto->AccountNumber,
									'SRecSaldoDebet'            => 0,
									'SRecSaldoCredit'           => abs($beban_amount_auto),
									'AmountCurrency'            => 0,
									'SRecSignStatus'            => 1, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $Invoice_Number,
									'LastUser'                  => $this->session->userdata("username")
								 );
								 $this->m_sales_receipt->insert_journal($beban_pembulatan_auto);
							}
							else if($Total_Beban < 0){
								$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								if($Currency_Code == 'IDR'){
									$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
								}
								else{
									$beban_amount_auto  = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
								}
							
								$beban_pembulatan_auto           = array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccountAuto->AccountNumber,
									'SRecSaldoDebet'            => abs($beban_amount_auto),
									'SRecSaldoCredit'           => 0,
									'AmountCurrency'            => 0,
									'SRecSignStatus'            => 0, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $Invoice_Number,
									'LastUser'                  => $this->session->userdata("username")
								 );
								 
								 $this->m_sales_receipt->insert_journal($beban_pembulatan_auto);
							}
							/*===============================End====================*/
							
							/*
								Insert Journal Payment Realized Account
							*/
							if($total_relize > 0){
								$realizegl_value    = $total_relize / $Bank_Curr_Rate ;                            
								$realized_amount    = $Currency_Code == 'IDR' ? abs($realizegl_value) : abs($realizegl_value) * $Bank_Curr_Rate;
								$realized_currency  = $Bank_Curr_Code == 'IDR' ? 0 : 0;
								//$realized_currency  = 0;    //abs($realizegl_value);
								
								$this->Insert_Journal_Realized(
									$SRecDate, $SRecNumber, $SRecDesc, $RealizedAccount->AccountNumber, 0, $realized_amount, $realized_currency, 1, $item_category_id                                 
								);                            
							}    
							/*=====================End===================================================================*/ 
							
							/*
								Insert Journal Payment Realized Account
							*/
							if($total_relize < 0){
								$realizegl_value    = $total_relize / $Bank_Curr_Rate ;                            
								$realized_amount    = $Currency_Code == 'IDR' ? abs($realizegl_value) : abs($realizegl_value) * $Bank_Curr_Rate;
								$realized_currency  = $Bank_Curr_Code == 'IDR' ? 0 : 0;
								//$realized_currency  = 0;    //abs($realizegl_value);
								
								$this->Insert_Journal_Realized(
									$SRecDate, $SRecNumber, $SRecDesc, $RealizedAccount->AccountNumber, $realized_amount, 0, $realized_currency, 0, $item_category_id                                
								);                                                        
							}   
							/*=====================End===================================================================*/
							
							
						}
						else if($row->Invoice_Type == 'SO'){
							$data_ppay_detail = $this->m_sales_receipt->get_receipt_detail($invoice_number, $SRecNumber);
							$total_ppay_realizedgl  = 0;
							$ppay_realizedgl        = 0;
							$advance_value 			= 0;
							$advance_currency 		= 0;
							$total_amount_advance 	= 0;
							
							/*
								Insert Journal Bank Acccount
							*/
							$payment_val 	= doubleval($payment_amount);
							$bank_amount 	= 0; 
							$bank_currency 	= 0; 
							
							if($Currency_Code == 'IDR'){
								$bank_amount    = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;	
								$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val / $Bank_Curr_Rate;
							}
							else{
								$bank_amount    = $Bank_Curr_Code == 'IDR' ? ($payment_currency / $Bank_Curr_Rate) * $Bank_Curr_Rate : $payment_val * $Bank_Curr_Rate;	
								$bank_currency  = $Bank_Curr_Code == 'IDR' ? $payment_currency / $Bank_Curr_Rate : $payment_val;
							}
							
							$get_journal_receipt = $this->m_sales_receipt->get_journal_recip_empty($BankPayment, $SRecNumber, $invoice_number);
							if(empty($get_journal_receipt->SRecAccountNumber)){
								$journal_bank           = array(
														'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
														'SRecNumber'                => $SRecNumber,
														'SRecDesc'                  => $SRecDesc,
														'SRecAccountNumber'         => $BankPayment,
														'SRecSaldoDebet'            => $bank_amount,
														'SRecSaldoCredit'           => 0,
														'AmountCurrency'            => $bank_currency,
														'SRecSignStatus'            => 0, 
														'ItemCategoryID'            => $item_category_id,
														'SInvNumber' 				=> $invoice_number,
														'LastUser'                  => $this->session->userdata("username")
													 );
	
								$this->m_sales_receipt->insert_journal($journal_bank);
							}
							else{
								$bank_amount      	= $bank_amount + $get_journal_receipt->SRecSaldoDebet;
								$bank_currency   	= $bank_currency + $get_journal_receipt->AmountCurrency;
								
								$journal_bank = array(
									'SRecSaldoDebet' 	=> $bank_amount,
									'SRecSaldoCredit' 	=> 0,
									'AmountCurrency' 	=> $bank_currency
								);
								$this->m_sales_receipt->update_journal($journal_bank, $SRecNumber, $get_journal_receipt->SRecAccountNumber, $invoice_number);
							}
							/*===================End========================================================================*/
							
							foreach($data_ppay_detail as $row_ppay){
								$payament_ratio         = $this->m_sales_receipt->get_receipt_by_id($row_ppay->InvoicePaymentID);
								$cat_payment_ratio      = $payament_ratio[0]->ItemCategoryRatio;
								$ipay_ItemType    		= $payament_ratio[0]->ItemType;
								
								$ppay_detail_id         = $row_ppay->SRecDetailID;
								$ppay_category_id       = $row_ppay->ItemCategoryID;
								$ppay_category_code     = $row_ppay->ItemCategoryCode;
								$ppay_ItemCategoryRatio = $row_ppay->ItemCategoryRatio;
								
								$currency_payable       = $payment_currency * ($cat_payment_ratio / 100);
								$amount_invoice         = $invoice_amount_copy * ($cat_payment_ratio / 100);
								$amount_advance         = $payment_amount * ($cat_payment_ratio / 100);
								$amount_advance_curr    = $payment_currency * ($cat_payment_ratio / 100);
								
								$amount_rounded       	= $Load_Rounding * ($cat_payment_ratio / 100);
								
								$amount_advance_owing   = ($payment_amount + $Load_Rounding) * ($cat_payment_ratio / 100);
								
								if($Currency_Code == 'IDR'){
									$total_amount_advance 	= $amount_advance + $amount_rounded;
								}
								else{
									if($Bank_Curr_Code == 'IDR'){
										$total_amount_advance 	= ($amount_advance_curr / $Bank_Curr_Rate) + $amount_rounded;
									}
									else{
										$total_amount_advance 	= $amount_advance + $amount_rounded;
									}
								}
								
								if($Currency_Code == 'IDR'){
									$inv_curr_amount    = $amount_advance;
									$ppay_curr_amount   = $amount_advance;                                
								}
								else{
									$inv_curr_amount    = $amount_advance * $invoice_rate;
									$ppay_curr_amount   = $amount_advance * $Bank_Curr_Rate;
								}
								
								$ppay_realizedgl        = $ppay_curr_amount - $inv_curr_amount;
								$inv_owing              = $amount_invoice - ($amount_advance_owing);   
	
								/*
									.Update ppaydetail
								*/
								$this->update_detail(
									$Select_DP, $ppay_detail_id, $inv_owing, $Bank_Curr_Rate, NULL, 0, 0, $amount_advance, 
									$amount_advance, $currency_payable, $inv_curr_amount, $ppay_realizedgl, $amount_rounded
								);   	
								
								if($ipay_ItemType == 0){
									$DPAccount  = $this->m_account_journal->get_cat_sales_account('AdvanceSales', $ppay_category_id, $Currency_Code); // Uang Muka Category -> 1-4-03-001-00                            
									if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan Inventory', $Currency_Code);}
								}
								else {
									$DPAccount  = $this->m_account_journal->get_sys_service_account('SalesAdvance', $Currency_Code); // Uang Muka Expense -> 1-4-03-001-00                            
									if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan Expense', $Currency_Code);}
								}
								
								if($Currency_Code == 'IDR'){
									$advance_value     		= $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance;
									$advance_currency   	= $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance / $Bank_Curr_Rate;
								}
								else{
									$advance_value    		= $Bank_Curr_Code == 'IDR' ? $total_amount_advance * $Bank_Curr_Rate : $total_amount_advance * $Bank_Curr_Rate;	
									$advance_currency  		= $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance;
								}
	
								/*
									Insert Journal DP Account Purchase
								*/
								$get_journal_receipt 			= $this->m_sales_receipt->get_journal_recip_empty($DPAccount->AccountNumber, $SRecNumber, $invoice_number);
								
								if(empty($get_journal_receipt->SRecAccountNumber)){
									$journal_dp         = array(
										'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
										'SRecNumber'                => $SRecNumber,
										'SRecDesc'                  => $SRecDesc,
										'SRecAccountNumber'         => $DPAccount->AccountNumber,
										'SRecSaldoDebet'            => 0,
										'SRecSaldoCredit'           => $advance_value,
										'AmountCurrency'            => $advance_currency,
										'SRecSignStatus'            => 0, 
										'SInvNumber' 				=> $invoice_number,
										'ItemCategoryID'            => $item_category_id,
										'LastUser'                  => $this->session->userdata("username")	
									 );
									 
									if($advance_value > 0){
										$this->m_sales_receipt->insert_journal($journal_dp);
									}
								}
								else{
									$advance_value      	= $advance_value + $get_journal_receipt->SRecSaldoCredit;
									$advance_currency   	= $advance_currency + $get_journal_receipt->AmountCurrency;
								
									$journal_dp = array(
										'SRecSaldoDebet' 	=> 0,
										'SRecSaldoCredit' 	=> $advance_value,
										'AmountCurrency' 	=> $advance_currency
									);
									
									if($advance_value > 0){
										$this->m_sales_receipt->update_journal($journal_dp, $SRecNumber, $get_journal_receipt->SRecAccountNumber, $invoice_number);
									}
								}						
							}	
							/*======================================================================================*/
							
							/*
								RoundingLoad greater than 0 (Beban Pembulatan)
							*/
							if($Load_Rounding > 0){
								$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
								if($Currency_Code == 'IDR'){
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								else{
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
							
								$beban_pembulatan         		= array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccount->AccountNumber,
									'SRecSaldoDebet'            => abs($beban_amount),
									'SRecSaldoCredit'           => 0,
									'AmountCurrency'            => abs($beban_currency),
									'SRecSignStatus'            => 0, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")	
								 );
						
								$this->m_sales_receipt->insert_journal($beban_pembulatan);
							}
							else if($Load_Rounding < 0){
								$BebanAccount   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
								if($BebanAccount == false) {$this->trans_rollback('journal','Beban Pembulatan', $Currency_Code);}
								
								$beban_amount    = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
								if($Currency_Code == 'IDR'){
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
								else{
									$beban_currency  = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
								}
							
								$beban_pembulatan         		= array(
									'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
									'SRecNumber'                => $SRecNumber,
									'SRecDesc'                  => $SRecDesc,
									'SRecAccountNumber'         => $BebanAccount->AccountNumber,
									'SRecSaldoDebet'            => 0,
									'SRecSaldoCredit'           => abs($beban_amount),
									'AmountCurrency'            => abs($beban_currency),
									'SRecSignStatus'            => 1, 
									'ItemCategoryID'            => $item_category_id,
									'SInvNumber' 				=> $invoice_number,
									'LastUser'                  => $this->session->userdata("username")	
								 );
						
								$this->m_sales_receipt->insert_journal($beban_pembulatan);
							}

							$total_amount_paid      += $payment_amount;
							$total_currency_paid    += $payment_currency;                                
						
						}
					}        
				} //akhir paid = Yes
                else{
                   //20. Delete PPay Detail for UnPaid Status
					$this->m_sales_receipt->delete_detail($invoice_number);
                }
            }//akhir foreach
            
            /*
				Update PurchasePayment for header info only.  
			*/          
            $data_group = array (
                            'SRecDesc'              => $SRecDesc, 
                            'ChequeNumber'          => $ChequeNumber,
                            'SInvTotalAmount'       => $hdn_SInvTotalAmount,
                            'SRecTotalDiscount'     => $hdn_SRecTotalDiscount,
                            'SRecTotalDPUsed'       => $hdn_SRecTotalDPUsed,
                            'SRecTotalAmount'       => $total_amount_paid,
                            'SRecAmountCurr'     	=> $total_currency_paid,
                            'SRecTotalOwing'         => $hdn_SRecTotalOwing,
							'BankCurrRate' 			=> $Bank_Curr_Rate,
							'AppFinished' 			=> 2,
                            'LastUser'              => $this->session->userdata("username")	
                          );           

            $this->m_sales_receipt->update($data_group, $SRecNumber);
           /*====================End=============================================================*/
			
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$result['status'] 		= FALSE;
				$result['message']   = get_notification_transaksi($this->name, 'update', 0,"$SRecNumber"); 
			}
			else {
				$this->db->trans_commit();
				$result['status'] 		= TRUE;
				$result['message']   = get_notification_transaksi($this->name, 'update', 1,"$SRecNumber");
			}
		}
        else{
            $result['status']   = false;
            $result['message']  = get_notification_transaksi($this->name, 'update', 0);            
        }

        echo json_encode($result);
    }
	
    
	/*
		update detail
	*/
	public function update_detail($Select_DP, $ipay_payment_id, $pinv_owing, $bank_curr_rate, $ppay_disc_date, $payment_disc, $payment_dp, 
                                  $payment_amount, $payment_total, $payment_currency, $invoice_currency, $payment_real_gl, $payment_rounded){
        $detail_data  = array(
                            'SRecOwing'             => $pinv_owing,
                            'SRecCurrRate'          => $bank_curr_rate,
                            'SRecDiscDate'          => $ppay_disc_date, 
                            'SRecDiscount'          => $payment_disc, 
                            'SRecDPUsed'            => $payment_dp, 
                            'SRecAmount'            => $payment_amount, 
                            'SRecTotalAmnt'         => $payment_total, 
                            'SRecCurrency'          => $payment_currency,
                            'SInvCurrency'          => $invoice_currency,
                            'SRecRealizedGL'        => $payment_real_gl,
                            'SRecRounded'           => $payment_rounded,   
							'SOrdNumber' 			=> $Select_DP,                             
                            'LastUser'              => $this->session->userdata("username")				
                        );

        $this->m_sales_receipt->update_detail($detail_data, $ipay_payment_id);
    }    
								 
	public function Insert_Journal_Realized($ppay_date, $ppay_number, $ppay_desc, $ppay_account_number, $ppay_saldo_debet, 
                                            $ppay_saldo_credit, $ppay_saldo_currency, $ppay_sign_status, $item_category_id){
        $journal_realized = array(
                                'SRecDate'                  => $ppay_date,
                                'SRecNumber'                => $ppay_number,
                                'SRecDesc'                  => $ppay_desc,
                                'SRecAccountNumber'         => $ppay_account_number,
                                'SRecSaldoDebet'            => $ppay_saldo_debet,
                                'SRecSaldoCredit'           => $ppay_saldo_credit,
                                'AmountCurrency'            => $ppay_saldo_currency,
                                'SRecSignStatus'            => $ppay_sign_status, 
                                'ItemCategoryID'            => $item_category_id,
                                'LastUser'                  => $this->session->userdata("username")
                             );

        $this->m_sales_receipt->insert_journal($journal_realized);
    }
	
	/*
		get_dp_by_sales_order_update
	*/
	function get_dp_by_sales_order_update($PPnFiscalStatus, $SRecDetailID, $SRecAmountCurr, $CurrencyRate, $CurrencyCode, $SRecDate, $SRecDesc, $CurrencyCode_Cus,$BankCode, $SRecNumber, $fiscal_rate, $DPStatus, $CategoryName, $Dp_Receipt, $SRecDetailID, $item_categori_id, $item_category_code, $srec_disc_datee, $invoice_rate, $invoice_number, $invoice_amount, $invoice_owing, $invoice_type, $invoice_date, $receipt_amount, $receipt_disc, $receipt_currency, $InvoiceAmountCopy, $RoundingLoad, $SRecTotalAmount){
		
		$InvoiceReceipt    	 = array();
		$InvoiceRatio    	 = array();
		$InvoiceAmount    	 = array();
		$InvoiceAdvanced     = array();
		$InvoiceItemCategory = array();
		$BankAccount       = $BankCode;
						
		$get_invoice_receipt = $this->m_sales_receipt->get_invoice_recip($invoice_number, 1, NULL);
		foreach($get_invoice_receipt as $row_receipt){
			/*============================deklar variabel from invoice receipt====================*/
			$InvoiceNumber 		   = $row_receipt->InvoiceNumber;
			$InvoicePaymentID      = $row_receipt->InvoicePaymentID;
			$ItemCategoryID        = $row_receipt->ItemCategoryID;
			$ItemCategoryCode      = $row_receipt->ItemCategoryCode;                            
			$ItemCategoryRatio     = $row_receipt->ItemCategoryRatio;
			$InvoiceAmount         = $row_receipt->InvoiceAmount;
			$InvoiceType           = $row_receipt->InvoiceType;
			//$PPnFiscalStatus 	   = $row_receipt->PPnFiscalStatus;
			/*==============================end=================================================*/
			
			/*============calculate cuurency customer===========================================*/
			if($CurrencyCode_Cus == 'IDR'){
				$amount_advance  = $receipt_amount * ($ItemCategoryRatio / 100);
			}
			else{
				if($CurrencyCode == 'IDR'){
					$amount_advance  = $receipt_currency * ($ItemCategoryRatio / 100);
				}
				else{
					$amount_advance  = $receipt_amount * ($ItemCategoryRatio / 100);
				}
			}
			/*=================end===========================================================*/
			
			/*=========================calculate ration invoicereceipt=======================*/
			$RoundingLoad_Total  	= $RoundingLoad * ($ItemCategoryRatio / 100);
			$amount_total           = $amount_advance + $RoundingLoad;	
			$inv_curr_amount        = $amount_total * $invoice_rate;
			/*=========================end===================================================*/
			
			/*===========================================================================*/
			/*
				update to table from invoice receipt (SRecAmntBooked,SRecTotalBooked,SRecRoundBooked)
			*/
			$data_at_invoicereceipt = array(
				'SRecAmntBooked' 	=> $amount_advance,
				'SRecTotalBooked' 	=> $SRecAmountCurr,
				'SRecRoundBooked' 	=> $RoundingLoad_Total
			);
			
			$this->m_sales_receipt->update_invoicerecip($data_at_invoicereceipt, $InvoicePaymentID);
			/*==========================end==============================================*/
			
			/*
				grouping by invoice number from invoicerecip
			*/
			@$InvoiceReceipt[$InvoiceNumber]   		 += $InvoiceAmount;
			@$InvoiceRatio[$InvoiceNumber]     		 += $amount_total;
			@$InvoiceAdvanced[$InvoiceNumber]  		 += $amount_advance;
			@$InvoiceItemCategory[$ItemCategoryID]   += $amount_total;
			/*====================================================*/
		}
		
		/*===============================insert detail===========================================*/
		$this->update_detail($SRecDetailID, $PPnFiscalStatus, $ItemCategoryCode, $ItemCategoryID, $inv_curr_amount, $srec_disc_datee, $InvoicePaymentID, $InvoiceReceipt, $InvoiceType, $Dp_Receipt, $CategoryName, $DPStatus, $receipt_disc, $fiscal_rate, $invoice_rate, $invoice_owing, $InvoiceAmountCopy, $invoice_amount, $invoice_date, $invoice_number, $receipt_amount, $receipt_currency, $RoundingLoad, $SRecNumber);
		/*=======================================================================================*/
		
		/*===========================insert journal===============================================*/
		$this->insert_journal_for_dp($InvoiceItemCategory, $RoundingLoad, $InvoiceRatio, $ItemCategoryID, $InvoiceReceipt, $ItemCategoryID, $SRecDate, $CurrencyCode, $CurrencyCode_Cus, $receipt_amount, $receipt_currency, $SRecNumber, $BankAccount, $CurrencyRate, $SRecDesc);
		/*====================================end=================================================*/
	}
	/*=======================================end============================================*/
	
	/*
		get ppn fiscal Update
	*/
	function get_ppn_fiscal_update($InvoiceAmountCopy, $PPnFiscalStatus, $CurrencyRate, $CurrencyCode, $SRecDate, $SRecDesc, $CurrencyCode_Cus, $BankCode, $SRecNumber, $fiscal_rate, $DPStatus, $CategoryName, $Dp_Receipt, $SRecDetailID, $item_categori_id, $item_category_code, $srec_disc_datee, $invoice_rate, $invoice_number, $invoice_amount, $invoice_owing, $invoice_type, $invoice_date, $receipt_amount, $receipt_disc, $receipt_currency, $receipt_amount_copy, $RoundingLoad, $SRecTotalAmount){
		
		$InvoiceReceipt 	= array();
		$InvoiceRatio    	= array();
		$InvoiceAmount   	= array();
		$InvoiceAdvanced 	= array();
		$BankAccount      	= $BankCode;
		$RoundingLoad_Total = 0;
		/*========================get ppn fiscal from invoice receipt=================================*/
		$get_invoice_receipt = $this->m_sales_receipt->get_invoice_recip($invoice_number, 2, 1); //ge data from invoicerecip new table
		foreach($get_invoice_receipt as $row_receipt){
			/*======================deklar variabel from invoice receipt==============================*/
			$InvoiceNumber 		= $row_receipt->InvoiceNumber;
			$InvoicePaymentID   = $row_receipt->InvoicePaymentID;
			$ItemCategoryID     = $row_receipt->ItemCategoryID;
			$ItemCategoryCode   = $row_receipt->ItemCategoryCode;                            
			$ItemCategoryRatio  = $row_receipt->ItemCategoryRatio;
			$InvoiceAmount      = $row_receipt->InvoiceAmount;
			$InvoiceType        = $row_receipt->InvoiceType;
			//$PPnFiscalStatus 	= $row_receipt->PPnFiscalStatus;
			$inv_curr_amount 	= 0;
			/*========================end===========================================================*/
			
			/*===========================kalkulasi ratio invoicereceipt=============================*/
			$amount_advance         = $receipt_amount * ($ItemCategoryRatio / 100);
			$DiscReceipt  			= $receipt_disc * ($ItemCategoryRatio / 100);
			$RoundingLoad_Total  	= $RoundingLoad * ($ItemCategoryRatio / 100);
			$inv_curr_amount        = $inv_curr_amount + $amount_advance;
			/*=========================end==========================================================*/
			
			@$InvoiceReceipt[$InvoiceNumber]   += $InvoiceAmount;
		}
		/*===================end======================================================================*/
		
		/*===============================update detail dan insert journal========================*/
		$this->update_detail($SRecDetailID, $PPnFiscalStatus, $ItemCategoryCode, $ItemCategoryID, $inv_curr_amount, $srec_disc_datee, $InvoicePaymentID, $InvoiceReceipt, $InvoiceType, $Dp_Receipt, $CategoryName, $DPStatus, $receipt_disc, $fiscal_rate, $invoice_rate, $invoice_owing, $InvoiceAmountCopy, $invoice_amount, $invoice_date, $invoice_number, $receipt_amount, $receipt_currency, $RoundingLoad, $SRecNumber);
		$this->insert_journal_ppn_fiscal($BankAccount, $CurrencyCode_Cus, $CurrencyCode, $SRecDesc, $SRecDate,$fiscal_rate, $RoundingLoad, $InvoiceRatio, $ItemCategoryID, $InvoiceReceipt, $ItemCategoryID, $SRecDate, $CurrencyCode, $CurrencyCode_Cus, $receipt_amount, $receipt_currency, $SRecNumber, $BankAccount, $CurrencyRate, $SRecDesc);
		/*=======================================================================================*/
	}
	/*=====================================end==============================================*/
	
	/*
		Get Sales Invoice Update
	*/
	function get_sales_invoice_from_receipt_update($jurnal_dp, $PPnFiscalStatus, $SRecDetailID, $SRecAmountCurr, $CurrencyRate, $CurrencyCode, $SRecDate, $SRecDesc, $CurrencyCode_Cus,$BankCode, $SRecNumber, $fiscal_rate, $DPStatus, $CategoryName, $Dp_Receipt, $SRecDetailID, $item_categori_id, $item_category_code, $srec_disc_datee, $invoice_rate, $invoice_number, $invoice_amount, $invoice_owing, $invoice_type, $invoice_date, $receipt_amount, $receipt_disc, $receipt_currency, $InvoiceAmountCopy, $RoundingLoad, $SRecTotalAmount){
		
		$InvoiceReceipt    	 		= array();
		$InvoiceRatio    	 		= array();
		$InvoiceAmount   	 		= array();
		$InvoiceAdvanced 	 		= array();
		$InvoiceItemCategory 		= array();
		
		$amount_round         		= 0;
		$dp_ratio 					= 0;
		$inv_curr_amount 			= 0;
		$total_curr_amount 			= 0;
		
		$get_invoice_receipt = $this->m_sales_receipt->get_invoice_recip($invoice_number, 0, $PPnFiscalStatus);
		
		foreach($get_invoice_receipt as $row_receipt){
			
			/*
				Deklar variabel
			*/
			$InvoiceNumber 			= $row_receipt->InvoiceNumber;
			$InvoicePaymentID       = $row_receipt->InvoicePaymentID;
			$ItemCategoryID         = $row_receipt->ItemCategoryID;
			$ItemCategoryCode       = $row_receipt->ItemCategoryCode;                            
			$ItemCategoryRatio      = $row_receipt->ItemCategoryRatio;
			$InvoiceAmount          = $row_receipt->InvoiceAmount;
			$InvoiceType            = $row_receipt->InvoiceType;
			/*========================end==========================================*/
			
			$amount_advance         = $receipt_amount * ($ItemCategoryRatio / 100);
			$dp_ratio  				= $Dp_Receipt * ($ItemCategoryRatio / 100);
			
			$disc_inv  				= $receipt_disc * ($ItemCategoryRatio / 100);
			$RoundingLoad_Total  	= $RoundingLoad * ($ItemCategoryRatio / 100);
			$total_ratio_inv 		= ($amount_advance + $dp_ratio) - $disc_inv;
			
			$inv_curr_amount        = $amount_advance * $invoice_rate;
			$srecip_curr_amount     = $amount_advance * $CurrencyRate;
							
			$data_at_invoicereceipt = array(
				'SRecAmntBooked' 	=> $amount_advance,
				'SRecDiscBooked' 	=> $disc_inv,
				'SRecDPUsedBooked' 	=> $dp_ratio,
				'SRecTotalBooked' 	=> $SRecAmountCurr,
				'SRecRoundBooked' 	=> $RoundingLoad_Total
			);			
			$this->m_sales_receipt->update_invoicerecip($data_at_invoicereceipt, $InvoicePaymentID);
			
			@$InvoiceReceipt[$InvoiceNumber]     += $InvoiceAmount;
			//@$InvoiceRatio[$row_receipt->InvoiceNumber]       += $amount_total;
			//@$InvoiceAmount[$row_receipt->InvoiceNumber]      += $inv_amount;
			//@$InvoiceAdvanced[$row_receipt->InvoiceNumber]    += $amount_advance;
			
			@$CategoryDisc[$ItemCategoryID]     	 = $disc_inv;
			@$InvoiceReceipt[$InvoiceNumber]   		 += $InvoiceAmount;
			@$InvoiceItemCategory[$ItemCategoryID]   += $dp_ratio;
			
			//@$CategoryAmount[$row_recip->InvoiceType]    += doubleval($row_recip->InvoiceAmount);
			//@$ItemCategoryCode[$row_recip->ItemCategoryCode]   = doubleval($row_recip->InvoiceAmount);
			
			//@$CategoryAdvance[$row_recip->ItemCategoryCode]    += doubleval($amount_advance);
			
			//@$CategoryDP[$row_recip->ItemCategoryCode]    += doubleval($dp_ratio);
			
			/*====================Summing for SinCurrency====================*/
			$total_curr_amount = $total_curr_amount + $inv_curr_amount;	
			/*===========================end=================================*/
		}
		
		/*===============================insert detail===========================================*/
		$this->update_detail($SRecDetailID, $PPnFiscalStatus, $ItemCategoryCode, $ItemCategoryID, $inv_curr_amount, $srec_disc_datee, $InvoicePaymentID, $InvoiceReceipt, $InvoiceType, $Dp_Receipt, $CategoryName, $DPStatus, $receipt_disc, $fiscal_rate, $invoice_rate, $invoice_owing, $InvoiceAmountCopy, $invoice_amount, $invoice_date, $invoice_number, $receipt_amount, $receipt_currency, $RoundingLoad, $SRecNumber);
		/*=======================================================================================*/
		
		/*====================insert journal receipt=============================================*/
		$this->insert_journal_sales_receipt($jurnal_dp, $BankCode, $InvoiceItemCategory, $CategoryDisc, $invoice_rate, $CurrencyRate, $get_invoice_receipt, $CurrencyCode, $CurrencyCode_Cus, $receipt_amount, $receipt_disc, $Dp_Receipt, $RoundingLoad, $SRecNumber, $SRecDate, $SRecDesc);
		/*====================end================================================================*/
	}
	/*=======================================End=================================================*/
	
	public function approval(){
            $detail_post    = $this->input->post('Detail');        
            $detail         = json_decode($detail_post);
            
            if(count($detail) > 0) {
                $this->db->trans_begin();
				
                $branch_code        = $this->session->userdata('branch');
                $status             = $this->input->post('Status');
                $customer_code        = $this->input->post('CustomerCode');
                $srec_number        = $this->input->post('SRecNumber');
                $bank_curr_code     = $this->input->post('BankCurrCode');
                $bank_curr_rate     = $this->input->post('BankCurrRate');
				$Cust_Curr_Code     = $this->input->post('Cust_Curr_Code');
				$SRecDate     		= $this->input->post('txt_srec_date');
				$DPPartial     		= $this->input->post('DPPartial');
                $data               = $this->m_sales_receipt->get_detail($srec_number);
				
				/*
					Cek Concuren For Approval Dir
				*/
				$get_employee = $this->m_employee->get_detail($data->AppLevel1Code);
				if(($data->AppLevel1Code != NULL)){
					$result['status']   = false;
					$result['message']  = 'Maaf Transaksi gagal di Approve, karena transaksi sudah di approve terlebih dahulu oleh, '.$get_employee->EmployeeName.' pada tanggal '.date("d-m-Y", strtotime($data->AppLevel1Date)).'';
					
					echo json_encode($result);
					die();
				}
				/*=========================End========================================*/
				
                $app_finished   = 1;
				$trans_status   = 2;
				$total_amount   = 0;
				$total_DP       = 0;
				$total_round 	= 0;
				
				foreach($detail as $row){
					if($row->Paid == 'Yes'){
						$invoice_number     = $row->Invoice_Number;
						$total_amount       = $row->Receipt_Amount;
						$total_DP           = $row->Receipt_DP;
						$total_discount     = $row->Receipt_Discount;
						$total_round     	= $row->Load_Rounding;
						$Select_DP     		= $row->Select_DP;
						
						$DP_Partial  		= 0;
						$DP_Customer 		= 0;
						
						if($row->ItemCategoryID == -3){
							/*
								Update customer outstanding fiscal
							*/
							$customer_dp        = $this->m_customer->get_saldo_by_id($customer_code);
							$ppn_fiscal_debt    = $customer_dp[0]->OutStandingFiscal - ($total_amount + $total_round);
							
							$data_customer     = array (
								'LockStatus'    	=> 0,
								'OutStandingFiscal' => $ppn_fiscal_debt,
								'LastUser'          => $this->session->userdata("username")
							);
							$this->m_customer->update($data_customer, $customer_code);
							/*========================End===================================*/
						}
						else{
							if($row->Invoice_Type == 'SI'){
								/*
									Update outstanding Customer
								*/
								$customer_dp        = $this->m_customer->get_saldo_by_id($customer_code);
								
								$saldo_balance  	= $customer_dp[0]->OutStanding - ($total_amount + $total_DP + $total_discount + $total_round);
								$saldodp_balance    = $customer_dp[0]->SaldoDPBalance - $total_DP;
								
								$data_customer    = array (
									'OutStanding'       => $saldo_balance,
									'SaldoDPBalance'    => $saldodp_balance,
									'LockStatus'    	=> 0,
									'LastUser'          => $this->session->userdata("username")
								 );
								 $this->m_customer->update($data_customer, $customer_code);
								 
								 /*==============End================================================*/
								 
								 /*
									Update pordetail for status dp for
									jika dp used dan dp balance tidak sama maka status dp for berubah jadi 1
								*/
								if($Select_DP != " "){
									$status_dp_for  = $this->m_sales_receipt->get_sordetail_dp_invoice_or_return($customer_code, $Select_DP, 1);
									foreach($status_dp_for as $row_dp_for){
										$DPUsed 				= $row_dp_for->DPUsed; 
										$SaldoDPBalance 		= $row_dp_for->SaldoDPBalance;
										$SOrdDetailDPID 		= $row_dp_for->SOrdDetailDPID;
											
										if($DPUsed != $SaldoDPBalance){
											$IsEdit = 1;
										}
										else{
											$IsEdit = 0;
										}
										
										$update_dp_for = array(
											'IsEdit' 			=> $IsEdit
										);
										$this->m_sales_receipt->update_so_detail_dp_by_customer($update_dp_for, $customer_code, $SOrdDetailDPID, $Select_DP);
									}
								}
							}
							else if($row->Invoice_Type == 'SO'){
								if($Cust_Curr_Code == 'IDR'){
									$currency_rate_po = 1;
								}
								else{
									$currency_rate_po = $bank_curr_rate;
								}
								
								if($Cust_Curr_Code == 'IDR'){
									$Paymen_DP = doubleval($row->Receipt_Amount + $row->Load_Rounding);
								}
								else{
									$Paymen_DP = doubleval($row->Receipt_Amount + $row->Load_Rounding);
								}
								
								/*===============================calculate dp partial=========================================================*/
								$customer_dp        = $this->m_customer->get_saldo_by_id($customer_code);
								$DP_Customer   		= $customer_dp[0]->SaldoDPBalance;
								
								if($row->Invoice_Owing == 0){
									$DP_Customer = $DP_Customer + $row->Invoice_Amount;
									$DPPartial	 = $DPPartial + $row->Receipt_Amount + $row->Load_Rounding;
									$DPPartial   = $DPPartial - $row->Invoice_Amount;
									$StatusDPFor = 1;
								}
								else{
									$DP_Customer = $DP_Customer;
									$DPPartial 	 = $DPPartial + $row->Receipt_Amount + $row->Load_Rounding;
									$StatusDPFor = 0;
								}
								/*========================end=================================================================================*/
								
								
								/*==============================================insert pordetail dp==========================================*/
								$data_detail_dp = array(
									'SOrdNumber' 	=> $row->Invoice_Number,
									'CustomerCode' 	=> $customer_code,
									'SRecNumber' 	=> $srec_number,
									'SOrdTotalDP' 	=> $row->Invoice_Amount,
									'Owing' 		=> $row->Invoice_Owing,
									'CurrencyRate' 	=> $currency_rate_po,
									'PaymentAmount' => $Paymen_DP,
									'SaldoDPBalance' => $Paymen_DP,
									'PaymentDate' 	=> date("Y-m-d", strtotime($SRecDate)),
									'SOrdStatus' 	=> 1,
									'StatusDPFor' 	=> $StatusDPFor,
									'LastUser'      => $this->session->userdata("username"),
									'LastEdited'    => date('Ymdhis')				
								);
								
								$this->m_sales_receipt->insert_so_detail_dp($data_detail_dp);
							   /*=========================================end===============================================================*/
								
								/*
									Update dp paid di vendor
								*/
								$data_customer_dp     = array (
									'SaldoDPBalance'    => $DP_Customer,
									'LockStatus'    	=> 0,
									'SaldoDPPartial' 	=> $DPPartial,
									'LastUser'          => $this->session->userdata("username")
								);

								$this->m_customer->update($data_customer_dp, $customer_code, $customer_dp[0]->BranchCode);
								/*=================End==============================================================*/
								
								/*
									Update PO total payment DP
								*/
								$SRecTotalDP       = $this->m_sales_order->get_sales_order($invoice_number);
								$new_srec_totaldp   = $SRecTotalDP + ($total_amount + $row->Load_Rounding);

								$data_so = array(
											'SRecTotalDP'   => $new_srec_totaldp,
											'LastUser'      => $this->session->userdata("username")
										);

								$this->m_sales_order->update($data_so, $invoice_number);
								/*=================End==============================================================*/
								
								/*================Update purchase Order for Receive DP===============================================================*/
								$this->m_sales_order->set_on_progress_dp_paid($invoice_number);
								/*==============================end===============================================================================*/
								
								if($row->Invoice_Owing == 0){
									$data_sordetail_dp = array(
										'StatusDPFor' => 1
									);
									
									$this->m_sales_receipt->update_so_detail_dp_by_invoice($data_sordetail_dp, $invoice_number);
								}
							}
						}

						/*
							Update Invoice Payment table
						*/
						$data_ppay_detail   = $this->m_sales_receipt->get_receipt_detail($invoice_number, $srec_number);
						
						foreach($data_ppay_detail as $row_detail){
							$inv_payment_id     = $row_detail->InvoicePaymentID;
							$payment_currency   = $bank_curr_code == 'IDR' ? $row_detail->SRecCurrency : $row_detail->SRecCurrency * $bank_curr_rate;
							
							$inv_disc_date  = empty($row_detail->SRecDiscDate) ? null: date("Y-m-d",strtotime($row_detail->SRecDiscDate));
							$data_payment   = $this->m_sales_receipt->get_receipt_by_id($inv_payment_id);

							$payment_update = array(
												'InvoiceOwing'          => $data_payment[0]->InvoiceOwing - ($row_detail->SRecDPUsed + $row_detail->SRecDiscount + $row_detail->SrecRounded + $row_detail->SRecAmount),
												'ReceiptDiscDate'       => $inv_disc_date,
												'ReceiptDiscount'       => $data_payment[0]->ReceiptDiscount + $row_detail->SRecDiscount,
												'ReceiptDPUsed'         => $data_payment[0]->ReceiptDPUsed + $row_detail->SRecDPUsed,
												'ReceiptAmount'         => $data_payment[0]->ReceiptAmount + $row_detail->SRecAmount,
												'ReceiptTotal'          => $data_payment[0]->ReceiptTotal + $row_detail->SRecTotalAmnt,
												'ReceiptCurrency'       => $data_payment[0]->ReceiptCurrency + $row_detail->SRecCurrency,
												//'InvoiceCurrency'       => $data_payment[0]->InvoiceCurrency + $row_detail->SInvCurrency,
												'ReceiptRounded'        => $data_payment[0]->ReceiptRounded + $row_detail->SrecRounded,
											);

						   $this->m_sales_receipt->update_invoicerecip($payment_update, $inv_payment_id);
						}  
						/*==================End================================================================================================*/   
					}
					
					//2. Set Finish Status as Purhcase Invoice table
					if(($row->Invoice_Type == 'SI') || ($row->ItemCategoryID == -3)){
						$get_invoice_receipt = $this->m_sales_receipt->set_finish_invoice($invoice_number);
						foreach($get_invoice_receipt as $row_receipt){
							if(abs(round($row_receipt->InvoiceOwing, 1)) == 0){
								$data_pi = array (			
									'TransStatus'   => 2,
									'LastUser' 	=> $this->session->userdata("username")
								);
					
								$this->m_sales_invoice->update($data_pi, $invoice_number);
							}
						}
					}
					//-------------------------------------------------------------------------------------------------//
				}
                
                //8. Update Approval Finished for update Journal
                 $data_pp = array (
					'TransStatus'       => $trans_status,						
					'AppLevel1Status'   => 1,
					'AppLevel1Code'     => $this->session->userdata("username"),
					'AppLevel1Date'     => date("Y-m-d"),	
					'AppFinished'       => $app_finished, 
					'LastUser'          => $this->session->userdata("username")
				);
                
                $this->m_sales_receipt->update($data_pp, $srec_number);
                //-------------------------------------------------------------------------------------------------------------//

                $this->db->trans_commit();
                $result['status']   = true;
                $result['message']  = get_notification('approval', 1);
            }
            else{
                $result['status']   = false;
                $result['message']  = get_notification('approval', 0);                
            }

            echo json_encode($result);
            die();		
    }
	
    function reverse_data_detail() {
		try{
			$txt_srec_no  		= $this->input->post('txt_srec_no');
			$customer_code      = $this->input->post('cbg_customer');
			$bank_curr_code 	= $this->input->post('hdn_bank_curr_code');
			$bank_curr_rate 	= $this->input->post('txt_bank_curr_rate');
			$txt_srec_date 		= $this->input->post('txt_srec_date');
			
			$detail_post 		= $this->input->post('detail');
            $detail 			= json_decode($detail_post);
			
			$date_transaction 	= check_end_periode($txt_srec_no);
			 
			$get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);//Check Periode End
			$get_customer 	 = $this->m_sales_dp->get_customer_code($customer_code);
			 
			if ($get_end_periode) {
				throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
			} else if($get_customer->LockStatus == 1){
				throw new Exception("Maaf Customer ini mempunya Transaksi yang belum di selesaikan di Sales Receipt atau Sales Journal, Silahkan proses terlebih dahulu"); //sudah di end periode atau belum
			}
			
			foreach($detail as $row){
				$Invoice_Type 		= $row->Invoice_Type;
				$invoice_number     = $row->Invoice_Number;
				$total_amount       = $row->Receipt_Amount;
				$total_DP           = $row->Receipt_DP;
				$total_discount     = $row->Receipt_Discount;
				$total_round     	= $row->Load_Rounding;
				$Select_DP     		= $row->Select_DP;
				
				$DPPartial  		= 0;
				$DP_Customer 		= 0;
				$SInvDate_Loop_new 		= "";	
				
				if(($Invoice_Type == "SO") && ($row->ItemCategoryID != -3)){
					$get_sales_invoicedp = $this->m_sales_receipt->get_sales_order_dp_detail($invoice_number);
					foreach($get_sales_invoicedp as $row_detail_dp){
						$SInvDate_Loop 		= $row_detail_dp->SRecDate.' '.$row_detail_dp->SRecTime;
						$SInvDate_detail 	= $row->SRecDate.' '.$row->SRecTime;
						
						if(($SInvDate_Loop > $SInvDate_detail)){
							throw new Exception('Transaksi gagal di reverse, karna ada transaksi melebihi tanggal transaksi ini silahkan reverse terlebih dahulu transaki no '.$row_detail_dp->SrecNumber.''); //sudah di end periode atau belum
						}
					}
					
					$get_sales_receipt_useddp = $this->m_sales_receipt->get_sales_receipt_dp_used($invoice_number);
					if($get_sales_receipt_useddp != false){
						$SRecNumber 		= $get_sales_receipt_useddp->SRecNumber;
						
						throw new Exception('Reverse tidak berhasil, karena Dp ini sudah dipakai di Sales Recipt, silahkan Reverse transaki Sales Recipt dengan No '.$SRecNumber.''); //sudah di end periode atau belum
					}
					
					$get_sales_dp_useddp = $this->m_sales_receipt->get_sales_dp_useddp($invoice_number);
					if($get_sales_dp_useddp != false){
						$SDpayNumber 		= $get_sales_dp_useddp->SDpayNumber;
						
						throw new Exception('Reverse tidak berhasil, karena Dp ini sudah dipakai di Sales Dp Journal, silahkan Reverse transaki Sales Dp Journal dengan No '.$SDpayNumber.''); //sudah di end periode atau belum
					}
					
					/*===============================calculate dp partial=========================================================*/
					$customer_dp        = $this->m_customer->get_saldo_by_id($customer_code);
					$DP_Customer   		= $customer_dp[0]->SaldoDPBalance;
					
					if($row->Invoice_Owing == 0){
						$DP_Customer = $DP_Customer - $row->Invoice_Amount;
						$DPPartial	 = $DPPartial - $row->Receipt_Amount + $row->Load_Rounding;
						$DPPartial   = $DPPartial + $row->Invoice_Amount;
						$StatusDPFor = 1;
					}
					else{
						$DP_Customer = $DP_Customer;
						$DPPartial 	 = $DPPartial - $row->Receipt_Amount + $row->Load_Rounding;
						$StatusDPFor = 0;
					}
					/*========================end=================================================================================*/
								
					/*
						Update dp paid di vendor
					*/
					$data_customer_dp     = array (
						'SaldoDPBalance'    => $DP_Customer,
						'LockStatus'    	=> 1,
						'SaldoDPPartial' 	=> $DPPartial,
						'LastUser'          => $this->session->userdata("username")
					);
					
					$this->transaction['update_customer']['data'][] = $data_customer_dp;
                	$this->transaction['update_customer']['CustomerCode'][] = $customer_code;
					/*=================End==============================================================*/
					
					/*
						Update PO total payment DP
					*/
					$SRecTotalDP       = $this->m_sales_order->get_sales_order($invoice_number);
					$new_srec_totaldp   = $SRecTotalDP - ($total_amount + $row->Load_Rounding);

					$data_so = array(
								'SRecTotalDP'   => $new_srec_totaldp,
								'TransStatus'   => 0,
								'LastUser'      => $this->session->userdata("username")
							);

					$this->transaction['update_so']['data'][] = $data_so;
                	$this->transaction['update_so']['SOrdNumber'][] = $invoice_number;
					/*=================End==============================================================*/
					
					$this->transaction['delete_dp']['SRecNumber'][] = $txt_srec_no;
				}
				else if($row->ItemCategoryID == -3){
					/*
						Update customer outstanding fiscal
					*/
					$customer_dp        = $this->m_customer->get_saldo_by_id($customer_code);
					$ppn_fiscal_debt    = $customer_dp[0]->OutStandingFiscal + ($total_amount + $total_round);
					
					$data_customer     = array (
						'LockStatus'    	=> 1,
						'OutStandingFiscal' => $ppn_fiscal_debt,
						'LastUser'          => $this->session->userdata("username")
					);
					$this->transaction['update_customer']['data'][] = $data_customer;
					$this->transaction['update_customer']['CustomerCode'][] = $customer_code;
					
					$data_pi = array (			
						'TransStatus'   => 1,
						'LastUser' 		=> $this->session->userdata("username")
					);
					$this->transaction['update_pi']['data'][] = $data_pi;
                	$this->transaction['update_pi']['InvoiceNumber'][] = $invoice_number;
				}
				else if($Invoice_Type == "SI"){
					$customer_dp        = $this->m_customer->get_saldo_by_id($customer_code);
							
					$saldo_balance  	= $customer_dp[0]->OutStanding + ($total_amount + $total_DP + $total_discount + $total_round);
					$saldodp_balance    = $customer_dp[0]->SaldoDPBalance + $total_DP;
					
					$data_customer    = array (
						'OutStanding'       => $saldo_balance,
						'SaldoDPBalance'    => $saldodp_balance,
						'LockStatus'    	=> 1,
						'LastUser'          => $this->session->userdata("username")
					 );
					 $this->transaction['update_customer']['data'][] = $data_customer;
					 $this->transaction['update_customer']['CustomerCode'][] = $customer_code;
					 
					 /*
						Update pordetail for status dp for
						jika dp used dan dp balance tidak sama maka status dp for berubah jadi 1
					*/
					if($Select_DP != " "){
						$status_dp_for  = $this->m_sales_receipt->get_sordetail_dp_invoice_or_return($customer_code, $Select_DP, 1);
						foreach($status_dp_for as $row_dp_for){
							$DPUsed 				= $row_dp_for->DPUsed; 
							$SaldoDPBalance 		= $row_dp_for->SaldoDPBalance;
							$SOrdDetailDPID 		= $row_dp_for->SOrdDetailDPID;
							$IsEdit 				= 1;
							
							$update_dp_for = array(
								'IsEdit' 			=> $IsEdit
							);
							$this->transaction['update_dp']['data'][] = $update_dp_for;
							$this->transaction['update_dp']['CustomerCode'][] = $customer_code;
							$this->transaction['update_dp']['SOrdDetailDPID'][] = $SOrdDetailDPID;
							$this->transaction['update_dp']['Select_DP'][] = $Select_DP;
						}
					}
					/*========================End===================================*/
							
					$data_pi = array (			
						'TransStatus'   => 1,
						'LastUser' 		=> $this->session->userdata("username")
					);
					$this->transaction['update_pi']['data'][] = $data_pi;
                	$this->transaction['update_pi']['InvoiceNumber'][] = $invoice_number;
				}
				
				/*
					Update Invoice Payment table
				*/
				$data_ppay_detail   = $this->m_sales_receipt->get_receipt_detail($invoice_number, $txt_srec_no);
				
				foreach($data_ppay_detail as $row_detail){
					$inv_payment_id     = $row_detail->InvoicePaymentID;
					$payment_currency   = $bank_curr_code == 'IDR' ? $row_detail->SRecCurrency : $row_detail->SRecCurrency * $bank_curr_rate;
					
					$inv_disc_date  = empty($row_detail->SRecDiscDate) ? null: date("Y-m-d",strtotime($row_detail->SRecDiscDate));
					$data_payment   = $this->m_sales_receipt->get_receipt_by_id($inv_payment_id);

					$payment_update = array(
						'InvoiceOwing'          => $data_payment[0]->InvoiceOwing + ($row_detail->SRecDPUsed + $row_detail->SRecDiscount + $row_detail->SrecRounded + $row_detail->SRecAmount),
						'ReceiptDiscDate'       => $inv_disc_date,
						'ReceiptDiscount'       => $data_payment[0]->ReceiptDiscount - $row_detail->SRecDiscount,
						'ReceiptDPUsed'         => $data_payment[0]->ReceiptDPUsed - $row_detail->SRecDPUsed,
						'ReceiptAmount'         => $data_payment[0]->ReceiptAmount - $row_detail->SRecAmount,
						'ReceiptTotal'          => $data_payment[0]->ReceiptTotal - $row_detail->SRecTotalAmnt,
						'ReceiptCurrency'       => $data_payment[0]->ReceiptCurrency - $row_detail->SRecCurrency,
						//'InvoiceCurrency'       => $data_payment[0]->InvoiceCurrency - $row_detail->SInvCurrency,
						'ReceiptRounded'        => $data_payment[0]->ReceiptRounded - $row_detail->SrecRounded,
					);
					
					$this->transaction['update_ireceipts']['data'][] = $payment_update;
                	$this->transaction['update_ireceipts']['InvoicePaymentID'][] = $inv_payment_id;
				}  
				/*==================End================================================================================================*/
			}
			
			//8. Update Approval Finished for update Journal
			 $data_pp = array (
				'TransStatus'       => 4,						
				'AppLevel1Status'   => 0,
				'AppLevel1Code'     => NULL,
				'AppLevel1Date'     => NULL,	
				'AppFinished'       => 0, 
				'LastUser'          => $this->session->userdata("username")
			);
			$this->transaction['update_receipts']['data'] = $data_pp;
            $this->transaction['update_receipts']['SRecNumber'] = $txt_srec_no;
					
			$result_approve = $this->m_sales_receipt->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_srec_no);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_srec_no);
            }
             //==================================end====================================================== 
			echo json_encode($result);
		}
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            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_receipt->get_all_print($data_filter);
		
        $this->load->view('v_header');
        $this->load->view('sales/sales_receipt/v_preview_salesreceipt', $data);	
        $this->load->view('v_footer');	
    }
	/*=====================end===============================================*/
	
    /*================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_receipt->get_all();

        $this->load->view('v_header');
        $this->load->view('sales/sales_receipt/v_print_salesreceipt', $data);	
        $this->load->view('v_footer');	
    }
	/*========================end==========================================*/
	
    /*======================Function Print form============================*/ 
    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_receipt->get_detail_print($id);
            $data['list'] = $this->m_sales_receipt->get_detail_invoice_print($data['detail']->SRecNumber);		

            $this->load->view('v_header');
			if($data['detail']->PPnFiscalStatus == 1){
				$this->load->view('sales/sales_receipt/v_print_detail_salesreceipt_fiscal', $data);	
			}
			else{
				$this->load->view('sales/sales_receipt/v_print_detail_salesreceipt', $data);	
			}
            $this->load->view('v_footer');	
        }
    }
	/*=====================end=====================================================*/
	
    //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_receipt->get_detail($id);
            $data['list'] = $this->m_sales_receipt->get_detail_item($data['detail']->SRecNumber);		

            $this->load->view('v_header');
            $this->load->view('sales/sales_receipt/v_preview_detail_salesreceipt', $data);	
            $this->load->view('v_footer');	
        }
    }
	
	/*======================Function preview v_print_journal_salesreceipt============================*/
    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_receipt->get_detail($id);
        $data['list']   = $this->m_sales_receipt->get_journal_by_number($id);		

        $this->load->view('v_header');
        $this->load->view('sales/sales_receipt/v_print_journal_salesreceipt',$data);	
        $this->load->view('v_footer');	
    }
	/*======================end============================*/
	
	/*======================Function preview journal============================*/
    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_receipt->get_detail($id);
		
        $data['list']   = $this->m_sales_receipt->get_journal_by_number($id);		

        $this->load->view('v_header');
        $this->load->view('sales/sales_receipt/v_preview_journal_salesreceipt',$data);	
        $this->load->view('v_footer');	
    }
	/*======================end============================*/
	
	/*================Function Suspen Data========================================================*/
	public function suspend_data() {
        $srec_number = $this->input->post('id');
		
        $data = $this->m_sales_receipt->get_detail_for_suspend($srec_number);
        
		/*
			0=SI
			1=SO
		*/
		$detail_invoice = $this->m_sales_receipt->get_detail_invoice($srec_number);
		foreach($detail_invoice as $row_detail){
			if(($row_detail->Select_DP != "") || ($row_detail->Select_DP != NULL)){				
				if($row_detail->SRecInvoiceType == 0){
					if($row_detail->Receipt_DP > 0){
						$DPAccount  		= $this->m_account_journal->get_account_name('Uang Muka Penjualan', $data->CurrencyCode);
						$sordetail_dp_new 	= $this->m_sales_receipt->get_payment_detail_dp_suspend($data->CustomerCode, $row_detail->Select_DP, $DPAccount->AccountNumber);
							
						foreach($sordetail_dp_new as $row_dp_suspend){
							$DPUsed 		 		=  $row_dp_suspend->DPUsed;
							$POrdDetailDPID 		=  $row_dp_suspend->SOrdDetailDPID;
							$POrdNumber_DP 			=  $row_dp_suspend->SOrdNumber; 
							$total_pordetail 		=  $row_dp_suspend->AmountCurrency - $DPUsed;
							$total_pordetail_new 	=  $row_dp_suspend->SRecSaldoDebet - $DPUsed;
							
							if($data->CurrencyCode == 'IDR'){
								$dp_total_amount    = $data->BankCurrCode == 'IDR' ? $total_pordetail : $total_pordetail_new;
							}
							else{
								$dp_total_amount    = $data->BankCurrCode == 'IDR' ? $total_pordetail : $total_pordetail;
							}
					
							//if($Select_DP != $POrdNumber_DP){
								$update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => abs($dp_total_amount), 'IsEdit'=>0);
								$this->m_sales_receipt->update_sr_detail_dp_rec_before($update_sordstatus, $data->CustomerCode, $row_detail->Select_DP, $POrdDetailDPID);
							//}
						}
					}
				}
			}
		}
		
		/*
			Update lock status 
		*/
		$data_cust_dp     = array (
			'LockStatus'    => 0,
			'LastUser'      => $this->session->userdata("username")
		);
		$this->m_customer->update($data_cust_dp, $data->CustomerCode);
		/*===============End============================================*/
		
		$data_update    = array (			
			'TransStatus'   => 3,
			'LastUser'      => $this->session->userdata("username")
		);
		
		/*===========Update saler recipt trans status=======================*/
		$this->m_sales_receipt->update($data_update, $srec_number);
		/*==================end=======================================*/
        
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$result['status']       = FALSE;
			$result['message']  = get_notification('suspend', 0);
		}
		else {
			$this->db->trans_commit();
			$result['status'] 	= TRUE;
			$result['message']  = get_notification('suspend', 1);
		}
        echo json_encode($result);
    }
	/*================================End==============================================================*/
	
    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('SRecNumber', $Number);} 
		if($Desc != ""){$this->db->like('SRecDesc', $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('TransStatus',array(0,1,4,5,6,7)); 
		}
		
		
		if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where('at_salesreceipt.SRecDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_salesreceipt.SRecDate <=', date("Y-m-d", strtotime($DateTo))); 
			}
        }
		/*==========================end=================================================================*/
		
		$count_data = $this->db->count_all_results('at_salesreceipt');
		$offset 	= $count_data - ($rows * $page);
		if($offset > 0){
			$rows = $rows;
		}
		else{
			$rows = $count_data - ($rows*($page-1));
		}
		/*========================end=======================================*/
		$result = $this->m_sales_receipt->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(
				'BranchName' 		=>	$result[$i]->BranchName, 
				'CustomerName' 		=>	$result[$i]->CustomerName, 
				'TransNumber' 		=>	$result[$i]->SRecNumber,
				'SRecDate' 			=>	$result[$i]->SRecDate, 
				'SRecAmountCurr' 	=>	$result[$i]->SRecTotalAmount, 
				'SRecDesc' 			=>	$result[$i]->SRecDesc, 
				'ReceiptStatus' 	=> 	$result[$i]->ReceiptStatus, 
				'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_item(){
        $customer_code        = $this->input->post('CustomerCode');
        $ppn_fiscal_status  = $this->input->post('PPnFiscalStatus');
		
        if(!empty($customer_code)){
            $result = $this->m_sales_invoice->get_detail_item_for_sr($customer_code, $ppn_fiscal_status);
			
            echo json_encode($result);
        }
        else{
            echo '[]';
        }
		//echo $this->db->last_query();
    }
	
    public function ajax_for_choose_invoice(){
        $CustomerCode = $this->input->post('cust_code');
        
        if(!empty($CustomerCode)){
            echo json_encode($this->m_sales_invoice->get_detail_item_for_sr($CustomerCode));
        }
        else{
            echo $CustomerCode;
        }
        
//        echo $this->db->last_query(); die();
    }
	
	public function ajax_for_choose_invoice_fiscal(){
        $CustomerCode = $this->input->post('cust_code');
        if(!empty($CustomerCode)){
            echo json_encode($this->m_sales_invoice->get_for_payment_fiscal($CustomerCode));
        }
        else{
            echo $CustomerCode;
        }
        
//        echo $this->db->last_query(); die();
    }

    
	public function ajax_item_for_edit(){
        $data['menu_link']  = $this->m_menu->get_menulink($this->menu_id);
        $invoice_number     = str_replace($data['menu_link'].'/ajax_item_for_edit/',"",$this->uri->uri_string());
	
        if(!empty($invoice_number)){
            $result = $this->m_sales_receipt->get_detail_invoice($invoice_number);
            echo json_encode($result);
        }
        else{
            echo '[]';
        }
		//echo $this->db->last_query();
    }
    
    public function ajax_sr_number(){
        $srec_date  = $this->input->post('SRec_Date') == '' ? date('d-m-Y') : $this->input->post('SRec_Date');        
        $bank_code  = $this->input->post('Bank_Code');        

        if(!empty($bank_code)){
            $result['status']   = true;
            $result['number']   = $this->m_sales_receipt->create_sr_number($srec_date, $bank_code);
        }
        else{
            $result['status']   = false;
            $result['number'] 	= '';
        }
        
        echo json_encode($result);		
    }

    public function ajax_bank_account(){
		$currency_code = $this->input->post('CurrencyCode');
        
        if(!empty($currency_code)){
           echo json_encode($this->m_sales_receipt->get_bank_account($currency_code));
        }
    }
    
	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();
    }
	
	function get_pordetail_dp_return(){
		 $CustomerCode 		= $this->input->post('customer_code');
		 $data_dp_payment 	= $this->m_sales_receipt->get_sordetail_dp_balance($CustomerCode);
         
		 $result['dp_customer'] 	= $data_dp_payment->DownPayment;
		 echo json_encode($result);
	}
	
	function get_pordetail_dp_return_partial(){
		 $CustomerCode 		= $this->input->post('customer_code');
		 $data_dp_payment 	= $this->m_sales_receipt->get_sordetail_dp_balance_invoice($CustomerCode);
         $result['dp_customer'] 			= $data_dp_payment->DownPayment;
		 $result['dp_customer_partial'] 	= $data_dp_payment->DownPayment_Partial;
		 echo json_encode($result);
	}
	
	/*
		Kemungkinan tidak terpakai
	*/
	function get_pordetail_dp_invoice(){
		 $CustomerCode = $this->input->post('customer_code');
		 $data_dp = $this->m_sales_receipt->get_sordetail_dp_balance_invoice($CustomerCode);
		 
		 if(empty($data_dp->DownPayment)){
		 	$result['status'] 		= true;
		 	$result['dp_customer_invoice'] 	= 0;
		 }
		 else{
		 	$result['status'] 		= true;
		 	$result['dp_customer_invoice'] 	= $data_dp->DownPayment;
		 }
		
         echo json_encode($result);
	}
	
	function get_sordetail_dp_new(){
		 $CustomerCode 	= $this->input->post('CustomerCode');
		 //$CurrencyCode 	= $this->input->post('CurrencyCode');
		 //$PordNumber 	= $this->input->post('POrdNumber');
		 $result 		= $this->m_sales_receipt->get_saldo_detail_dp_new($CustomerCode);
		 echo json_encode($result);
	}
	
	function get_sordetail_dp(){
		 $CustomerCode 	= $this->input->post('CustomerCode');
		 $CurrencyCode 	= $this->input->post('CurrencyCode');
		 $SOrdNumber 	= $this->input->post('SOrdNumber');
		 $SRecNumber 	= $this->input->post('SRecNumber');
		 $BankCurrCode	= $this->input->post('BankCurrCode');
		 
		 $Total_Balance = 0; 
		 $hasil 		= [];
		 $Summing_Array = array();
		 
		 $result 		= $this->m_sales_receipt->get_saldo_detail_dp_update($CustomerCode);
		 
		 foreach($result as $row_detail_dp){
			$get_detail = $this->m_sales_receipt->get_saldo_detail($row_detail_dp->SOrdDetailDPID, $CustomerCode, $SRecNumber);
			
			//echo $this->db->last_query();
			if($CurrencyCode == 'IDR'){
				if(empty($get_detail->AmountCurrency)){
					$DPUsed = 0;
				}
				else{
					$DPUsed    = $BankCurrCode == 'IDR' ? $get_detail->AmountCurrency : $get_detail->SRecSaldoDebet;
				}
			}
			else{
				if(empty($get_detail->AmountCurrency)){
					$DPUsed = 0;
				}
				else{
					$DPUsed    = $BankCurrCode == 'IDR' ? $get_detail->AmountCurrency : $get_detail->AmountCurrency;
				}
			}
			
			//echo 'DP SUM = '.$row_detail_dp->PaymentAmount_SUM;
		 	$Total_Balance = $row_detail_dp->PaymentAmount_SUM + $DPUsed;
			@$Summing_Array[$row_detail_dp->SOrdNumber]           += $Total_Balance;
		 }
		 
		 //print_r($Summing_Array);
		 foreach($Summing_Array as $key => $value){
			$hasil[] = array(
				'Status' 			=> 'No',
				'SOrdNumber' 		=> $key,
				'PaymentAmount_SUM' => $value
			);
		 }
		 $result['rows'] = $hasil;
		 echo json_encode($result);
	}
}