<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Fachri / 13-11-2015	
 
 */
 
class Sales_expense extends CI_Controller {
    public $menu_id     	= 362;
	public $menu_edit     	= 164;
    public $code        	= 'Sales Journal Number';
    public $name        	= 'Sales Journal';
    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->model('setup/m_branchinfo');
			$this->load->model('m_sales_expense');
			$this->load->model('m_sales_invoice');
			$this->load->model('m_sales_receipt');
			
			$this->load->model('m_sales_order');
			$this->load->model('m_customer');
			$this->load->model('m_account_journal');
			
    }
	
    public function index(){
		
			
    }
	
    //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');
					// 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['se_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_expense/v_new_salesexpense', $data);
					$this->load->view('v_footer');
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
	public function ajax_account_expense(){
        echo json_encode($this->m_sales_expense->get_account_expense());
    }
	
	function get_data_expense(){
         $CustomerCode = $this->uri->segment(4);
		
        
        if(!empty($CustomerCode)){
           echo json_encode($this->m_sales_expense->get_for_expense($CustomerCode));
        }
        else{
            echo '[]';
        }
    }
	
	function get_data_dp(){
        $CustomerCode = $this->uri->segment(4);
        
        if(!empty($CustomerCode)){
           echo json_encode($this->m_sales_expense->get_for_dp($CustomerCode));
        }
        else{
            echo '[]';
        }
    }
	
	function get_data_expense_by_invoice(){
        $si_number = $this->input->post('si_number');
		$invoice_type = $this->input->post('invoice_type');
		$invoice_name = $this->input->post('invoice_name');
        
        if(!empty($si_number)){
           echo json_encode($this->m_sales_expense->get_for_expense_invoice($si_number, $invoice_type, $invoice_name));
        }
        else{
            echo '[]';
        }
    }
	
	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');
		
		/*=====================================jcos number==========================================*/
		$SRecNumber  		= $this->m_sales_expense->create_sr_number($SRecDate);
		/*==========================================================================================*/
		
		$BankCode 			= $this->input->post('cbg_bank');
		$CurrencyCode 		= $this->input->post('hdn_cust_curr'); 
		$CurrencyRate 		= $this->input->post('hdn_cust_curr_rate'); 
		$InvoiceType 		= $this->input->post('hdn_inv_type'); 
		
		$PPnFiscalStatus    = $InvoiceType == 'PPN' ? 1 : 0;
		$FiscalRate 		= $this->input->post('hdn_fiscal_rate'); 
		$SInvTotalAmount 	= $this->input->post('hdn_inv_amount'); 
		$SRecTotalOwing 	= $this->input->post('hdn_inv_owing'); 
		$SRecTotalAmount 	= $this->input->post('hdn_rec_amount'); 
		$SRecAmountCurr 	= $this->input->post('hdn_rec_amount');
		
		$SRecDesc			= $this->input->post('txa_sr_desc');
		
		$branch_code    	= $this->session->userdata('branch');
		$detail 			= json_decode($this->input->post('detail'));
		/*=====================================end================================================*/
		
		/*
			Insert group
		*/
		if(count($detail)>0){
			$this->db->trans_begin();
			$this->insert_group($CustomerCode, $DepartmentCode, $SRecNumber, $SRecDate, $BankCode, $CurrencyCode, $CurrencyRate, $SRecDesc, $PPnFiscalStatus, $SInvTotalAmount, $SRecTotalOwing, $SRecTotalAmount, $SRecAmountCurr);
			/*==================End==============================*/
			
			/*
				detail grid 
			*/
			foreach($detail as $row){
				$item_categori_id   = $row->ItemCategoryID;
				$item_category_code = $row->ItemCategoryCode;
				
				$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_type_id 	= $row->InvoiceTypeID;
				$invoice_currency 	= $row->InvoiceCurrCode;
				
				$InvoicePaymentID 	= $row->InvoicePaymentID;
				$InvoiceAmountCopy 	= $row->InvoiceAmountCopy;
				
				$invoice_date       = date("Y-m-d", strtotime($row->InvoiceDate));
				
				$receipt_amount     = $row->PaymentAmount; 
				$receipt_currency   = $row->PaymentAmount; 
				
				$CategoryName   	= $row->ItemCategoryName;
				$FiscalStatus_Detail 	= $row->PPnFiscalStatus;
						
				if($row->InvoiceType == 'PPN'){
					$get_invoice_receipt = $this->m_sales_receipt->get_invoice_recip($invoice_number, 2, 1); //ge data from invoicerecip new table
					$this->insert_detail_grid($InvoicePaymentID,$SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $InvoiceAmountCopy, $invoice_owing, $invoice_rate, $fiscal_rate, $PPnFiscalStatus, $receipt_amount, $receipt_currency, $invoice_type_id, $item_categori_id, $item_category_code, $CategoryName);
					$this->insert_journal_fiscal($fiscal_rate, $item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc);
				}
				else{
					if($row->InvoiceType == 'SI'){
						/*
							Insert detail
						*/
						$get_invoice_receipt = $this->m_sales_receipt->get_invoice_recip($invoice_number, 0, $FiscalStatus_Detail);
						$this->insert_detail_grid($InvoicePaymentID,$SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $InvoiceAmountCopy, $invoice_owing, $invoice_rate, $fiscal_rate, $PPnFiscalStatus, $receipt_amount, $receipt_currency, $invoice_type_id, $item_categori_id, $item_category_code, $CategoryName);
						/*===========================End========================================================*/
						$this->insert_journal_invoice($item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc);
					}
					else{
						/*===================Get Sordetail DP==========================================*/
						//if($Dp_Receipt > 0){
							$sordetail_dp    = $this->m_sales_receipt->get_saldo_detail_dp_sales_journal($invoice_number);
							
							$saldo_dp 		 = $receipt_amount;
							foreach($sordetail_dp as $row_detail_dp){
								$is_edit 	 = 1;
									
								$update_sordetail = array(
									'DPUsedBook' 			=> $saldo_dp,
									'IsEdit' 				=> $is_edit
								);
								$this->m_sales_receipt->update_so_detail_dp_by_invoice($update_sordetail, $invoice_number);
							}
						//}
						/*========================End===================================================*/
						
						/*
							Insert detail
						*/
						$get_invoice_receipt 	   = $this->m_sales_receipt->get_invoice_recip($invoice_number, 1, NULL);
						$this->insert_detail_grid($InvoicePaymentID,$SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $InvoiceAmountCopy, $invoice_owing, $invoice_rate, $fiscal_rate, $PPnFiscalStatus, $receipt_amount, $receipt_currency, $invoice_type_id, $item_categori_id, $item_category_code, $CategoryName);
						$this->insert_journal_dp($item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc);
						/*===========================End========================================================*/
					}
				}
			}
			/*=================End=========================*/
			
			/*=============================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, $SRecNumber);
		}
		echo json_encode($result);
	}
	
	function insert_group($CustomerCode, $DepartmentCode, $SRecNumber, $SRecDate, $BankCode, $CurrencyCode, $CurrencyRate, $SRecDesc, $PPnFiscalStatus, $SInvTotalAmount, $SRecTotalOwing, $SRecTotalAmount, $SRecAmountCurr){
		$data_sr = array(
			'BranchCode'		=> $this->session->userdata('branch'), 
			'CustomerCode'		=> $CustomerCode, 
			'DepartmentCode'	=> $DepartmentCode, 
			'SRecNumber'		=> $SRecNumber, 
			'SRecDate'			=> date("Y-m-d", strtotime($SRecDate)), 
			'BankReceipt'		=> $BankCode,
			'BankCurrCode' 		=> 'IDR',
			'BankCurrRate' 		=> 1,
			'CurrencyCode'		=> $CurrencyCode, 
			'CurrencyRate'		=> $CurrencyRate, 
			'ChequeNumber'		=> "", 
			'ChequeDate'		=> $SRecDate, 
			'ChequeAmount'		=> 0, 
			'SRecDesc'			=> $SRecDesc, 
			'SInvTotalAmount'	=> doubleval($SInvTotalAmount), 
			'SRecTotalOwing'	=> doubleval($SRecTotalOwing), 
			'SRecTotalDPUsed'	=> 0, 
			'SRecTotalDiscount'	=> 0, 
			'SRecTotalAmount'	=> doubleval($SRecTotalAmount), 
			'SRecAmountCurr' 	=> doubleval($SRecAmountCurr),
			'PPnFiscalStatus' 	=> $PPnFiscalStatus,
			'TransStatus'		=> 4, 
			'ReceiptStatus' 	=> 1,
			'CreatedBy' 		=> $this->session->userdata('username'),
			'CreatedAt' 		=> date('Y-m-d'),
			'LastUser'			=> $this->session->userdata('username')
		);
		
		$this->m_sales_receipt->insert($data_sr);
		
		/*===============================================================================*/
		/*
			Update customer for lock status
		*/
		$data_customer  = array (
			'LockStatus'    => 1,
			'LastUser'      => $this->session->userdata("username")
		);

		$this->m_customer->update($data_customer, $CustomerCode);
		/*===========================end=================================================*/
	}
	
	function insert_detail_grid($InvoicePaymentID,$SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $InvoiceAmountCopy, $invoice_owing, $invoice_rate, $fiscal_rate, $PPnFiscalStatus, $receipt_amount, $receipt_currency, $InvoiceType, $ItemCategoryID, $ItemCategoryCode, $CategoryName){
		$detail_data  = array(
			'InvoicePaymentID'      => $InvoicePaymentID, 
			'SrecNumber'            => $SRecNumber, 
			'SInvNumber'            => $invoice_number,
			'SInvDate'              => $invoice_date, 
			'SInvAmount'            => $invoice_amount,
			'SInvAmountTemp' 		=> $InvoiceAmountCopy,
			'SRecOwing'             => $invoice_owing,
			'SInvCurrRate'          => $invoice_rate,
			'SInvFiscalRate'        => $fiscal_rate,
			'FiscalStatus' 			=> $PPnFiscalStatus,                        
			
			'SRecDiscDate'          => 0, 
			'SRecDiscount'          => 0, 
			'SRecDPUsed'            => 0, 
			'SRecAmount'            => $receipt_amount, 
			
			'SRecCurrency'          => 0,
			'SInvCurrency'          => 0,
			'SrecRounded' 			=> 0,                     
			'SRecPaidStatus'        => 1, 
			'SRecInvoiceType'       => $InvoiceType,
			'DPStatus'       		=> 0, 
			'ItemCategoryID'        => $ItemCategoryID, 
			'ItemCategoryCode'      => $ItemCategoryCode, 
			'CategoryName' 			=> $CategoryName,
			'LastUser'              => $this->session->userdata("username")				
		);

		$this->m_sales_receipt->insert_detail($detail_data);
	}
	
	function insert_journal_invoice($item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc){
		/*===================Journal Bank================================================*/
		if($receipt_amount > 0){
			$account_amount    = $invoice_currency == 'IDR' ? $receipt_amount : $receipt_amount * $invoice_rate;
			$account_currency  = $invoice_currency == 'IDR' ? $receipt_amount : $receipt_amount;
			
			$journal_bank           = array(
				'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
				'SRecNumber'                => $SRecNumber,
				'SRecDesc'                  => $SRecDesc,
				'SRecAccountNumber'         => $BankCode,
				'SRecSaldoDebet'            => $account_amount,
				'SRecSaldoCredit'           => 0,
				'AmountCurrency'            => $account_currency,
				'SRecSignStatus'            => 0, 
				'ItemCategoryID'            => $item_categori_id,
				'LastUser'                  => $this->session->userdata("username")
			 );
		
			$this->m_sales_receipt->insert_journal($journal_bank);
		}
		/*=======================end=====================================================*/
		
		/*=======================Journal Payable Account - piutang Dagang====================================================================*/
		foreach($get_invoice_receipt as $row_inv_receipt){
			$InvoicePaymentID      	= $row_inv_receipt->InvoicePaymentID;
			$ItemCategoryID        	= $row_inv_receipt->ItemCategoryID;
			$ItemCategoryCode      	= $row_inv_receipt->ItemCategoryCode;
			$ItemCategoryRatio   	= $row_inv_receipt->ItemCategoryRatio;
			$InvoiceOwing  			= $row_inv_receipt->InvoiceOwing;
										 
			if($ItemCategoryID > 0){
				$SalesAccount    = $this->m_account_journal->get_cat_sales_account('SRAccountReceivable', $ItemCategoryCode, $invoice_currency);
				if($SalesAccount == false) {$this->trans_rollback('journal','Piutang Dagang', $invoice_currency);}                                
			}
			else{
				$SalesAccount    = $this->m_account_journal->get_sys_service_account('SalesExpense', 'IDR');                            
				if($SalesAccount == false) {$this->trans_rollback('journal','Exepnse, Expense', $invoice_currency);}                         
			}
			
			$amount_payment         = $receipt_amount * ($ItemCategoryRatio / 100);
			
			$get_journal_receipt 	= $this->m_sales_receipt->get_journal_recip_empty($SalesAccount->AccountNumber, $SRecNumber);		
			if(empty($get_journal_receipt->SRecAccountNumber)){
				$payable_amount     = $invoice_currency == 'IDR' ? $amount_payment : $amount_payment * $invoice_rate;
				$payable_currency   = $invoice_currency == 'IDR' ? $amount_payment : $amount_payment;
							
				$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'            => $ItemCategoryCode,
					'LastUser'                  => $this->session->userdata("username")
				 );
	
				$this->m_sales_receipt->insert_journal($journal_reciv);
			}
			else{
				$payable_value      	= $payable_value + $get_journal_receipt->SRecSaldoCredit;
				$payable_value_curr     = $payable_value_curr + $get_journal_receipt->AmountCurrency;
				
				$payable_amount     = $CurrencyCode == 'IDR' ? $payable_value : $payable_value * $invoice_rate;
				$payable_currency   = $CurrencyCode == 'IDR' ? $payable_value_curr : $payable_value;
				
				$journal_reciv           = array(
					'SRecSaldoDebet'            => 0,
					'SRecSaldoCredit'           => $payable_value,
					'AmountCurrency'            => $payable_currency,
					'SRecSignStatus'            => 1, 
				 );
	
				$this->m_sales_receipt->update_journal($journal_reciv, $SalesAccount->AccountNumber, $SRecNumber);
			}
		}
		/*=================================end=========================================================================*/
		
		
	}
	
	function insert_journal_dp($item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc){
		/*===================Journal Accoont================================================*/
		if($receipt_amount > 0){
			$account_amount    = $invoice_currency == 'IDR' ? $receipt_amount : $receipt_amount * $invoice_rate;
			$account_currency  = $invoice_currency == 'IDR' ? $receipt_amount : $receipt_amount;
			
			$journal_bank           = array(
				'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
				'SRecNumber'                => $SRecNumber,
				'SRecDesc'                  => $SRecDesc,
				'SRecAccountNumber'         => $BankCode,
				'SRecSaldoDebet'            => $account_amount,
				'SRecSaldoCredit'           => 0,
				'AmountCurrency'            => $account_currency,
				'SRecSignStatus'            => 0, 
				'ItemCategoryID'            => $item_categori_id,
				'LastUser'                  => $this->session->userdata("username")
			 );
		
			$this->m_sales_receipt->insert_journal($journal_bank);
		}
		/*=======================end=====================================================*/
		
		/*=======================================================================================
		 	advance sales or sales advance
			advancesales = inventori
			sales advance = servis
		 */
		foreach($get_invoice_receipt as $row_inv_receipt){
			$InvoicePaymentID      	= $row_inv_receipt->InvoicePaymentID;
			$ItemCategoryID        	= $row_inv_receipt->ItemCategoryID;
			$ItemCategoryCode      	= $row_inv_receipt->ItemCategoryCode;
			$ItemCategoryRatio   	= $row_inv_receipt->ItemCategoryRatio;
			$InvoiceOwing  			= $row_inv_receipt->InvoiceOwing;
			$DpValue 				= 0;
			/*================================================================================================================
				ItemCategoryID = not 0 this inventory, 0 this servis 
			*/
			if($ItemCategoryID > 0){
				$DPAccount  = $this->m_account_journal->get_cat_sales_account('AdvanceSales', $ItemCategoryID, $invoice_currency); // Uang Muka Category -> 1-4-03-001-00                            
			}
			else {
				$DPAccount  = $this->m_account_journal->get_sys_service_account('SalesAdvance', $invoice_currency); // Uang Muka Expense -> 1-4-03-001-00                            
			}
			if($DPAccount == false) {$this->trans_rollback('journal','Uang Muka Penjualan', $invoice_currency);}
			/*==============================================================================================================*/
			
			$amount_payment         = $receipt_amount * ($ItemCategoryRatio / 100);
			
			$get_journal_receipt = $this->m_sales_receipt->get_journal_recip_empty($DPAccount->AccountNumber, $SRecNumber);
			$DpValue      		 = $invoice_currency == 'IDR' ? $amount_payment : $amount_payment;
			$DPCurrency    		 = $invoice_currency == 'IDR' ? $amount_payment : $amount_payment * $invoice_rate;
			
				
			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'           => $DpValue,
					'AmountCurrency'            => $DPCurrency,
					'SRecSignStatus'            => 1, 
					'ItemCategoryID'            => $ItemCategoryID,
					'LastUser'                  => $this->session->userdata("username")	
				 );
	
				$this->m_sales_receipt->insert_journal($journal_dp);
			}
			else{
				$DpValue 					= $get_journal_receipt->SRecSaldoCredit + $amount_payment;
				$DPCurrency 				= $get_journal_receipt->AmountCurrency + $DPCurrency;
				
				$journal_dp   = array(
					'SRecSaldoDebet'            => 0,
					'SRecSaldoCredit'           => $DpValue,
					'AmountCurrency'            => $DPCurrency,
				);
				$this->m_sales_receipt->update_journal($journal_dp, $SRecNumber, $get_journal_receipt->SRecAccountNumber);
			}
		}
		/*================================================end=======================================================*/
	}
	
	
	function insert_journal_fiscal($fiscal_rate, $item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc){
		/*==================================get account from model account journal======================*/
		$PPnFiscalAccount   = $this->m_account_journal->get_account_name('PPN Fiscal'); 
		if($PPnFiscalAccount == false) {$this->trans_rollback('journal','Purchase PPn Fiscal, Taxable', $invoice_currency);}
		/*======================================end=====================================================*/
		
		$FiscalCurrency = $receipt_amount;
		$FiscalValue 	= $receipt_amount;
		$FiscalRelize 	= $receipt_amount / $fiscal_rate;
		
		
		/*==========================Insert Journal Hutang PPn Fiscal===============================*/
		$journal_fiscal           = array(
			'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
			'SRecNumber'                => $SRecNumber,
			'SRecDesc'                  => $SRecDesc,
			'SRecAccountNumber'         => $PPnFiscalAccount->AccountNumber,
			'SRecSaldoDebet'            => $FiscalValue,
			'SRecSaldoCredit'           => 0,
			'AmountCurrency'            => $FiscalCurrency,
			'SRecSignStatus'            => 0, 
			'ItemCategoryID'            => $item_categori_id,
			'LastUser'                  => $this->session->userdata("username")
		 );
		 $this->m_sales_receipt->insert_journal($journal_fiscal);
		 /*========================================================================================*/
		 
		/*===================Journal Accoont================================================*/
		$BankRelize 		  = $receipt_amount / $invoice_rate;
		if($receipt_amount > 0){
			$account_amount    = $invoice_currency == 'IDR' ? $receipt_amount : $receipt_amount;
			$account_currency  = $invoice_currency == 'IDR' ? $receipt_amount : $receipt_amount;
			
			$journal_bank           = array(
				'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
				'SRecNumber'                => $SRecNumber,
				'SRecDesc'                  => $SRecDesc,
				'SRecAccountNumber'         => $BankCode,
				'SRecSaldoDebet'            => 0,
				'SRecSaldoCredit'           => $account_amount,
				'AmountCurrency'            => $account_currency,
				'SRecSignStatus'            => 0, 
				'ItemCategoryID'            => $item_categori_id,
				'LastUser'                  => $this->session->userdata("username")
			 );
		
			$this->m_sales_receipt->insert_journal($journal_bank);
		}
		/*=======================end=====================================================*/
		
		/*===============================Realized G/L TotalSrecRealizedGl > 0============================*/
		 $Total_Relize 			= ($BankRelize) - ($FiscalRelize);
		 $TotalSrecRealizedGl 	=  $Total_Relize * $invoice_rate;
		 if($invoice_currency != 'IDR'){
		 	if($TotalSrecRealizedGl > 0){
				$RealizedAccount  = $this->m_account_journal->get_sys_sales_account('RealizedGainedLoss', 'IDR');
				if($RealizedAccount == false) {$this->trans_rollback('journal','Realized G/L, Sales', $invoice_currency);}
				
				$RealizeglValue    = $TotalSrecRealizedGl / $invoice_rate ;                            
				$RealizedAmount    = $invoice_currency == 'IDR' ? abs($RealizeglValue) : abs($RealizeglValue) * $invoice_rate;
				$RealizedCurrency  = abs($RealizeglValue);

				$journal_realized = array(
					'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
					'SRecNumber'                => $SRecNumber,
					'SRecDesc'                  => $SRecDesc,
					'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
					'SRecSaldoDebet'            => $RealizedAmount,
					'SRecSaldoCredit'           => 0,
					'AmountCurrency'            => 0,
					'SRecSignStatus'            => 0, 
					'ItemCategoryID'            => $item_categori_id,
					'LastUser'                  => $this->session->userdata("username")
				 );
				
				//$this->m_sales_receipt->insert_journal($journal_realized); 
			}
		 }
		 /*==============================END============================================================*/
		 
		 /*=======================================Realized G/L TotalSrecRealizedGl < 0======================*/
		 if($invoice_currency != 'IDR'){
			if($TotalSrecRealizedGl < 0){
				$RealizedAccount  = $this->m_account_journal->get_sys_sales_account('RealizedGainedLoss', 'IDR'); 
				if($RealizedAccount == false) {$this->trans_rollback('journal','Realized G/L, Sales', $CurrencyCode_Cus);}
		
				$RealizeglValue    = $TotalSrecRealizedGl / $invoice_rate ;                            
				$RealizedAmount    = $invoice_currency == 'IDR' ? abs($RealizeglValue) : abs($RealizeglValue) * $invoice_rate;
				$RealizedCurrency  = abs($RealizeglValue);

				$journal_realized = array(
					'SRecDate'                  => date("Y-m-d", strtotime($SRecDate)),
					'SRecNumber'                => $SRecNumber,
					'SRecDesc'                  => $SRecDesc,
					'SRecAccountNumber'         => $RealizedAccount->AccountNumber,
					'SRecSaldoDebet'            => 0,
					'SRecSaldoCredit'           => abs($RealizedAmount),
					'AmountCurrency'            => 0,
					'SRecSignStatus'            => 1, 
					'ItemCategoryID'            => $item_categori_id,
					'LastUser'                  => $this->session->userdata("username")
				 );
				 //$this->m_sales_receipt->insert_journal($journal_realized);  
			}                        
		}
		/*=======================================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_edit);
			
			//--------------------------end-----------------------------------------------------------
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_edit, $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_edit);
					$data['menu_link'] = $this->m_menu->get_menulink($this->menu_edit);
					
					$data['app1']       = $this->app1;
					$data['app2']       = $this->app2;

					// inisialisasi additional parameter
					$id = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
					$id_number  		= $this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6);
					
					$data['detail'] = $this->m_sales_expense->get_detail($id_number);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_edit, $group_menu);
					
					if($data['detail'] != false){
						// set for view
						$this->load->view('v_header');
						$this->load->view('sales/sales_expense/v_edit_salesexpense',$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 from sales recip dari group
		*/
		$DepartmentCode 	= $this->input->post('cbg_department');
		$CustomerCode 		= $this->input->post('cbg_customer');
		$SRecDate 			= $this->input->post('txt_sr_date');
		
		/*=====================================jcos number==========================================*/
		$SRecNumber  		= $this->input->post('txt_sr_no');
		/*==========================================================================================*/
		
		$BankCode 			= $this->input->post('cbg_bank');
		$CurrencyCode 		= $this->input->post('hdn_cust_curr'); 
		$CurrencyRate 		= $this->input->post('hdn_cust_curr_rate'); 
		$PPnFiscalStatus 	= $this->input->post('hdn_fiscal_status'); 
		$FiscalRate 		= $this->input->post('hdn_fiscal_rate'); 
		$SInvTotalAmount 	= $this->input->post('hdn_inv_amount'); 
		$SRecTotalOwing 	= $this->input->post('hdn_inv_owing'); 
		$SRecTotalAmount 	= $this->input->post('hdn_rec_amount'); 
		$SRecAmountCurr 	= $this->input->post('hdn_rec_amount'); 
		
		$SRecDesc			= $this->input->post('txa_sr_desc');
		
		$branch_code    	= $this->session->userdata('branch');
		$detail 			= json_decode($this->input->post('detail'));
		/*=====================================end================================================*/
		
		
		if(count($detail)>0){
			$this->db->trans_begin();
			$this->m_sales_receipt->delete_journal($SRecNumber);
			/*
				insert group
			*/
			$this->update_group($SRecDesc, $SRecNumber, $SRecDate, $SInvTotalAmount, $SRecTotalOwing, $SRecTotalAmount, $SRecAmountCurr);
			/*========================================end=============================================*/
			
			foreach($detail as $row){
				$item_categori_id   = $row->ItemCategoryID;
				$item_category_code = $row->ItemCategoryCode;
				
				$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_type_id 	= $row->InvoiceTypeID;
				$invoice_currency 	= $row->InvoiceCurrCode;
				
				//$InvoicePaymentID 	= $row->InvoicePaymentID;
				$InvoiceAmountCopy 	= $row->InvoiceAmountCopy;
				$SRecDetailID 		= $row->SRecDetailID;
				
				$invoice_date       = date("Y-m-d", strtotime($row->InvoiceDate));
				
				$receipt_amount     = $row->PaymentAmount; 
				$receipt_currency   = $row->PaymentAmount; 
				
				$CategoryName   	= $row->CategoryName;
				$FiscalStatus_Detail 	= $row->PPnFiscalStatus;
						
				if($row->CategoryName == 'PPn Fiscal'){
					$get_invoice_receipt = $this->m_sales_receipt->get_invoice_recip($invoice_number, 2, 1); //ge data from invoicerecip new table
					$this->update_detail_grid($SRecDetailID, $receipt_amount, $invoice_amount, $invoice_owing, $item_categori_id, $item_category_code, $InvoiceAmountCopy);
					$this->insert_journal_fiscal($fiscal_rate, $item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc);
				}
				else{
					if($row->CategoryName == 'Invoice'){
						/*
							Insert detail
						*/
						$get_invoice_receipt = $this->m_sales_receipt->get_invoice_recip_no_fiscal($invoice_number, 0);
						
						$this->update_detail_grid($SRecDetailID, $receipt_amount, $invoice_amount, $invoice_owing, $item_categori_id, $item_category_code, $InvoiceAmountCopy);
						/*===========================End========================================================*/
						$this->insert_journal_invoice($item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc);
					}
					else{
						/*===================Get Sordetail DP==========================================*/
						//if($Dp_Receipt > 0){
							$sordetail_dp    = $this->m_sales_receipt->get_saldo_detail_dp_sales_journal($invoice_number);
							
							$saldo_dp 		 = $receipt_amount;
							foreach($sordetail_dp as $row_detail_dp){
								$is_edit 	 = 1;
									
								$update_sordetail = array(
									'DPUsedBook' 			=> $saldo_dp,
									'IsEdit' 				=> $is_edit
								);
								$this->m_sales_receipt->update_so_detail_dp_by_invoice($update_sordetail, $invoice_number);
							}
						//}
						/*========================End===================================================*/
						
						/*
							Insert detail
						*/
						$get_invoice_receipt 	   = $this->m_sales_receipt->get_invoice_recip($invoice_number, 1, NULL);
						$this->update_detail_grid($SRecDetailID, $receipt_amount, $invoice_amount, $invoice_owing, $item_categori_id, $item_category_code, $InvoiceAmountCopy);
						$this->insert_journal_dp($item_categori_id, $BankCode,$invoice_number, $invoice_rate, $get_invoice_receipt, $invoice_currency, $receipt_amount,$SRecNumber, $SRecDate, $SRecDesc);
						/*===========================End========================================================*/
					}
				}
			}
			/*=================End=========================*/
			
			/*=============================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, '');
				
				$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, 'update', 1, '');
			}
			/*==================================end======================================================*/
		}
		else{
			$this->db->trans_rollback();
			$result['status']    = false;
            $result['message']   = get_notification_transaksi($this->name, 'insert', 0, '');
		}
		echo json_encode($result);
		
	}
	
	function update_group($SRecDesc, $SRecNumber, $SRecDate, $SInvTotalAmount, $SRecTotalOwing, $SRecTotalAmount, $SRecAmountCurr){
		$data_sr = array(
			'SRecNumber'		=> $SRecNumber, 
			'SRecDate'			=> date("Y-m-d", strtotime($SRecDate)), 
			 
			'SRecDesc'			=> $SRecDesc, 
			'SInvTotalAmount'	=> doubleval($SInvTotalAmount), 
			'SRecTotalOwing'	=> doubleval($SRecTotalOwing), 
			'SRecTotalAmount'	=> doubleval($SRecTotalAmount),
			'SRecAmountCurr' 	=> doubleval($SRecAmountCurr),
			'LastUser'			=> $this->session->userdata('username')
		);
		/*=========================insert receept group======================*/
		$this->m_sales_receipt->update($data_sr, $SRecNumber);
		/*==========================end=====================================*/
	}
	
	function update_detail_grid($SRecDetailID, $receipt_amount, $invoice_amount, $invoice_owing, $item_categori_id, $item_category_code, $InvoiceAmountCopy){
		$detail_data  = array(
			'SInvAmount'            => $invoice_amount,
			'SInvAmountTemp' 		=> $InvoiceAmountCopy,
			'SRecOwing'             => $invoice_owing,
			'SRecAmount'            => $receipt_amount, 

			'ItemCategoryID'        => $item_categori_id, 
			'ItemCategoryCode'      => $item_category_code, 
			'LastUser'              => $this->session->userdata("username")				
		);

		$this->m_sales_receipt->update_detail($detail_data, $SRecDetailID);
	}
	
	public function approval(){
		/*=======================================deklar variabel=========================================*/
		$detail_post   		= $this->input->post('Detail');        
		$detail         	= json_decode($detail_post);
		$cust_code      	= $this->input->post('CustCode');
		$srec_number    	= $this->input->post('SRecNumber');
		$SrecDate    		= $this->input->post('SrecDate');
		$currency_rate  	= $this->input->post('CurrencyRate');
		$TotalRecipt  		= $this->input->post('TotalRecipt');
		$Cust_curr_code  	= $this->input->post('Cust_curr_code');
		$DPPartial  		= $this->input->post('DPPartial');
		/*=================end============================================================================*/
		
		if(count($detail) > 0){
				$this->db->trans_begin();
				
			foreach($detail as $row){
				$fiscal_rate 			= 0;
				$currency_rate_so 		= 0;
				$DP_Customer 			= 0;
				$DP_Partial  			= 0;
				
				$receipt_amount     	= $row->PaymentAmount;
				$receipt_amount_copy  	= $row->InvoiceAmountCopy;
				$fiscal_rate 			= $row->InvoiceFiscalRate;
				
				if($row->CategoryName == 'PPn Fiscal'){
					$cust_dp    		= $this->m_customer->get_saldo_by_id($cust_code);
					$OutStandingFiscal  = $cust_dp[0]->OutStandingFiscal;
					$OutStandingFiscal  = $OutStandingFiscal - $row->PaymentAmount;
					
					/*===================update cust dp=================================*/	
					$data_cust_dp     = array (
						'OutStandingFiscal' => $OutStandingFiscal,
						'LockStatus'    	=> 0,
						'LastUser'          => $this->session->userdata("username")
					);
					$this->m_customer->update($data_cust_dp, $cust_code);
					/*======================end=========================================*/
					
					/*===================update cust dp detail================================*/	
					$data_detail_srec     = array (
						'SInvAmountTemp'    => $row->InvoiceOwing,
						'LastUser'          => $this->session->userdata("username")
					);
					$this->m_sales_receipt->update_detail($data_detail_srec, $row->SRecDetailID);
					/*=========================end==============================================*/
					
					/*===================update at_invoicereceipt===============================*/
					$get_invoice_recip = $this->m_sales_receipt->get_invoice_recip($row->InvoiceNumber, 2, 1);
					foreach($get_invoice_recip as $row_recip){
						$inv_recip_id         	= $row_recip->InvoicePaymentID;
												  
						$inv_category_ratio     = $row_recip->ItemCategoryRatio;
						$inv_amount             = $row_recip->InvoiceAmount;
						$ReceiptAmount 			= $row_recip->ReceiptAmount;
						$ReceiptTotal 			= $row_recip->ReceiptTotal;
						
						if($Cust_curr_code == 'IDR'){
							$paymen_amount		= $receipt_amount * 1;
						}
						else{
							$paymen_amount 		= $receipt_amount * $fiscal_rate;
						}
						
						$amount_advance         = ($paymen_amount * $inv_category_ratio) / 100;
						$owing         			= ($row->InvoiceOwing * $inv_category_ratio) / 100;
						
						$data_at_invoicereceipt = array(
							'ReceiptAmount' 	=> $amount_advance,
							'ReceiptTotal' 		=> $amount_advance,
							'InvoiceOwing' 		=> $owing,
						);
						$this->m_sales_receipt->update_invoicerecip($data_at_invoicereceipt, $inv_recip_id);
					}
					/*===============================end===========================================================*/
				}
				else if($row->CategoryName == 'Invoice'){
					/*============================Update Customer DP Balance, Outstanding====================*/
					$cust_dp    	= $this->m_customer->get_saldo_by_id_new($cust_code);
					$saldo_balance  = $cust_dp->OutStanding - $receipt_amount;
						
					$data_cust_dp     = array (
						'OutStanding'       => $saldo_balance,
						'LockStatus'    	=> 0,
						'LastUser'          => $this->session->userdata("username")
					);
					$this->m_customer->update($data_cust_dp, $cust_code);
					/*======================end============================================================*/
					
					/*===================Update Detail Srec==================================================*/	
					$data_detail_srec     = array (
						'SInvAmountTemp'    => $row->InvoiceOwing,
						'LastUser'          => $this->session->userdata("username")
					);
					$this->m_sales_receipt->update_detail($data_detail_srec, $row->SRecDetailID);
					/*===================end==============================================================*/
					
					//update at_invoicereceipt
					$get_invoice_recip = $this->m_sales_receipt->get_invoice_recip($row->InvoiceNumber, 0, $row->PPnFiscalStatus);
					//echo $this->db->last_query();
					foreach($get_invoice_recip as $row_recip){
						$inv_recip_id         	= $row_recip->InvoicePaymentID;
												  
						$inv_category_ratio     = $row_recip->ItemCategoryRatio;
						$inv_amount             = $row_recip->InvoiceAmount;
						
						$ReceiptAmount 			= $row_recip->ReceiptAmount;
						$ReceiptDisc 			= $row_recip->ReceiptDiscount;
						$ReceiptDPUsed 			= $row_recip->ReceiptDPUsed;
						$ReceiptTotal 			= $row_recip->ReceiptTotal;
						$ReceiptRounded 		= $row_recip->ReceiptRounded;
						
						$amount_advance         = ($row->PaymentAmount * $inv_category_ratio) / 100;
						$owing         			= ($row->InvoiceOwing * $inv_category_ratio) / 100;
						
						$data_at_invoicereceipt = array(
							'ReceiptAmount' 	=> $amount_advance,
							'ReceiptTotal' 		=> $amount_advance,
							'InvoiceOwing' 		=> $owing
						);
						$this->m_sales_receipt->update_invoicerecip($data_at_invoicereceipt, $inv_recip_id);
					}//end
				}
				else{
					/*====================approve so dp=====================================*/
					$cust_dp    	= $this->m_customer->get_saldo_by_id_new($cust_code);
					$DP_Customer   	= $cust_dp->SaldoDPBalance;
					
					if($Cust_curr_code == 'IDR'){
						$currency_rate_so = 1;
					}
					else{
						$currency_rate_so = $currency_rate;
					}
					
					//get sordetail dp
						$sordetail_dp    = $this->m_sales_receipt->get_saldo_detail_dp_approve_by_inv($row->InvoiceNumber);
						$dp_used 		 = 0;
						foreach($sordetail_dp as $row_app){
							$DPUsed 			= $row_app->DPUsed;
							$SaldoDPBalance 	= $row_app->SaldoDPBalance;
							$sordetail_id 		= $row_app->SOrdDetailDPID;
							
							if($DPUsed != $SaldoDPBalance){
								$dp_used_row_book 	= $row_app->DPUsedBook;
								$dp_approve 		= $row_app->DPUsed;
								$dp_used 			= $dp_used_row_book;
								$is_edit 			= 0;
								
								$update_sordetail = array(
									'DPUsed' 			=> $dp_used + $dp_approve,
									'DPUsedBook' 		=> $dp_used + $dp_approve,
									'IsEdit' 			=> $is_edit,
									'SOrdStatus' 		=> 0
								);
								$this->m_sales_receipt->update_so_detail_dp_by_invoice($update_sordetail, $row->InvoiceNumber);
							}
						}
						//end
					
					/*===============================calculate dp partial=========================================================*/
					if($row->InvoiceOwing == 0){
						$DP_Customer = $DP_Customer - $row->InvoiceAmount; //DP balance di customer dikurang apa tidak
						$DPPartial	 = $DPPartial + $row->PaymentAmount;
						$DPPartial   = $DPPartial - $row->InvoiceAmount;
					}
					else{
						$DP_Customer = $DP_Customer;
						$DPPartial 	 = $DPPartial + $row->PaymentAmount;
					}
					/*========================end=================================================================================*/
					
					/*==============================update cust dp=================================================================*/	
					$data_cust_dp     = array (
						'SaldoDPBalance'    => $DP_Customer,
						'LockStatus'    	=> 0,
						'SaldoDPPartial' 	=> $DPPartial,
						'LastUser'          => $this->session->userdata("username")
					);
					$this->m_customer->update($data_cust_dp, $cust_code);
					/*================================end============================================================================*/
					
					/*===============================update sin temporary==============================================================*/
					$data_detail_srec     = array (
						'SInvAmountTemp'    => $row->InvoiceOwing,
						'LastUser'          => $this->session->userdata("username")
					);
					$this->m_sales_receipt->update_detail($data_detail_srec, $row->SRecDetailID);
					/*=========================end=====================================================================================*/
					
					/*==================================update srec total dp di so=====================================================*/
					$get_srec_total_dp    = $this->m_sales_order->get_sales_order($row->InvoiceNumber);
					$data_so = array(
						'SRecTotalDP' => $get_srec_total_dp - $row->PaymentAmount
					);
					$this->m_sales_order->update($data_so, $row->InvoiceNumber);
					/*=====================================end========================================================================*/
					
					/*================Update sales Order for Receive DP===============================================================*/
					//$this->m_sales_order->set_finish_so_dp_new($row->InvoiceNumber);
					/*==============================end===============================================================================*/
					
					/*=================update at_invoicereceipt=======================================================================*/
					/*$get_invoice_recip 			= $this->m_sales_receipt->get_invoice_recip($row->InvoiceNumber, 1, NULL);
					foreach($get_invoice_recip as $row_recip){
						$inv_number 			= $row_recip->InvoiceNumber;
						$inv_recip_id         	= $row_recip->InvoicePaymentID;
												  
						$inv_category_ratio     = $row_recip->ItemCategoryRatio;
						$inv_amount             = $row_recip->InvoiceAmount;
						
						$amount_advance         = ($row->PaymentAmount * $inv_category_ratio) / 100;
						$owing         			= ($row->InvoiceOwing * $inv_category_ratio) / 100;
						
						$data_at_invoicereceipt = array(
							'ReceiptAmount' 	=> $amount_advance,
							'ReceiptTotal' 		=> $amount_advance,
							'InvoiceOwing' 		=> $owing,
							
						);
						$this->m_sales_receipt->update_invoicerecip($data_at_invoicereceipt, $inv_recip_id);
					}*/
					/*====================================end=======================================================================*/
				}
			}
			
			$data_sr = array (
				'TransStatus'       => 2,						
				'AppLevel1Status'   => 1,
				'AppLevel1Code'     => $this->session->userdata("username"),
				'AppLevel1Date'     => date("Y-m-d"),	
				'AppFinished'       => 1,
				
				'LastUser'          => $this->session->userdata("username")
			);
			
			//Update Approval Finished for update Journal
			$this->m_sales_receipt->update($data_sr, $srec_number);
			
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_commit();
				$result['status']       = FALSE;
				$result['message']  = get_notification('approval', 0);
			}
			else {
				$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();
	}
	
	public function ajax_item_for_edit(){
        $id 		= $this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6);
	
        if(!empty($id)){
            echo json_encode($this->m_sales_expense->get_detail_invoice($id));
        }else{
            echo '[]';
        }
        
//        echo $this->db->last_query(); die();
    }
	
	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 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');
            $this->load->view('sales/sales_expense/v_print_detail_salesjournal', $data);
            $this->load->view('v_footer');	
        }
    }
	/*=====================end=====================================================*/
	
	public function suspend_data() {
		$SRecNumber 			= $this->input->post('id');
		$get_sales_jornal 	= $this->m_sales_expense->check_app_level_end_grid($SRecNumber);
		
		$this->db->trans_begin();
		$data_group = array(
			'TransStatus' => 3,
			'LastUser'      => $this->session->userdata("username")
		);
		$this->m_sales_receipt->update($data_group, $SRecNumber);		
		/*
			Update lock status 
		*/
		$data_customer  = array (
			'LockStatus'    => 0,
			'LastUser'      => $this->session->userdata("username")
		);

		$this->m_customer->update($data_customer, $get_sales_jornal->CustomerCode, $get_sales_jornal->BranchCode);
		/*===============End============================================*/
		
		/*===================Get Sordetail DP==========================================*/
		//if($Dp_Receipt > 0){
			$sordetail_dp    = $this->m_sales_receipt->get_saldo_detail_dp_sales_journal($get_sales_jornal);
			
			$saldo_dp 		 = $receipt_amount;
			foreach($sordetail_dp as $row_detail_dp){
				$is_edit 	 = 1;
					
				$update_sordetail = array(
					'DPUsedBook' 			=> $saldo_dp,
					'IsEdit' 				=> $is_edit
				);
				$this->m_sales_receipt->update_so_detail_dp_by_invoice($update_sordetail, $get_sales_jornal->SInvNumber);
			}
		//}
		/*========================End===================================================*/
							
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_commit();
			$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);		
	}
}