<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Wahyu
 *	Tanggal : 08-08-2014	
 *	Revisi 	: Fachri
 */
 
class Sales_return extends CI_Controller {
	// inisialisasi manual
	public $menu_id = 163;
	public $code = "Sales Return Number";
	public $name = "Sales Return";
	public $transaction 	= [];
	
    public function __construct() {
        parent::__construct();
		$this->load->helper('message');	
		$this->load->helper('status');			
		$this->load->helper('convert_date');
		$this->load->helper('approval');
		$this->load->helper('lables');
		$this->load->helper('custom_string_helper');
		
		$this->load->model('setup/m_branchinfo');
		//$this->load->model('m_employee');
		$this->load->model('m_customer');
		$this->load->model('m_inventories');
		$this->load->model('m_sales_invoice');
		$this->load->model('m_sales_return');
		$this->load->model('m_sales_quotation');
		$this->load->model('m_sales_receipt');
		$this->load->model('m_taxes');
		$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();
			}
		}
	}
	
	//Function Index
    public function index()	{	
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
            $arr_group_id           = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					$group_menu 	 = $this->session->userdata('group_menu');	
					// 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_return/v_salesreturn', $data);	
					$this->load->view('v_footer');		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
		
	}
	
	//Function Form Edit
	public function add() {
		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');
					// 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['date_now']  = date('d-m-Y');
					
					$data['taxes_ppn10']	= $this->m_taxes->get_by_code('PPN');
					//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_return/v_new_salesreturn', $data);
					$this->load->view('v_footer');
					//----------------------end--------------------------------------------------------		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
		
	}
	
	//Function Form Insert
	public function insert() {
		$detail 			= $this->input->post('detail');
		$detail 			= json_decode($detail);
		
		$txt_currency_code 	= $this->input->post('txt_currency_code');
		$txt_ppn_rate 		= $this->input->post('txt_ppn_rate');
		$hdn_ppn10_pcnt 	= $this->input->post('hdn_ppn10_pcnt');
		$cmb_customer		= $this->input->post('cmb_customer');
		$taxes_status		= $this->input->post('chk_taxtable')?$this->input->post('chk_taxtable'):0;
        $intax_status		= $this->input->post('chk_inclusive')?$this->input->post('chk_inclusive'):0;
		$txa_address		= $this->input->post('txa_address');
		$txa_ship_to		= $this->input->post('txa_ship_to');
		$txt_sr_date		= $this->input->post('txt_sr_date');
		$txt_si_no			= $this->input->post('txt_si_no');
		$txt_si_date		= date("Y-m-d", strtotime($this->input->post('txt_si_date')));
		
		/*=====================================return number==========================================*/
		$txt_sr_no  		= $this->m_sales_return->create_sret_number($txt_sr_date);
		/*==========================================================================================*/
		$txt_currency_rate  = $this->input->post('txt_currency_rate');
		$txt_fiscal_rate  	= $this->input->post('txt_fiscal_rate');
		$txa_description	= $this->input->post('txa_description');
		
		$txt_total_return 	= $this->input->post('txt_total_return_hide');
		$txt_total_amount 	= $this->input->post('txt_total_amount_hide');
		
		$txt_total_return_real 	= $this->input->post('txt_total_return');
		$txt_total_amount_real 	= $this->input->post('txt_total_amount');
		
		$ppn 				= $this->input->post('ppn_hide');
		$ppn_real 				= $this->input->post('ppn');
		
		$result_insert  	= 0;
		$TransStatus 		= 4; 
		
		$this->db->trans_begin();
		//cek suspended
		if(count($detail) > 0) {
			$data = array (
				'BranchCode'		=> $this->session->userdata('branch'),
				'CustomerCode' 		=> $cmb_customer,
				'SRetNumber'		=> $txt_sr_no,
				'Sretdate'			=> date("Y-m-d", strtotime($txt_sr_date)),	
				'SInvNumber'		=> $txt_si_no,
				'SInvDate'			=> $txt_si_date,
				
				'SRetDesc'			=> $txa_description,
				'SRetSubTotal'		=> $txt_total_return,
				'SRetTotalAmount'	=> $txt_total_amount,
				'BillingAddress' 	=> $txa_address,
				'ShippingAddress' 	=> $txa_ship_to,
				
				'CurrencyCode' 		=> $txt_currency_code,
				'CurrencyRate' 		=> $txt_currency_rate,
				'FiscalRate' 		=> $txt_fiscal_rate,
				'TransStatus'		=> $TransStatus,
				'SRetPPNPcnt' 		=> $hdn_ppn10_pcnt,
				'SRetPPNOut' 		=> $ppn,
				'SRetTaxesStatus' 	=> $taxes_status,
				'SRetInTaxStatus' 	=> $intax_status,
				'CreatedBy' 		=> $this->session->userdata("username"),
				'CreatedAt' 		=> date('Y-m-d'),
				'LastUser' 			=> $this->session->userdata("username")
			);
			// insert kedalam tabel group at_salesreturn
			
			$this->m_sales_return->insert($data);
			//$this->transaction['insert_group']['data'] = $data;
			//end
		
			foreach($detail as $row) {
				$detail_data = array(
					'SRetNumber' 		=> $txt_sr_no,
					'SInvNumber' 		=> $txt_si_no,
					'SInvDetailID' 		=> $row->SInvDetailID,
					'SRetDate' 			=> date("Y-m-d", strtotime($txt_sr_date)),
					'ItemCode' 			=> $row->ItemCode,
					'ItemQty'			=> $row->ItemQty,
					'ItemQtyRet'		=> $row->ItemQtyRet,
					'InvoiceQty'		=> $row->max_item,
					'ItemDesc' 			=> $row->ItemDesc,
					'itemUnit'			=> $row->ItemUnit,
					'ItemPrice'			=> $row->ItemPrice,
					'ItemPriceCogs' 	=> $row->ItemPriceCogs,
					'ItemAmountCogs' 	=> $row->ItemAmountCogs,
					'ItemAmount'		=> $row->Item_Amount_Hide,
					'SalesmanCode'		=> $row->SalesmanCode,
					'ItemCategoryID' 	=> $row->ItemCategoryID,
					'ItemCategoryCode' 	=> $row->ItemCategoryCode,
					'ItemTotalAmount' 	=> $row->Total_Amount_Hide,
					'AmountTax'			=> $row->ItemTax,
					'ItemType' 			=> $row->ItemType,
					'ItemDiscPcnt' 		=> $row->ItemDiscPcnt,
					'LastUser' 		    => $this->session->userdata("username")				
				);
				$this->m_sales_return->insert_detail($detail_data);
				//$this->transaction['insert_detail']['data'][] = $detail_data;
				
				/*$get_detail_si = $this->m_sales_return->get_detail_si($row->SInvDetailID);
				$detail_inv = array(
					'QtyBookReturn' => $row->ItemQty + $get_detail_si->QtyBookReturn
				);
				
				$this->m_sales_invoice->update_detail($detail_inv, $row->SInvDetailID);*/
				
				if($row->ItemType == 0){
					$AmountCogs 								= $row->ItemPriceCogs * $row->ItemQty;
				}
				else{
					$AmountCogs 								= 0;
				}
				@$ItemCategoryCode[$row->ItemCategoryID]    	+= round($row->Item_Amount_Hide, 2);
				@$ItemCategoryCodePPn[$row->ItemCategoryID]    	+= round($row->ItemTax,2);
				@$ItemCategoryid[$row->ItemCategoryID]    		+= $row->ItemAmount;
				@$ItemCategoryidCogs[$row->ItemCategoryID]    	+= $AmountCogs;
				@$ItemCategoryType[$row->ItemCategoryID]    	= $row->ItemType;
			}
			
			/*=======================================insert journal========================================*/
			$insert_jurnal = $this->insert_journal_debet_credit($ppn_real, $txt_total_return_real, $txt_total_amount_real, $txt_total_return, $txt_si_no, $ItemCategoryCodePPn, $txt_fiscal_rate, $ItemCategoryType, $txt_total_return, $ItemCategoryidCogs, $ItemCategoryid, $ItemCategoryCode, $txt_sr_no, $txa_description, $txt_currency_rate, $txt_currency_code, $txt_sr_date, $ppn);
			/*===================================end=========================================================*/
			
			//Update Si for LockedStatus is 1
            $data_sinv_group   = array (
				'LockStatus'      => 1,
				'LastUser' 		=> $this->session->userdata("username")
			);
			
			$this->m_sales_invoice->update($data_sinv_group, $txt_si_no);
            //$this->transaction['update_invoice_group']['data'] 			= $data_sinv_group;
			//$this->transaction['update_invoice_group']['SInvNumber']	= $txt_si_no;
			
			//$result_insert = $this->m_sales_return->insert_transaction_all($this->transaction);
			//$this->transaction 	= [];
			/*=============================trans roll back dan trans commit============================/*/
			
			/*=============================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, $txt_sr_no);
			}
			else {
				$this->db->trans_commit();
				$result['status'] 	= TRUE;
				$result['message']  = get_notification_transaksi($this->name, 'insert', 1, $txt_sr_no);
			}
			/*==================================end======================================================*/
		}
		else{
			//jika gagal 
			$result['status']   = false;
			$result['message']  = "Data gagal disimpan, karena tidak ada Item yang dipilih";  
			$this->db->trans_rollback();
		}
		echo json_encode($result);
	}
	
	
	function insert_journal_debet_credit($ppn_real, $txt_total_return_real, $txt_total_amount_real, $txt_total_return, $txt_si_no, $ItemCategoryCodePPn, $txt_fiscal_rate, $ItemCategoryType, $txt_total_return, $ItemCategoryidCogs, $ItemCategoryid, $ItemCategoryCode, $txt_sr_no, $txa_description, $txt_currency_rate, $txt_currency_code, $txt_sr_date, $ppn){
		//jurnal inventori
		
		$inventori_amount = 0;
		$inventori_currency = 0;
		foreach(@$ItemCategoryidCogs as $key => $value){
			if($ItemCategoryType[$key] == 0){
				$InventoriAccount  = $this->m_account_journal->get_cat_item_account('Inventory', $key ,'IDR');
				if($InventoriAccount == false) {$this->trans_rollback('preference','Item Inventory Account', 'IDR');} 
				
				$get_journal_return = $this->m_sales_return->get_journal_return_empty($InventoriAccount->AccountNumber, $txt_sr_no);
				$inventori_amount     	= $txt_currency_code == 'IDR' ? doubleval($value) : doubleval($value);
				$inventori_currency   	= doubleval($value / $txt_currency_rate);
					
				if(empty($get_journal_return->SRetAccountNumber)){
					$journal_inventori   = array(
						'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
						'SRetNumber'                => $txt_sr_no,
						'SRetDesc'                  => $txa_description,
						'SRetAccountNumber'         => $InventoriAccount->AccountNumber,
						'SRetSaldoDebet'            => $inventori_amount,
						'SRetSaldoCredit'           => 0,
						'AmountCurrency'            => $inventori_currency,
						'SRetSignStatus'            => 0, 
						'ReturnStatus' 				=> 0,
						//'ItemCategoryID'            => 'Hutang Dagang',
						'LastUser'                  => $this->session->userdata("username")	
					);
					
					$this->m_sales_return->insert_journal($journal_inventori);
				}
				else{
					$inventori_amount      = $inventori_amount + $get_journal_return->SRetSaldoDebet;
					$inventori_currency    = $inventori_currency + $get_journal_return->AmountCurrency;
					
					$journal_inventori   = array(
						'SRetSaldoDebet'            => $inventori_amount,
						'SRetSaldoCredit'           => 0,
						'AmountCurrency'            => $inventori_currency,
					);
					
					$this->m_sales_return->update_journal($journal_inventori, $get_journal_return->SRetJournalID);
				}
			}
		}
		
		$cogs_amount = 0;
		$cogs_currency = 0;
		foreach(@$ItemCategoryidCogs as $key => $value){
			if($ItemCategoryType[$key] == 0){
				$CogsAccount  = $this->m_account_journal->get_cat_item_account('COGS', $key ,'IDR');
				if($CogsAccount == false) {$this->trans_rollback('preference','COGS Account', $txt_currency_code);} 
				
				$get_journal_return = $this->m_sales_return->get_journal_return_empty($CogsAccount->AccountNumber, $txt_sr_no);
				$total_value = $value;
					//Journal Inventori Account - inventori Pembelian
				$cogs_amount     = $txt_currency_code == 'IDR' ? doubleval($total_value) : doubleval($total_value);
				$cogs_currency   = doubleval($value / $txt_currency_rate);
					
				if(empty($get_journal_return->SRetAccountNumber)){
					$journal_cogs   = array(
						'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
						'SRetNumber'                => $txt_sr_no,
						'SRetDesc'                  => $txa_description,
						'SRetAccountNumber'         => $CogsAccount->AccountNumber,
						'SRetSaldoDebet'            => 0,
						'SRetSaldoCredit'           => $cogs_amount,
						'AmountCurrency'            => $cogs_currency,
						'SRetSignStatus'            => 1, 
						//'ItemCategoryID'            => 'Hutang Dagang',
						'LastUser'                  => $this->session->userdata("username")	
					);
					
					$this->m_sales_return->insert_journal($journal_cogs);
				}
				else{
					$cogs_amount      = $cogs_amount + $get_journal_return->SRetSaldoCredit;
					$cogs_currency    = $cogs_currency + $get_journal_return->AmountCurrency;
					
					$journal_cogs   = array(
						'SRetSaldoDebet'            => 0,
						'SRetSaldoCredit'           => $cogs_amount,
						'AmountCurrency'            => $cogs_currency,
					);
					
					$this->m_sales_return->update_journal($journal_cogs, $get_journal_return->SRetJournalID);
				}
			}
		}
		//end jurnal cogs
		
		//jurnal return
		$return_amount 			= 0;
		$return_currency 		= 0;
		$amount_round_item 		= 0;
		$amount_noround_item 	= 0;
		
		foreach(@$ItemCategoryid as $key => $value){
			if($ItemCategoryType[$key] == 0){
				$ReturnAccount  = $this->m_account_journal->get_cat_item_account('SalesReturn', $key ,$txt_currency_code);
				if($ReturnAccount == false) {$this->trans_rollback('preference','Sales Return Account', $txt_currency_code);} 
				
				$get_journal_return = $this->m_sales_return->get_journal_return_empty($ReturnAccount->AccountNumber, $txt_sr_no);
				
				$return_amount     = $txt_currency_code == 'IDR' ? doubleval(($value)) : doubleval(($value)) * $txt_currency_rate;
				$return_currency   = doubleval(($value));
				
				$journal_return   = array(
						'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
						'SRetNumber'                => $txt_sr_no,
						'SRetDesc'                  => $txa_description,
						'SRetAccountNumber'         => $ReturnAccount->AccountNumber,
						'SRetSaldoDebet'            => $return_amount,
						'SRetSaldoCredit'           => 0,
						'AmountCurrency'            => $return_currency,
						'SRetSignStatus'            => 0, 
						//'ItemCategoryID'            => 'Hutang Dagang',
						'LastUser'                  => $this->session->userdata("username")	
					);
					$this->m_sales_return->insert_journal($journal_return);
						
			
				
				$amount_noround_item 		+= $value;
				$amount_round_item 			+= round($value,2);
			}
		}
		//end jurnla return
		
		/*
			jurnal return servis/expense UnbilledAccount
			sesuai jurnal yang ada di invoice
		*/
		$servis_amount 			= 0;
		$servis_currency 		= 0;
		$amount_round_expense 	= 0;
		$amount_noround_expense = 0;
		
		foreach(@$ItemCategoryid as $key => $value){
			if($ItemCategoryType[$key] != 0){
				//servis
				$SalesExpense    	= $this->m_account_journal->get_sys_service_account('SalesExpense', 'IDR'); // Jasa / Service
				
				if($SalesExpense==false){
					$this->trans_rollback('journal','Sales Exepense Account', $txt_currency_code);
				}
				else{
					$servis_amount     		= $txt_currency_code == 'IDR' ? doubleval(($value)) : doubleval(($value)) * $txt_currency_rate;
					$servis_currency   		= doubleval(($value));
				
					$get_journal_return = $this->m_sales_return->get_journal_return_empty($SalesExpense->AccountNumber, $txt_sr_no);
					if(empty($get_journal_return->SRetAccountNumber)){
						
						$journal_Unbilled   = array(
							'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
							'SRetNumber'                => $txt_sr_no,
							'SRetDesc'                  => $txa_description,
							'SRetAccountNumber'         => $SalesExpense->AccountNumber,
							'SRetSaldoDebet'            => round($servis_amount, 2),
							'SRetSaldoCredit'           => 0,
							'AmountCurrency'            => round($servis_currency,2),
							'SRetSignStatus'            => 1, 
							'LastUser'                  => $this->session->userdata("username")	
						);
						$this->m_sales_return->insert_journal($journal_Unbilled);
					}
					else{
						$servis_amount      = $servis_amount + $get_journal_return->SRetSaldoDebet;
						$servis_currency    = $servis_currency + $get_journal_return->AmountCurrency;
						
						$journal_Unbilled   = array(
							'SRetSaldoDebet'            => round($servis_amount, 2),
							'SRetSaldoCredit'           => 0,
							'AmountCurrency'            => round($servis_currency, 2),
						);
						
						$this->m_sales_return->update_journal($journal_Unbilled, $get_journal_return->SRetJournalID);
					}
					
					$amount_noround_expense 	+= $servis_amount;
					$amount_round_expense += round($value,2);
				}
				//end
			}
		}
		/*=============================end==============================================*/
		
		//Journal Return PPn Account - PPn Masukan
		if($ppn > 0){
			$PPnAccount     = $this->m_account_journal->get_sys_sales_account('SalesTaxable', 'IDR'); // PPn Masukan
			if($PPnAccount == false) {$this->trans_rollback('journal','PPn Account', $txt_currency_code);} 
		
			$PPn_amount     = $txt_currency_code == 'IDR' ? doubleval($ppn) : doubleval($ppn) * $txt_fiscal_rate;
			$PPn_currency   = doubleval(round($ppn,2));
			
			$journal_ppn    = array(
				'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
				'SRetNumber'                => $txt_sr_no,
				'SRetDesc'                  => $txa_description,
				'SRetAccountNumber'         => $PPnAccount->AccountNumber,
				'SRetSaldoDebet'            => $PPn_amount,
				'SRetSaldoCredit'           => 0,
				'AmountCurrency'            => $PPn_currency,
				'SRetSignStatus'            => 1, 
				//'ItemCategoryID'            => 'Hutang Dagang',
				'LastUser'                  => $this->session->userdata("username")	
			);
			
			$this->m_sales_return->insert_journal($journal_ppn);
		}
		//end
		
		$advance_amount 	= 0;
		$advance_currency 	= 0;
		$sum_advanced 		= 0;
		
		$AdvanceAccount = $this->m_account_journal->get_sys_sales_account('AdvanceSales', $txt_currency_code);          
		if($AdvanceAccount == false) {$this->trans_rollback('preference','Advance Sales Account', $txt_currency_code);} 
		
		$get_journal_return = $this->m_sales_return->get_journal_return_empty($AdvanceAccount->AccountNumber, $txt_sr_no, $txt_si_no);
		
		$advance_amount     = $txt_currency_code == 'IDR' ? doubleval($txt_total_amount_real) : ((doubleval($txt_total_return_real) * $txt_currency_rate) + ((doubleval($ppn_real) * $txt_fiscal_rate)));
		$advance_currency   = doubleval($txt_total_amount_real);
				
		$journal_advance   = array(
			'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
			'SRetNumber'                => $txt_sr_no,
			'SRetDesc'                  => $txa_description,
			'SRetAccountNumber'         => $AdvanceAccount->AccountNumber,
			'SRetSaldoDebet'            => 0,
			'SRetSaldoCredit'           => $advance_amount,
			'AmountCurrency'            => $advance_currency,
			'SRetSignStatus'            => 0, 
			//'ItemCategoryID'            => 'Hutang Dagang',
			'SInvNumber' 				=> $txt_si_no,
			'LastUser'                  => $this->session->userdata("username")	
		);
		
		$this->m_sales_return->insert_journal($journal_advance);
		
		$sum_advanced = $advance_amount;
		
		/*
			Beban Pembulatan Auto
		*/
		$amount_noround_item_real = $amount_noround_item * $txt_currency_rate;
		$Ppn_real 			= empty($PPn_amount) ? 0 : $PPn_amount;
		$amoun_expensereal 	= empty($amount_noround_expense) ? 0 : $amount_noround_expense;
		$advanced_ppnreal 	= empty($sum_ppn_advanced) ? 0 : $sum_ppn_advanced;
		
		$Total_all_amount 	= (($amount_noround_item_real + $PPn_amount + $amount_noround_expense) - ($sum_advanced));
		
		if(($txt_total_return - round($txt_total_return,2)) != 0){
			if($txt_total_return < round($txt_total_return,2)){
				$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
				if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $txt_currency_code);}
				
				$journal_beban    = array(
					'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
					'SRetNumber'                => $txt_sr_no,
					'SRetDesc'                  => $txa_description,
					'SRetAccountNumber'         => $BebanAccountAuto->AccountNumber,
					'SRetSaldoDebet'            => abs($Total_all_amount),
					'SRetSaldoCredit'           => 0,
					'AmountCurrency'            => 0,
					'SRetSignStatus'            => 0, 
					//'ItemCategoryID'            => 'Hutang Dagang',
					'LastUser'                  => $this->session->userdata("username")	
				);
				
				$this->m_sales_return->insert_journal($journal_beban);
			}
			else{
				$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
				if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $txt_currency_code);}
				
				$journal_beban    = array(
					'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
					'SRetNumber'                => $txt_sr_no,
					'SRetDesc'                  => $txa_description,
					'SRetAccountNumber'         => $BebanAccountAuto->AccountNumber,
					'SRetSaldoDebet'            => 0,
					'SRetSaldoCredit'           => abs($Total_all_amount),
					'AmountCurrency'            => 0,
					'SRetSignStatus'            => 1, 
					//'ItemCategoryID'            => 'Hutang Dagang',
					'LastUser'                  => $this->session->userdata("username")	
				);
				
				$this->m_sales_return->insert_journal($journal_beban);
			}
		}
		
		/*if($ppn > 0){
			$Total_ppn_amount 	= ($ppn - round($ppn,2)) * $txt_fiscal_rate;
			if($Total_ppn_amount != 0){
				if($ppn < round($ppn,2)){
					$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
					if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $txt_currency_code);}
					
					$journal_beban_ppn    = array(
						'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
						'SRetNumber'                => $txt_sr_no,
						'SRetDesc'                  => $txa_description,
						'SRetAccountNumber'         => $BebanAccountAuto->AccountNumber,
						'SRetSaldoDebet'            => abs($Total_ppn_amount),
						'SRetSaldoCredit'           => 0,
						'AmountCurrency'            => 0,
						'SRetSignStatus'            => 0, 
						//'ItemCategoryID'            => 'Hutang Dagang',
						'LastUser'                  => $this->session->userdata("username")	
					);
					
					$this->m_sales_return->insert_journal($journal_beban_ppn);
				}
				else{
					$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
					if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $txt_currency_code);}
					
					$journal_beban_ppn    = array(
						'SRetDate'                  => date("Y-m-d", strtotime($txt_sr_date)),
						'SRetNumber'                => $txt_sr_no,
						'SRetDesc'                  => $txa_description,
						'SRetAccountNumber'         => $BebanAccountAuto->AccountNumber,
						'SRetSaldoDebet'            => 0,
						'SRetSaldoCredit'           => abs($Total_ppn_amount),
						'AmountCurrency'            => 0,
						'SRetSignStatus'            => 1, 
						//'ItemCategoryID'            => 'Hutang Dagang',
						'LastUser'                  => $this->session->userdata("username")	
					);
					
					$this->m_sales_return->insert_journal($journal_beban_ppn);
				}
			}
		}*/
		/*=====================End=============================*/
	}
	
	//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);
					
					// inisialisasi additional parameter
					$id = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
					$data['detail'] = $this->m_sales_return->get_detail($id);
					$data['taxes_ppn10']	= $this->m_taxes->get_by_code('PPN');
					
					//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_return/v_edit_salesreturn',$data);
						$this->load->view('v_footer');
					}
					//----------------------end--------------------------------------------------------		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
	}
	
	// Function Update
	public function update() {
	  	$detail 			= $this->input->post('detail');
		$cmb_customer		= $this->input->post('cmb_customer');
		$txt_sr_no			= $this->input->post('txt_sr_no');
		$txt_sr_date		= $this->input->post('txt_sr_date');
		$txt_si_no			= $this->input->post('txt_si_no');
		$txa_description	= $this->input->post('txa_description');
		$txt_total_return 	= $this->input->post('txt_total_return_hide');
		$txt_total_amount 	= $this->input->post('txt_total_amount_hide');
		
		$txt_total_return_real 	= $this->input->post('txt_total_return');
		$txt_total_amount_real 	= $this->input->post('txt_total_amount');
		
		$txt_currency_code 	= $this->input->post('txt_currency_code');
		
		$ppn 				= $this->input->post('ppn_hide');
		$ppn_real 			= $this->input->post('ppn');
		
		$txt_currency_rate  = $this->input->post('txt_currency_rate');
		$txt_fiscal_rate  	= $this->input->post('txt_fiscal_rate');
		$txt_ppn_rate  		= $this->input->post('txt_ppn_rate');
		
		$taxes_status		= $this->input->post('chk_taxtable')?$this->input->post('chk_taxtable'):0;
        $intax_status		= $this->input->post('chk_inclusive')?$this->input->post('chk_inclusive'):0;
		$detail 			= json_decode($detail);
		$txa_address		= $this->input->post('txa_address');
		$txa_ship_to		= $this->input->post('txa_ship_to');
		
		//cek suspended
		$detail_id			= $this->input->post('detail_id');
        $detail_id			= json_decode($detail_id);
		
		$detail_qty			= $this->input->post('detail_qty');
        $detail_qty			= json_decode($detail_qty);
		$branch_code 		= $this->input->post('branch_code');
		
		$this->db->trans_begin();
		if(count($detail) > 0) {
			$this->m_sales_return->delete_journal($txt_sr_no);
			
			$data = array (
				'BranchCode'		=> $branch_code,
				'CustomerCode' 		=> $cmb_customer,
				'SRetNumber'		=> $txt_sr_no,
				'Sretdate'			=> date("Y-m-d", strtotime($txt_sr_date)),	
				'SInvNumber'		=> $txt_si_no,
				'SRetDesc'			=> $txa_description,
				'SRetSubTotal'		=> $txt_total_return,
				
				'BillingAddress' 	=> $txa_address,
				'ShippingAddress' 	=> $txa_ship_to,
				
				'SRetTotalAmount'	=> $txt_total_amount,
				'CurrencyCode' 		=> $txt_currency_code,
				'SRetPPNPcnt' 		=> $txt_ppn_rate,
				'SRetPPNOut' 		=> $ppn,
				'SRetTaxesStatus' 	=> $taxes_status,
				'SRetInTaxStatus' 	=> $intax_status,
				'CurrencyRate' 		=> $txt_currency_rate,
				'FiscalRate' 		=> $txt_fiscal_rate,
				'AppFinished' 		=> 2,
				'LastUser' 			=> $this->session->userdata("username")
			);
				
			// insert kedalam tabel group at_salesreturn
			
			//$this->transaction['update_group']['data']= $data;
			//$this->transaction['update_group']['SRetNumber'] = $txt_sr_no;
			
			$this->m_sales_return->update($data, $txt_sr_no);
			//end
			
			foreach($detail as $row) {
				$detail_data = array(
					'SRetNumber' 		=> $txt_sr_no,
					'SInvNumber' 		=> $txt_si_no,
					'SInvDetailID' 		=> $row->SInvDetailID,
					'SRetDate' 			=> date("Y-m-d", strtotime($txt_sr_date)),
					'ItemCode' 			=> $row->ItemCode,
					'itemQty'			=> $row->ItemQty,
					'ItemQtyRet'		=> $row->ItemQtyRet,
					'itemUnit'			=> $row->ItemUnit,
					'ItemPrice'			=> $row->ItemPrice,
					'ItemPriceCogs' 	=> $row->ItemPriceCogs,
					'ItemAmountCogs' 	=> $row->ItemAmountCogs,
					'ItemAmount'		=> $row->Item_Amount_Hide,
					'SalesmanCode'		=> $row->SalesmanCode,
					'ItemCategoryID' 	=> $row->ItemCategoryID,
					'ItemCategoryCode' 	=> $row->ItemCategoryCode,
					'ItemTotalAmount' 	=> $row->Total_Amount_Hide,
					'AmountTax'			=> $row->ItemTax,
					'LastUser' 		    => $this->session->userdata("username")				
				);
				
				$this->m_sales_return->update_detail($detail_data, $row->SRetDetailID);
				
				if($row->ItemType == 0){
					$AmountCogs 								= $row->ItemPriceCogs * $row->ItemQty;
				}
				else{
					$AmountCogs 								= 0;
				}
				
				@$ItemCategoryCode[$row->ItemCategoryID]    	+= round($row->Item_Amount_Hide, 2);
				@$ItemCategoryCodePPn[$row->ItemCategoryID]    	+= round($row->ItemTax,2);
				@$ItemCategoryid[$row->ItemCategoryID]    		+= $row->Item_Amount_Hide;
				@$ItemCategoryidCogs[$row->ItemCategoryID]    	+= $AmountCogs;
				@$ItemCategoryType[$row->ItemCategoryID]    	= $row->ItemType;
				
			}
			
			if(count($detail_id)>0){
				foreach ($detail_id as $SRetDetailID) {
					$this->m_sales_return->delete_detail_by_sretdetail_id($SRetDetailID);
					
					/*$get_detail_si = $this->m_sales_return->get_detail_si($detail_qty[0]);
					$detail_inv = array(
						'QtyBookReturn' => $detail_qty[1] + $get_detail_si->QtyBookReturn
					);
					
					//insert kedalam tabel sretdetail
					
					$this->m_sales_invoice->update_detail($detail_inv, $detail_qty[0]);*/
				}	
			}
			
			
			/*=======================================insert journal========================================*/
			$this->insert_journal_debet_credit($ppn_real, $txt_total_return_real, $txt_total_amount_real,$txt_total_return, $txt_si_no, $ItemCategoryCodePPn, $txt_fiscal_rate, $ItemCategoryType, $txt_total_return, $ItemCategoryidCogs, $ItemCategoryid, $ItemCategoryCode, $txt_sr_no, $txa_description, $txt_currency_rate, $txt_currency_code, $txt_sr_date, $ppn);
			/*===================================end=========================================================*/
			
			//kondisi dimana jika dia berhasil
			//$result_update = $this->m_sales_return->update_transaction_all($this->transaction);
			//$this->transaction 	= [];
			
			/*=============================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, 'update', 0, $txt_sr_no);
			}
			else {
				$this->db->trans_commit();
				$result['status'] 	= TRUE;
				$result['message']  = get_notification_transaksi($this->name, 'update', 1, $txt_sr_no);
			}
			/*==================================end======================================================*/
		}
		else{
			//jika gagal 
			$result['status']   = false;
			$result['message']  = get_notification_transaksi($this->name, 'Update', 0, $txt_sr_no);
			$this->db->trans_rollback();
			die();  
		}
		
		echo json_encode($result);
	}
	
	function reverse_data_detail() {
		try{
			$txt_sret_no  		= $this->input->post('txt_sr_no');
			$txt_si_no  		= $this->input->post('txt_si_no');
			$detail_post 		= $this->input->post('detail');
            $detail 			= json_decode($detail_post);
			$branch_code 		= $this->session->userdata("branch");
			$date_transaction 	= check_end_periode($txt_sret_no);
			 
			$get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);//Check Periode End
			 
			if ($get_end_periode) {
				throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
			}
			
			foreach ($detail as $row_detail) {
				
				/*
					Check Item Or Expense
					0 = Item
					1 = Expense
				*/
				$ItemQty 		= $row_detail->ItemQty;
				$QtyInvoice 	= $row_detail->max_item_finis;
				$ItemCode 		= $row_detail->ItemCode;
				$ItemPrice 		= $row_detail->ItemPrice;
				$ItemPriceCogs 	= $row_detail->ItemPriceCogs;
			
				if ($row_detail->ItemType == 0) {
					/*
                      Check Adjustment
                     */
                    $item_lock_status = $this->m_inventories->get_inventori_by_item($ItemCode, $branch_code);
                    if ($item_lock_status->LockStatus == 1) {
                        throw new Exception(('Tidak bisa dilakukan proses Reverse, karena item ' . $row_detail->ItemCode . ' pada listing sedang dilakukan proses Adjustment')); //item adjust
                    }
                    /* =================END============================== */
					
					$total_inventori 		= $item_lock_status->ItemQty - $ItemQty;
					$item_value_inventori 	= $item_lock_status->ItemAverage * $item_lock_status->ItemQty;
					$item_value_do 			= $ItemPriceCogs * $ItemQty;
					
					$item_average 			= ($item_value_inventori - $item_value_do) / $total_inventori;
					$item_value_new 		= ($item_average * $total_inventori);
					/*$item_value  	 = $get_inventori_code->ItemAverage * $total_inventori;
					$item_average	 = $item_value / $total_inventori;*/
					
					$data_inventori = array(
						'ItemQty' 		=> $total_inventori,
						'ItemValue' 	=> $item_value_new,
						'ItemAverage' 	=> $item_average
					);
					
					$this->transaction['update_inventory']['data'][] = $data_inventori;
                	$this->transaction['update_inventory']['ItemCode'][] = $ItemCode;
				}
				
				$get_detail_si  = $this->m_sales_return->get_detail_si($row_detail->SInvDetailID);
				$detail_inv = array(
					'QtyReturn' 	=> $get_detail_si->QtyReturn - $row_detail->ItemQty,
					//'QtyBookReturn' => $get_detail_si->QtyBookReturn - $row_detail->ItemQty
				);
				$this->transaction['update_qty_invoice']['data'][] = $detail_inv;
                $this->transaction['update_qty_invoice']['SInvDetailID'][] = $row_detail->SInvDetailID;
			}
			
			$get_sordetail_dp = $this->m_sales_return->get_detail_invoice($txt_sret_no);
			if(!empty($get_sordetail_dp->Invoice_Number)){
				$NoSalesReceipt = $get_sordetail_dp->SRecNumber;
				throw new Exception(('Tidak bisa dilakukan proses Reverse, karena Down Payment dari no transaksi ' . $txt_sret_no . ' sudah dipakai di Sales Receipts'. $NoSalesReceipt .', silahkan Reverse terlebih dahulu Sales Receipts')); //item adjust
			}
			
			$this->transaction['delete_sordetaildp']['SOrdNumber'] = $txt_sret_no;
			
			$data_sret = array(
                'TransStatus' => 4,
                'AppLevel1Status' => 0,
                'AppLevel1Code' => NULL,
                'AppLevel1Date' => NULL,
                'AppFinished' => 0,
                'LastUser' => $this->session->userdata("username")
            );
            $this->transaction['update_sret']['data'] = $data_sret;
            $this->transaction['update_sret']['SRetNumber'] = $txt_sret_no;
			
			//Update Si for LockedStatus is 1
			$data_sinv_group   = array (
				'LockStatus'      => 1,
				'LastUser' 		=> $this->session->userdata("username")
			);
			$this->transaction['update_invoice']['data'] = $data_sinv_group;
            $this->transaction['update_invoice']['SInvNumber'] = $txt_si_no;
			
			$result_approve = $this->m_sales_return->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_sret_no);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_sret_no);
            }
            /* ==================================end====================================================== */
			echo json_encode($result);
		}
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
	}
	
	// Function Approval Manager
	public function approval_mgr() {
		/*=======================deklar variabel========================================================*/
		$id 				= $this->input->post('id');
		$txt_sr_date		= date('Y-m-d', strtotime($this->input->post('txt_sr_date')));
		$branch_code 		= $this->input->post('branch_code');
		$cmb_customer 		= $this->input->post('cmb_customer');
		$txt_total_return 	= $this->input->post('txt_total_return_hide');				
		$txt_total_amount 	= $this->input->post('txt_total_amount_hide');
		
		$FiscalRate 		=  $this->input->post('txt_fiscal_rate');
		$CurrencyRate 		=  $this->input->post('txt_currency_rate');
		
		$CurrencyCode 		= $this->input->post('txt_currency_code');
		$SInvnumber 		= $this->input->post('txt_si_no');
		$SInvDate 			= $this->input->post('txt_si_date');
		$ppn 				= $this->input->post('ppn_hide');
		
		$CategoryIDCode     = array();
		$PPNCategoryAmount  = array();
		$total_amount 		= 0;
		
		$get_inventori_by_si = $this->m_sales_return->get_detail_item($id);
		/*=================================end==============================================================*/
		$this->db->trans_begin();
		$data = array (				
			'TransStatus' 		=> 2,
			'AppFinished'		=> 1,
			'AppLevel1Status' 	=> 1,
			'AppLevel1Code'     => $this->session->userdata("username"),
			'AppLevel1Date'		=> date("Y-m-d"),	
			'LastUser' 			=> $this->session->userdata("username")
		);
		
		$this->m_sales_return->update($data, $id);
		
		//update ke inventori
		foreach($get_inventori_by_si as $row_detail){
			/*====================================deklar variabel dari detail================================*/
			$get_detail_si  = $this->m_sales_return->get_detail_si($row_detail->SInvDetailID);
			$ItemQty 		= $row_detail->ItemQty;
			$QtyInvoice 	= $row_detail->max_item_finis;
			$ItemCode 		= $row_detail->ItemCode;
			$ItemPrice 		= $row_detail->ItemPrice;
			$ItemPriceCogs 	= $row_detail->ItemPriceCogs;
			/*===================================end========================================================*/
			
			$detail_inv = array(
				'QtyReturn' 	=> $get_detail_si->QtyReturn + $row_detail->ItemQty,
				//'QtyBookReturn' => $get_detail_si->QtyBookReturn - $row_detail->ItemQty
			);
			
			/*==========================insert kedalam tabel sretdetail========================================*/
			$this->m_sales_invoice->update_detail_for_return($detail_inv, $row_detail->SInvDetailID);
			/*=================================end=============================================================*/
			
			/*=======================cek lock status adjustment=================================================*/ 
			$get_inventori_code = $this->m_inventories->get_inventori_by_item($row_detail->ItemCode, $branch_code);
			/*=========================end======================================================================*/
			
			/*==============================cek jika ada item sedang daam adjust==================================================*/
			if(!empty($get_inventori_code->ItemCode)){
				if($get_inventori_code->LockStatus == 1){
					$this->db->trans_rollback();
					$result['status']   = false;
					$result['message']  = "Produk ".$get_inventori_code->ItemCode.", sedang dalam proses Adjustment.";
					
					echo json_encode($result);
					die();
				}
			}
			/*=========================================end===================================================================*/
			
			/*===============================================================================================================*/
			/*
				update inventori book, QTY dan Value
			*/
			if($row_detail->ItemType == 0){
				$total_inventori 		= $get_inventori_code->ItemQty + $ItemQty;
				$item_value_inventori 	= $get_inventori_code->ItemAverage * $get_inventori_code->ItemQty;
				$item_value_do 			= $ItemPriceCogs * $ItemQty;
				
				$item_average 			= ($item_value_inventori + $item_value_do) / $total_inventori;
				$item_value_new 		= ($item_average * $total_inventori);
				/*$item_value  	 = $get_inventori_code->ItemAverage * $total_inventori;
				$item_average	 = $item_value / $total_inventori;*/
				
				$data_inventori = array(
					'ItemQty' 		=> $total_inventori,
					'ItemValue' 	=> $item_value_new,
					'ItemAverage' 	=> $item_average
				);
				
				$this->m_inventories->update_average($data_inventori, $ItemCode, $branch_code);
			}
			/*==================end==========================================================================================*/
			
			/*================================================================================================================*/
			/*
				grouping amount by kategori
			*/
			@$CategoryAmount[$row_detail->ItemCategoryID] 		+= $row_detail->ItemAmount;
			@$PPNCategoryAmount[$row_detail->ItemCategoryID] 	+= $row_detail->AmountTax;
			@$CategoryIDCode[$row_detail->ItemCategoryID]       = $row_detail->ItemCategoryID;
			/*===========================================end=================================================================*/
			
		}
		//end
		
		/*=====================================update balance customer================================================*/
		$SaldoDPBalance = 0;
		$get_customer_saldo_dp = $this->m_customer->get_saldo_by_id($cmb_customer);
		foreach($get_customer_saldo_dp as $row_customer){
			$SaldoDPBalance = $row_customer->SaldoDPBalance;
			$total_dp_balance = $SaldoDPBalance + $txt_total_amount;
			
			$data_customer = array(
				'SaldoDPBalance' => $total_dp_balance
			);
			$this->m_customer->update_by_branch($data_customer, $cmb_customer, $branch_code);
		}
		/*============================================end==================================================================*/
		
		/*=====================================================================================*/
		/*
			masuk ke dalam sordetail dp
		*/
		if($CurrencyCode == 'IDR'){
			$total_amount     = round($txt_total_amount,2);
		}
		else{
			$total_amount     = round($ppn,2) > 0 ? doubleval(round($txt_total_amount,2) - round($ppn,2)) : doubleval(round($txt_total_amount,2));
		}
		
		$data_detail_dp = array(
			'SOrdNumber' 	 => $id,
			'CustomerCode' 	 => $cmb_customer,
			'SRecNumber' 	 => $SInvnumber,
			'SOrdTotalDP' 	 => $total_amount,
			'Owing' 		 => 0,
			'CurrencyRate' 	 => $CurrencyRate,
			'PaymentAmount'	 => $total_amount,
			'SaldoDPBalance' => $total_amount,
			'SOrdStatus' 	 => 1,
			'StatusDPFor' 	 => 1,
			'LastUser'       => $this->session->userdata("username")			
		);
		
		$this->m_sales_receipt->insert_so_detail_dp($data_detail_dp);
		
		if($CurrencyCode != 'IDR' && ($ppn > 0)){
			$data_detail_dp_ppn = array(
				'SOrdNumber' 	 => $id,
				'CustomerCode' 	 => $cmb_customer,
				'SRecNumber' 	 => $SInvnumber,
				'SOrdTotalDP' 	 => doubleval(round($ppn,2)),
				'Owing' 		 => 0,
				'CurrencyRate' 	 => $FiscalRate,
				'PaymentAmount'	 => doubleval(round($ppn,2)),
				'SaldoDPBalance' => doubleval(round($ppn,2)),
				'SOrdStatus' 	 => 1,
				'StatusDPFor' 	 => 1,
				'LastUser'       => $this->session->userdata("username")			
			);
			$this->m_sales_receipt->insert_so_detail_dp($data_detail_dp_ppn);
		}
		/*======================================end================================================*/
		
		//Update Si for LockedStatus is 1
		$data_sinv_group   = array (
			'LockStatus'      => 0,
			'LastUser' 		=> $this->session->userdata("username")
		);
		$this->m_sales_invoice->update($data_sinv_group, $SInvnumber);
		
		/*=============================trans roll back dan trans commit============================/*/
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$result['status'] 	= FALSE;
			$result['message']  = get_notification('approval', 0);
		}
		else {
			$this->db->trans_commit();
			$result['status'] 	= TRUE;
			$result['message']  = get_notification('approval', 1);
		}
		/*==================================end======================================================*/
			
		echo json_encode($result);
	}
	
	public function suspend_data() {
		$id 			= $this->input->post('id');
		$SInvnumber 	= $this->input->post('txt_si_no');
		
		$data = array (				
			'TransStatus' 		=> 3,
			'LastUser' 			=> $this->session->userdata("username")
		);
		
		$this->db->trans_begin();
		$this->m_sales_return->update($data, $id);
		
		/*$get_inventori_by_si = $this->m_sales_return->get_detail_item($id);
		foreach($get_inventori_by_si as $row_detail){
			$ItemQty = $row_detail->ItemQty;
			$ItemCode = $row_detail->ItemCode;
			
			$get_item_qty = $this->m_sales_return->get_at_sales_inv_qty($row_detail->SInvDetailID);
			$nilai_qty = $get_item_qty->QtyBookReturn - $ItemQty;
			
			$detail_inv = array(
				'QtyBookReturn' => $nilai_qty
			);
			
			//insert kedalam tabel sretdetail
			$this->m_sales_invoice->update_detail_for_return($detail_inv, $get_item_qty->SInvDetailID);
			//end
		}*/
		
		//Update Si for LockedStatus is 1
		$data_sinv_group   = array (
			'LockStatus'      => 0,
			'LastUser' 		=> $this->session->userdata("username")
		);
		$this->m_sales_invoice->update($data_sinv_group, $SInvnumber);
			
		/*=============================trans roll back dan trans commit============================/*/
		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);
		}
		/*==================================end======================================================*/
			
		echo json_encode($result);
			
	}
	//Function preview data
	public function to_preview($obj_string = null){
	     // set data
		$data['menu_id'] =  $this->menu_id;
		$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data_filter            = arrayParamInUrlToStr($obj_string);
		$data['list'] = $this->m_sales_return->get_all_print($data_filter);
		$data['branch_code'] = $data_filter['cmb_branch'];
		$data['company_code'] = $data_filter['cmb_company'];
		
		$this->load->view('v_header');
		$this->load->view('sales/sales_return/v_preview_salesreturn', $data);	
		$this->load->view('v_footer');	
	}
	
	//Function To Print
	public function to_print(){	
		 // set data
		$data['menu_id'] =  $this->menu_id;
		$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
		
		$data['list'] = $this->m_sales_return->get_all();
		
		$this->load->view('v_header');
		$this->load->view('sales/sales_return/v_print_salesreturn', $data);	
		$this->load->view('v_footer');	
	}
	
	// Function Print
	function to_print_detail(){
	    // get link from tbl_menu 
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
		// get label from tbl_menu 
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data
		$id = str_replace($data['menu_link'].'/to_print_detail/',"",$this->uri->uri_string());
		if($id!=""){		
			$data['detail'] = $this->m_sales_return->get_detail_print($id);
			$data['list'] = $this->m_sales_return->get_detail_item_print($data['detail']->SRetNumber);		
			
			$this->load->view('v_header');
			$this->load->view('sales/sales_return/v_print_detail_salesreturn', $data);	
			$this->load->view('v_footer');	
		}
	}
	
	//Function preview data
	function to_preview_detail(){
	    // get link from tbl_menu 
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
		// get label from tbl_menu 
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data
		$id = str_replace($data['menu_link'].'/to_preview_detail/',"",$this->uri->uri_string());
		if($id!=""){		
			$data['detail'] = $this->m_sales_return->get_detail($id);
			$data['list'] = $this->m_sales_return->get_detail_item($data['detail']->SRetNumber);		
			
			$this->load->view('v_header');
			$this->load->view('sales/sales_return/v_preview_detail_salesreturn', $data);	
			$this->load->view('v_footer');	
		}
	}
	
	function to_print_journal(){	
	    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data	 
		$id = str_replace($data['menu_link'].'/to_print_journal/',"",$this->uri->uri_string());
		$data['detail'] = $this->m_sales_return->get_detail($id);
		$data['list']   = $this->m_sales_return->get_journal_by_number($id);		
		$this->load->view('v_header');
		$this->load->view('sales/sales_return/v_print_journal_salesreturn',$data);	
		$this->load->view('v_footer');	
	}
	
	function to_preview_journal(){	
	    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
		// set data 
		$id = str_replace($data['menu_link'].'/to_preview_journal/',"",$this->uri->uri_string());
		$data['detail'] = $this->m_sales_return->get_detail($id);
		$data['list']   = $this->m_sales_return->get_journal_by_number($id);		
		$this->load->view('v_header');
		$this->load->view('sales/sales_return/v_preview_journal_salesreturn',$data);	
		$this->load->view('v_footer');	
	}
	
	public function ajax(){
		$page	= ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
		$rows	= ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
		
		$hasil = array();
		/*===========rows*page tidak boleh melebihi dari jumlah data======= */
		
		/*=================================post dari find di kiri====================================================*/
		$param 			= $this->input->post('param');
		$Number			= isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : ''; 
		$Desc			= isset($param['txt_Description']) ? $param['txt_Description'] : ''; 
		
		$DateFrom		= isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
		$DateTo			= isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
		$TransStatus	= isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
		$BranchCode		= isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
		/*============================================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('SRetNumber', $Number);} 
		if($Desc != ""){$this->db->like('SRetDesc', $Desc);} 
		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_salesreturn.SRetdate >=', date("Y-m-d", strtotime($DateFrom))); 
            	$this->db->where('at_salesreturn.SRetdate <=', date("Y-m-d", strtotime($DateTo))); 
			}
        }
		/*==========================end=================================================================*/
		
		$count_data = $this->db->count_all_results('at_salesreturn'); 
		$offset 	= $count_data - ($rows * $page);
		if($offset > 0){
			$rows = $rows;
		}
		else{
			$rows = $count_data - ($rows*($page-1));
		}
		/*========================end=======================================*/
		$result = $this->m_sales_return->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, 
				'EmployeeName' 	=>	$result[$i]->EmployeeName,
				'TransNumber' 	=>	$result[$i]->SRetNumber, 
				'SRetdate' 		=>	$result[$i]->SRetdate, 
				'SInvNumber' 	=>	$result[$i]->SInvNumber, 
				'SRetDesc' 		=>	$result[$i]->SRetDesc, 
				'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(){
        $id=$this->input->post('si_no');
        
        if(!empty($id)){
            echo json_encode($this->m_sales_invoice->get_detail_item_for_return($id));
        }
        else{
			$emptyVar = array();
			echo json_encode($emptyVar);
        }
        
//        echo $this->db->last_query(); die();
    }
	
	
	
	public function ajax_item_for_edit(){
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $id = str_replace($data['menu_link'].'/ajax_item_for_edit/',"",$this->uri->uri_string());

        if(!empty($id)){
            echo json_encode($this->m_sales_return->get_detail_item($id));
        }
        else{
            echo '[]';
        }
        
//        echo $this->db->last_query(); die();
    }
	
	/*public function ajax_detail(){		
        $Sret_number = $this->input->post('PInvNumber');

        if(!empty($pinv_number)){
            echo json_encode($this->m_purchase_invoice->get_detail_item($pinv_number));
        }
        else{
            echo '[]';
        }
    }
	
	public function ajax_detail(){
       $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$id = str_replace($data['menu_link'].'/ajax_detail/',"",$this->uri->uri_string());
        echo $id;
        if(!empty($CustomerCode)){
            echo json_encode($this->m_sales_return->get_detail_item($id));
        }
        else{
            echo $id;
        }
        
//        echo $this->db->last_query(); die();
    }*/
	
	/*public function ajax_detail(){
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$id = str_replace($data['menu_link'].'/ajax_detail/',"",$this->uri->uri_string());
		
		$result = $this->m_sales_return->get_detail_item($id);
		foreach($result as $row) {
			if($row->DepartmentCode != "") {
				$dept = $this->m_sales_return->get_dept_name($row->DepartmentCode);
			}
			else {
				$dept = "";
			}
			
			$hasil[] = array(
				'SRetDetailID' => $row->SRetDetailID,
				'SRetDate' => $row->SRetDate,
				'SRetNumber' => $row->SRetNumber,
				'ItemDesc' => $row->ItemDesc,
				'ItemCode' => $row->ItemCode,
				'ItemQty' => $row->ItemQty,
				'ItemUnit' => $row->ItemUnit,
				'ItemPrice' => $row->ItemPrice,
				'ItemAmount' => $row->ItemAmount,
				'ItemSN' => $row->ItemSN,
				'DepartmentCode' => $dept,
				'SalesmanCode' => $row->SalesmanCode,
				'SalesmanName' => $this->m_employee->get_name_by_id($row->SalesmanCode)
			); 
		}
		
		echo json_encode($hasil);
	}*/
	
	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();
    }
}
	