<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 * Author 	: Ferry / 29-01-2015
 */
 
class Purchase_expense extends CI_Controller {
    public $menu_id         = 363;
    public $menu_model      = array('m_purchase_order','m_purchase_invoice','m_purchase_payment','m_vendors', 'm_account_journal','m_purchase_expense');
    public $name            = "Purchase Journal";
    public $jobtitle_status = array('0', '1');
        
//    public $app_level       = array("DIR","MGR","SPV");
//    public $app1            = array("MGR","SPV");
//    public $app2            = array("DIR");

    public $branch          = "";
    public $ho;
	
    public function __construct(){
        parent::__construct();
		$this->load->model('custom/m_custom');
		$data_branch  = $this->m_custom->get_branch_detail();
		$this->branch = $this->session->userdata('branch');

		if($data_branch->BranchStatus == 0){
			$this->ho = true;
		}
		else{
			$this->ho = false;
		}

		$this->load->model($this->menu_model);
		$this->load->helper('regex');
		$this->load->helper('message');
		$this->load->helper('status');
    }

    public function index(){
       
	}
	
    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)
					*/
					//untuk ambil data dari session dan hak akses
					$group_menu 		= $this->session->userdata('group_menu');
					
					$data['menu_id']        = $this->menu_id;
					$data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
					$data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$data['ppay_date']      = date('d-m-Y');

					$this->load->view('v_header');
					$this->load->view('purchase/purchase_expense/v_new_purchasejournal',$data);
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }	
    }
	
   public function get_detail_invoice(){
        $vendor_code = $this->uri->segment(4);
		
        if(!empty($vendor_code)){
            $result = $this->m_purchase_expense->get_detail_item_for_pj($vendor_code);
            echo json_encode($result);
        }
        else{
            echo '[]';
        }
    }
	
	public function get_data_dp(){
        $vendor_code = $this->uri->segment(4);
		
        if(!empty($vendor_code)){
            $result = $this->m_purchase_expense->get_data_dp($vendor_code);
            echo json_encode($result);
        }
        else{
            echo '[]';
        }
    }
	
	function get_data_expense_by_pj(){
        $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_purchase_expense->get_detail_invoice_number($si_number, $invoice_type, $invoice_name));
        }
        else{
            echo '[]';
        }
    }
	
	public function ajax_expense_for_edit(){
        $id 		= $this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6);
	
        if(!empty($id)){
            echo json_encode($this->m_purchase_expense->get_detail_expense_invoice($id));
        }else{
            echo '[]';
        }
        
//        echo $this->db->last_query(); die();
    }
	
	public function insert(){
		/*====================================================================================*/
		/*
			deklar variabel from purchase jourmal dari group
		*/
		$BranchPaidFor 		= $this->input->post('cbg_branch');
		$VendorCode 		= $this->input->post('cbg_vendor');
		$SRecDate           = date("Y-m-d", strtotime($this->input->post('txt_sr_date')));
		/*=====================================jcos number==========================================*/
		$SRecNumber  		= $this->m_purchase_expense->create_pj_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');
		
		$detail 			= json_decode($this->input->post('detail'));
		/*=====================================end================================================*/
		if(count($detail)>0){
			$this->db->trans_begin();
			$get_vendro_for_lock_status = $this->m_purchase_payment->get_vendor_for_lock_status($VendorCode);
			if($get_vendro_for_lock_status->LockStatus == 1){
				$result['status']    = false;
            	$result['message']   = "Transaksi gagal, vendor code sudah di lock silahkan proses transaksi dengan vendor ".$get_vendro_for_lock_status->VendorName."";
				echo json_encode($result);
				die();
			}
			
			$this->insert_group($VendorCode,$BranchPaidFor, $SRecDate, $SRecNumber, $BankCode, $CurrencyCode, $CurrencyRate, $InvoiceType, $PPnFiscalStatus,$FiscalRate, $SInvTotalAmount,$SRecTotalOwing,$SRecTotalAmount,$SRecDesc);
			
			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->Invoice_Number;                    
				$invoice_amount     = $row->Invoice_Amount;
				$invoice_owing      = $row->Invoice_Owing;
				$invoice_type 		= $row->Invoice_Type;
				$invoice_type_id 	= $row->InvoiceTypeID;
				$invoice_currency 	= $row->InvoiceCurrCode;
				
				$InvoicePaymentID 	= $row->InvoicePaymentID;
				$InvoiceAmountCopy 	= $row->InvoiceAmountCopy;
				
				$invoice_date       = date("Y-m-d", strtotime($row->Invoice_Date));
				
				$receipt_amount     = $row->Payment_Amount; 
				$receipt_currency   = $row->Payment_Amount; 
				
				$CategoryName   	= $row->ItemCategoryName;
				$FiscalStatus_Detail 	= $row->PPnFiscalStatus;
				
				if($row->ItemCategoryName == 'PPn Fiscal'){
					$this->insert_detail_grid($CategoryName, $PPnFiscalStatus, $invoice_type_id, $InvoicePaymentID, $SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $invoice_owing, $invoice_rate, $fiscal_rate, $receipt_amount, $item_categori_id, $item_category_code);
					$this->insert_journal_ppn($BranchPaidFor,$fiscal_rate, $BankCode, $invoice_number, $invoice_rate, $invoice_currency, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc);
				}
				else{
					if($row->Invoice_Type == 'PI'){
						$this->insert_detail_grid($CategoryName,$PPnFiscalStatus, $invoice_type_id, $InvoicePaymentID, $SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $invoice_owing, $invoice_rate, $fiscal_rate, $receipt_amount, $item_categori_id, $item_category_code);
						$this->insert_journal_invoice($BranchPaidFor,$BankCode, $invoice_number, $invoice_rate, $invoice_currency, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc);
					}
					else{
						/*===================Get Sordetail DP==========================================*/
						//if($Dp_Receipt > 0){
							$pordetail_dp    		= $this->m_purchase_payment->get_saldo_detail_dp_for_pj($invoice_number);
							
							$saldo_dp 		 = $receipt_amount;
							foreach($pordetail_dp as $row_detail_dp){
								$is_edit 	 = 1;
								$update_sordetail = array(
									'DPUsedBook' 			=> $saldo_dp,
									'IsEdit' 				=> $is_edit
								);
								$this->m_purchase_payment->update_po_detail_dp_by_sal($update_sordetail, $invoice_number);
							}
						//}
						/*========================End===================================================*/
						
						$this->insert_detail_grid($CategoryName,$PPnFiscalStatus, $invoice_type_id, $InvoicePaymentID, $SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $invoice_owing, $invoice_rate, $fiscal_rate, $receipt_amount, $item_categori_id, $item_category_code);
						$this->insert_journal_dp($BranchPaidFor,$BankCode, $invoice_number, $invoice_rate, $invoice_currency, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc);
					}
				}
			}
			
			/*=============================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($VendorCode,$BranchPaidFor, $SRecDate, $SRecNumber, $BankCode, $CurrencyCode, $CurrencyRate, $InvoiceType, $PPnFiscalStatus,$FiscalRate, $SInvTotalAmount,$SRecTotalOwing,$SRecTotalAmount,$SRecDesc){
		$branch_code    	= $this->session->userdata('branch');
		$data_group = array(
			'BranchCode' 		=> $branch_code,
			'BranchPaidFor' 	=> $BranchPaidFor,
			'VendorCode' 		=> $VendorCode,
			'PPayDate' 			=> $SRecDate,
			'PPayNumber' 		=> $SRecNumber,
			'PPayDesc'	 		=> $SRecDesc,
			'CurrencyCode' 		=> $CurrencyCode,
			'BankPayment' 		=> $BankCode,
			'BankCurrCode' 		=> 'IDR',
			'BankCurrRate' 		=> $CurrencyRate,	
			'PPayTotalDPUsed' 	=> $InvoiceType == 'PO' ? $SRecTotalAmount : 0,			
			'PInvTotalAmount' 	=> $SInvTotalAmount,
			'PPayTotalAmount' 	=> $SRecTotalAmount,
			'PPayTotalCurrency' => $SRecTotalAmount,
			'PPayTotalOwing' 	=> $SRecTotalOwing,
			'TransStatus' 		=> 6,
			'PPnFiscalStatus' 	=> $PPnFiscalStatus,
			'PaymentStatus' 	=> 1,
			'CreatedBy' 		=> $this->session->userdata("username"),
			'CreatedAt' 		=> date('Y-m-d'),
			'LastUser' 			=> $this->session->userdata("username")
		);
		
		$this->m_purchase_payment->insert($data_group);
		/*
			Update vendor for lock status
		*/
		$data_vendor  = array (
			'LockStatus'    => 1,
			'LastUser'      => $this->session->userdata("username")
		);

		$this->m_vendors->update($data_vendor, $VendorCode, $BranchPaidFor);
		/*===========================end=================================================*/
	}
	
	function insert_detail_grid($CategoryName,$PPnFiscalStatus, $invoice_type_id, $InvoicePaymentID, $SRecNumber, $invoice_number, $invoice_date, $invoice_amount, $invoice_owing, $invoice_rate, $fiscal_rate, $receipt_amount, $item_categori_id, $item_category_code){
		$detail_data  = array(
			'InvoicePaymentID' 	=> $InvoicePaymentID,
			'PPayNumber' 		=> $SRecNumber,
			'PInvNumber' 		=> $invoice_number,
			'PInvDate' 			=> $invoice_date,
			'PInvOwing' 		=> $invoice_owing,
			'PInvAmount' 		=> $invoice_amount,
			'PInvCurrRate' 		=> $invoice_rate,
			'PInvFiscalRate' 	=> $fiscal_rate,
			'PPayCurrRate' 		=> $invoice_rate,
			'PPayAmount' 		=> $receipt_amount,
			'PPayTotalAmnt' 	=> $receipt_amount,
			'PInvAmountTemp' 	=> $invoice_amount,
			'PPayDPUsed' 		=> $invoice_type_id == 0 ? 0 : $receipt_amount,
			'PPayCurrency' 		=> $receipt_amount,
			'PInvCurrency' 		=> $invoice_amount,
			'CategoryName' 		=> $CategoryName,
			'PPayPaidStatus' 	=> 1,
			'PPayInvoiceType' 	=> $invoice_type_id,
			'PPayFiscalStatus' 	=> $PPnFiscalStatus,
			'ItemCategoryID' 	=> $item_categori_id,
			'ItemCategoryCode' 	=> $item_category_code,
			'LastUser' 			=> $this->session->userdata("username"),
		);
		
		$this->m_purchase_payment->insert_detail($detail_data);
	}
	
	function insert_journal_invoice($BranchPaidFor, $BankCode, $invoice_number, $invoice_rate, $CurrencyCode, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc){
		
		/*=====================Get Invoice Payment new Tabel=============================================*/
		/*
			(jika beda kategori tetapi akun nya sama, setting preferences)
		*/
		$payment_amount 		= $receipt_amount;
		$curr_account_no        = '';
		$CategoryIDDisc         = array();
		$CategoryIDCode         = array();
		
		$payable_value          = 0;
		$total_loop             = 0;
							
		$data_payment = $this->m_purchase_payment->get_payment($invoice_number, 0, 0);
		foreach($data_payment as $row_payment){
			$total_loop++;
			
			$ipay_payment_id        = $row_payment->InvoicePaymentID;
			$ipay_category_id       = $row_payment->ItemCategoryID;
			$ipay_category_code     = $row_payment->ItemCategoryCode;
			$ipay_category_ratio    = $row_payment->ItemCategoryRatio;
			$ipay_category_amount   = $row_payment->InvoiceOwing;
			$ipay_InvoiceAmount   	= $row_payment->InvoiceAmount;
										 
			if($ipay_category_id> 0){
				$PurchaseAccount    = $this->m_account_journal->get_cat_purchase_account('Payable', $ipay_category_id, $CurrencyCode);
				if($PurchaseAccount == false) {$this->trans_rollback('journal','Payable,','');}                                
			}
			else if($ipay_category_id == -1){
				$PurchaseAccount    = $this->m_account_journal->get_sys_service_account('Expense', 'IDR');                            
				if($PurchaseAccount == false) {$this->trans_rollback('preference','Exepnse, Expense','');}                                
			}
			else if($ipay_category_id == -2){
				$PurchaseAccount    = $this->m_account_journal->get_sys_advance_account('Expense', 'IDR'); 
				if($PurchaseAccount == false) {$this->trans_rollback('preference','Expense, Adv.Payment','');}                                
			}

			//$currency_payable       = $payment_currency * ($ipay_category_ratio / 100);
			$amount_payment         = $payment_amount * ($ipay_category_ratio / 100);
			$amount_total           = $amount_payment;
			
			if($total_loop == 1){$curr_account_no = $PurchaseAccount->AccountNumber;}
										
			//3. Journal Payable Account - Hutang Dagang
			if(strcmp($curr_account_no, $PurchaseAccount->AccountNumber) == -1){
				
				$payable_amount     = $CurrencyCode == 'IDR' ? $payable_value : $payable_value * $invoice_rate;
				$payable_currency   = $CurrencyCode == 'IDR' ? $payable_value : $payable_value;

				$journal_purchase   = array(
										'PPayDate'                  => $SRecDate,
										'PPayNumber'                => $SRecNumber,
										'PPayDesc'                  => $SRecDesc,
										'PPayAccountNumber'         => $curr_account_no,
										'PPaySaldoDebet'            => $payable_amount,
										'PPaySaldoCredit'           => 0,
										'AmountCurrency'            => $payable_currency,
										'PPaySignStatus'            => 1, 
										'ItemCategoryID'            => $item_categori_id,
										'BranchTransCode' 			=> $BranchPaidFor,
										'LastUser'                  => $this->session->userdata("username")	
									);

				$this->m_purchase_payment->insert_journal($journal_purchase);
				
				$curr_account_no    = $PurchaseAccount->AccountNumber;
				$payable_value      = $amount_total;
			}
			else{
				$payable_value      = $payable_value + $amount_total;
			}
			/*=====================End====================================================*/
		}
		
		/*
			Journall Payable Account - Hutang Dagang (satu akun satu kategori jalan kan fungsi sini)
		*/
		$payable_amount     = $CurrencyCode == 'IDR' ? $payable_value : $payable_value * $invoice_rate;
		$payable_currency   = $CurrencyCode == 'IDR' ? $payable_value : $payable_value;
		
		$journal_purchase   = array(
								'PPayDate'                  => $SRecDate,
								'PPayNumber'                => $SRecNumber,
								'PPayDesc'                  => $SRecDesc,
								'PPayAccountNumber'         => $PurchaseAccount->AccountNumber,
								'PPaySaldoDebet'            => $payable_amount,
								'PPaySaldoCredit'           => 0,
								'AmountCurrency'            => $payable_currency,
								'PPaySignStatus'            => 1, 
								'ItemCategoryID'            => $item_categori_id,
								'BranchTransCode' 			=> $BranchPaidFor,
								'LastUser'                  => $this->session->userdata("username")	
							);

		$this->m_purchase_payment->insert_journal($journal_purchase);
		/*=======================End==================================================================*/
		/*=============================End===============================================================*/
		
		/*
			Journal Akun Payment - Invoice Payment
		*/
		$payment_val = doubleval($payment_amount);
		
		if($payment_val > 0){
			
			$bank_amount    = $CurrencyCode == 'IDR' ? $payment_val : $payment_val * $invoice_rate;	
			$bank_currency  = $CurrencyCode == 'IDR' ? $payment_val : $payment_val;
			
			$get_sub_type 	= $this->m_purchase_expense->get_m_account_gl($BankCode);
			$nature_journal = $this->m_account_journal->debet_kredit($get_sub_type->TypeName, $get_sub_type->SubtypeName);
			
			if($nature_journal == "Debet"){
				$sign_status 	= 1;
			}
			else{
				$sign_status 	= 0;
			}
			
			$journal_bank   = array(
									'PPayDate'                  => $SRecDate,
									'PPayNumber'                => $SRecNumber,
									'PPayDesc'                  => $SRecDesc,
									'PPayAccountNumber'         => $BankCode,
									'PPaySaldoDebet'            => 0,
									'PPaySaldoCredit'           => $bank_amount,
									'AmountCurrency'            => $bank_currency,
									'PPaySignStatus'            => $sign_status, 
									'ItemCategoryID'            => $item_categori_id,
									'BranchTransCode' 			=> $BranchPaidFor,
									'LastUser'                  => $this->session->userdata("username")
								);

			$this->m_purchase_payment->insert_journal($journal_bank);
		}
		/*=======================End==================================================================*/
	}
	
	function insert_journal_ppn($BranchPaidFor, $fiscal_rate, $BankCode, $invoice_number, $invoice_rate, $CurrencyCode, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc){
		/*
			Insert Journal Hutang PPn Fiscal
		*/
		$payment_amount 	= $receipt_amount;
		$PPnFiscalAccount   = $this->m_account_journal->get_account_name('Hutang PPn Fiscal'); 
		if($PPnFiscalAccount == false) {$this->trans_rollback('journal','Purchase PPn Fiscal, Taxable','');}
		
		$fiscal_value    	= $CurrencyCode == 'IDR' ? $payment_amount : $payment_amount;	
		$fiscal_currency  	= $CurrencyCode == 'IDR' ? $payment_amount : $payment_amount / $fiscal_rate;
		//$fiscal_realize    	= $CurrencyCode == 'IDR' ? $payment_amount : ($payment_currency * $fiscal_rate);
		
		$journal_fiscal     = array(
								'PPayDate'              => $SRecDate,
								'PPayNumber'            => $SRecNumber,
								'PPayDesc'              => $SRecDesc,
								'PPayAccountNumber'     => $PPnFiscalAccount->AccountNumber,
								'PPaySaldoDebet'        => $fiscal_value,
								'PPaySaldoCredit'       => 0,
								'AmountCurrency'        => $fiscal_currency,
								'PPaySignStatus'        => 1, 
								'ItemCategoryID'        => $item_categori_id,
								'BranchTransCode' 		=> $BranchPaidFor,
								'LastUser'              => $this->session->userdata("username")	
							 );

		$this->m_purchase_payment->insert_journal($journal_fiscal);
		
		//$total_ppay_realizedgl = $total_ppay_realizedgl + $ppay_realizedgl;
		/*=====================End=================================================================*/
		
		/*
			Journal Akun Payment - Invoice Payment
		*/
		$payment_val = doubleval($payment_amount);
		
		if($payment_val > 0){
			
			$bank_amount    = $CurrencyCode == 'IDR' ? $payment_val : $payment_val;	
			$bank_currency  = $CurrencyCode == 'IDR' ? $payment_val : $payment_val / $fiscal_rate;
			
			$get_sub_type 	= $this->m_purchase_expense->get_m_account_gl($BankCode);
			$nature_journal = $this->m_account_journal->debet_kredit($get_sub_type->TypeName, $get_sub_type->SubtypeName);
			
			if($nature_journal == "Debet"){
				$sign_status 	= 1;
			}
			else{
				$sign_status 	= 0;
			}
			
			$journal_bank   = array(
									'PPayDate'                  => $SRecDate,
									'PPayNumber'                => $SRecNumber,
									'PPayDesc'                  => $SRecDesc,
									'PPayAccountNumber'         => $BankCode,
									'PPaySaldoDebet'            => 0,
									'PPaySaldoCredit'           => $bank_amount,
									'AmountCurrency'            => $bank_currency,
									'PPaySignStatus'            => $sign_status, 
									'ItemCategoryID'            => $item_categori_id,
									'BranchTransCode' 			=> $BranchPaidFor,
									'LastUser'                  => $this->session->userdata("username")
								);

			$this->m_purchase_payment->insert_journal($journal_bank);
		}
		/*=======================End==================================================================*/
	}
	
	function insert_journal_dp($BranchPaidFor, $BankCode, $invoice_number, $invoice_rate, $CurrencyCode, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc){
					
		/*
			Journal Akun Payment - Invoice Payment
		*/
		$payment_val = doubleval($receipt_amount);
		
		if($payment_val > 0){
			
			$bank_amount    = $CurrencyCode == 'IDR' ? $payment_val : $payment_val * $invoice_rate;	
			$bank_currency  = $CurrencyCode == 'IDR' ? $payment_val : $payment_val;
			
			$get_sub_type 	= $this->m_purchase_expense->get_m_account_gl($BankCode);
			$nature_journal = $this->m_account_journal->debet_kredit($get_sub_type->TypeName, $get_sub_type->SubtypeName);
			
			if($nature_journal == "Debet"){
				$sign_status 	= 0;
			}
			else{
				$sign_status 	= 1;
			}
			
			$journal_bank   = array(
									'PPayDate'                  => $SRecDate,
									'PPayNumber'                => $SRecNumber,
									'PPayDesc'                  => $SRecDesc,
									'PPayAccountNumber'         => $BankCode,
									'PPaySaldoDebet'            => $bank_amount,
									'PPaySaldoCredit'           => 0,
									'AmountCurrency'            => $bank_currency,
									'PPaySignStatus'            => $sign_status, 
									'ItemCategoryID'            => $item_categori_id,
									'BranchTransCode' 			=> $BranchPaidFor,
									'LastUser'                  => $this->session->userdata("username")
								);

			$this->m_purchase_payment->insert_journal($journal_bank);
		}
		/*=======================End==================================================================*/
		
		if($receipt_amount > 0) {
								
			$ItemStatusRatio    = array();
			$ItemStatusCatID    = array();
			$ItemStatusCatCode  = array();
			$data_payment       = $this->m_purchase_payment->get_payment($invoice_number, 1, 0);
			
			foreach($data_payment as $row_payment){
				@$ItemStatusRatio[$row_payment->ItemStatus]     += $row_payment->ItemCategoryRatio;
				@$ItemStatusCatID[$row_payment->ItemStatus]      = $row_payment->ItemCategoryID;
				@$ItemStatusCatCode[$row_payment->ItemStatus]    = $row_payment->ItemCategoryCode;
			}
		
			foreach($ItemStatusRatio as $key => $value){
				$ipay_category_id       = $ItemStatusCatID[$key];
				$ipay_category_code     = $ItemStatusCatCode[$key];
				$ipay_category_ratio    = $value;

				if($ipay_category_id > 0){
					$DPAccount  = $this->m_account_journal->get_cat_purchase_account('AdvancePurchase', $ipay_category_id, $CurrencyCode); // Uang Muka Category -> 1-4-03-001-00
					if($DPAccount == false) {$this->trans_rollback('preference','Uang Muka,','');}                                
				}
				else {
					$DPAccount  = $this->m_account_journal->get_sys_purchase_account('AdvancePurchase', $CurrencyCode); // Uang Muka Expense -> 1-4-03-001-00                            
					if($DPAccount == false) {$this->trans_rollback('preference','Uang Muka, Expense / Adv.Payment','');}                                
				}

				$amount_advance = $receipt_amount * ($ipay_category_ratio / 100);
				$dp_amount      = $CurrencyCode == 'IDR' ? $amount_advance : $amount_advance * $invoice_rate;
				$dp_currency   	= $CurrencyCode == 'IDR' ? $amount_advance : $amount_advance;

				$journal_dp     = array(
										'PPayDate'                  => $SRecDate,
										'PPayNumber'                => $SRecNumber,
										'PPayDesc'                  => $SRecDesc,
										'PPayAccountNumber'         => $DPAccount->AccountNumber,
										'PPaySaldoDebet'            => 0,
										'PPaySaldoCredit'           => $dp_amount,
										'AmountCurrency'            => $dp_currency,
										'PPaySignStatus'            => 1, 
										'ItemCategoryID'            => $item_categori_id,
										'BranchTransCode' 			=> $BranchPaidFor,
										'LastUser'                  => $this->session->userdata("username")
									);

				$this->m_purchase_payment->insert_journal($journal_dp);
			}
		}
	}
	
	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);

       // $id 		= str_replace($data['menu_link'].'/to_preview_journal/',"",$this->uri->uri_string());
		$id 		= $this->uri->segment(4).'/'.$this->uri->segment(5).'/'.$this->uri->segment(6);
		
        $data['detail'] = $this->m_purchase_expense->get_detail_journal($id);
		
        $data['list']   = $this->m_purchase_payment->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_expense/v_preview_journal_purchase_journal',$data);	
        $this->load->view('v_footer');	
    }
	
	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)
					*/
					//untuk ambil data dari session dan hak akses
					$group_menu 		= $this->session->userdata('group_menu');
					
					$data['menu_id']    = $this->menu_id;
					$data['menu_link']  = $this->m_menu->get_menulink($this->menu_id);
					$data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$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_purchase_expense->get_detail_expense($id_number);
					//$data['vendor']     = $this->m_vendors->get_saldo_by_id($data['detail']->VendorCode);
					//$data['vendor']     = $data['vendor'][0];

					if($data['detail'] != false){
						$this->load->view('v_header');
						$this->load->view('purchase/purchase_expense/v_edit_purchasejournal',$data);
						$this->load->view('v_footer');
					}
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
	public function update(){
		/*====================================================================================*/
		/*
			deklar variabel from purchase jourmal dari group
		*/
		$BranchPaidFor 		= $this->input->post('cbg_branch');
		$VendorCode 		= $this->input->post('cbg_vendor');
		$SRecDate           = date("Y-m-d", strtotime($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'); 
		$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');
		
		$detail 			= json_decode($this->input->post('detail'));
		/*=====================================end================================================*/
		
		if(count($detail)>0){
			$this->db->trans_begin();
			
			$this->m_purchase_payment->delete_journal($SRecNumber);
			$this->update_group($SRecNumber, $SRecDesc, $SInvTotalAmount, $SRecTotalAmount, $SRecTotalAmount, $SRecTotalOwing, $PPnFiscalStatus);
			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->Invoice_Number;                    
				$invoice_amount     = $row->Invoice_Amount;
				$invoice_owing      = $row->Invoice_Owing;
				$invoice_type 		= $row->Invoice_Type;
				$invoice_type_id 	= $row->InvoiceTypeID;
				$invoice_currency 	= $row->InvoiceCurrCode;
				
				$InvoicePaymentID 	= $row->InvoicePaymentID;
				$InvoiceAmountCopy 	= $row->InvoiceAmountCopy;
				
				$invoice_date       = date("Y-m-d", strtotime($row->Invoice_Date));
				
				$receipt_amount     = $row->Payment_Amount; 
				$receipt_currency   = $row->Payment_Amount; 
				
				$CategoryName   	= $row->ItemCategoryName;
				$FiscalStatus_Detail = $row->PPnFiscalStatus;
				$PPayDetailID 		= $row->PPayDetailID;
				
				if($row->ItemCategoryName == 'PPn Fiscal'){
					$this->update_detail_grid($PPayDetailID, $invoice_owing, $invoice_amount, $invoice_rate, $item_categori_id, $item_category_code, $receipt_amount);
					$this->insert_journal_ppn($BranchPaidFor,$fiscal_rate, $BankCode, $invoice_number, $invoice_rate, $invoice_currency, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc);
				}
				else{
					if($row->ItemCategoryName == 'Invoice'){
						$this->update_detail_grid($PPayDetailID, $invoice_owing, $invoice_amount, $invoice_rate, $item_categori_id, $item_category_code, $receipt_amount);
						$this->insert_journal_invoice($BranchPaidFor,$BankCode, $invoice_number, $invoice_rate, $invoice_currency, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc);
					}
					else{
						/*===================Get Sordetail DP==========================================*/
						//if($Dp_Receipt > 0){
							$pordetail_dp    		= $this->m_purchase_payment->get_saldo_detail_dp_for_pj($invoice_number);
							
							$saldo_dp 		 = $receipt_amount;
							foreach($pordetail_dp as $row_detail_dp){
								$is_edit 	 = 1;
								$update_sordetail = array(
									'DPUsedBook' 			=> $saldo_dp,
									'IsEdit' 				=> $is_edit
								);
								$this->m_purchase_payment->update_po_detail_dp_by_sal($update_sordetail, $invoice_number);
							}
						//}
						/*========================End===================================================*/
						
						$this->update_detail_grid($PPayDetailID, $invoice_owing, $invoice_amount, $invoice_rate, $item_categori_id, $item_category_code, $receipt_amount);
						$this->insert_journal_dp($BranchPaidFor,$BankCode, $invoice_number, $invoice_rate, $invoice_currency, $receipt_amount, $SRecDate, $SRecNumber, $item_categori_id, $SRecDesc);
					}
				}
			}
			
			/*=============================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, 'update', 0, '');
		}
		echo json_encode($result);
	}
	
	function update_group($SRecNumber, $SRecDesc, $SInvTotalAmount, $SRecTotalAmount, $SRecTotalAmount, $SRecTotalOwing, $PPnFiscalStatus){
		$data_group = array(
			'PPayDesc'	 		=> $SRecDesc,
			
			'PInvTotalAmount' 	=> $SInvTotalAmount,
			'PPayTotalAmount' 	=> $SRecTotalAmount,
			'PPayTotalCurrency' => $SRecTotalAmount,
			'PPayTotalOwing' 	=> $SRecTotalOwing,
			'PPnFiscalStatus' 	=> $PPnFiscalStatus,
		);
		
		$this->m_purchase_payment->update($data_group, $SRecNumber);
	}
	
	function update_detail_grid($PPayDetailID, $invoice_owing, $invoice_amount, $invoice_rate, $item_categori_id, $item_category_code, $receipt_amount){
		$detail_data  = array(
			'PInvOwing' 		=> $invoice_owing,
			'PInvAmount' 		=> $invoice_amount,
			'PInvCurrRate' 		=> $invoice_rate,
			'PPayCurrRate' 		=> $invoice_rate,
			'PPayAmount' 		=> $receipt_amount,
			'PPayTotalAmnt' 	=> $receipt_amount,
			'PInvAmountTemp' 	=> $invoice_amount,
			
			'PPayCurrency' 		=> $receipt_amount,
			'PInvCurrency' 		=> $invoice_amount,
			
			'ItemCategoryID' 	=> $item_categori_id,
			'ItemCategoryCode' 	=> $item_category_code,
			'LastUser' 			=> $this->session->userdata("username"),
		);
		
		$this->m_purchase_payment->update_detail($detail_data, $PPayDetailID);
	}
	
	public function approval(){
		/*=======================================deklar variabel=========================================*/
		$detail_post   		= $this->input->post('Detail');        
		$detail         	= json_decode($detail_post);
		
		
		/*=================end============================================================================*/
		 if(count($detail) > 0) {
			$this->db->trans_begin();
			$trans_status       = 2;
			$app_finished       = 0;
			
			$vendor_code      	= $this->input->post('VendCode');
			$ppay_number    	= $this->input->post('PPayNumber');
			$ppay_Date    		= $this->input->post('PPayDate');
			$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');
			$BranchCode     	= $this->input->post('BranchCode');
			$status             = $this->input->post('Status');
			
			$data               = $this->m_purchase_payment->check_app_level($ppay_number);
			
			if($status == 1) {
				if($data->AppLevel2Status != 1) {$trans_status = 5;}
			}
			else {
				if($data->AppLevel1Status != 1) {$trans_status = 4;}
			}
			
			if($trans_status == 2){
				$app_finished   = 1;
				$total_amount   = 0;
				$total_invoice   = 0;
				$total_DP       = 0;
				$Amount_DP_customer = 0;
				
				foreach($detail as $row){
					$invoice_number     = $row->Invoice_Number;
					$total_amount       = $row->Payment_Amount;
					$total_invoice 		= $row->Invoice_Amount;
					//$total_DP           = $row->Payment_DP;
				   // $total_discount     = $row->Payment_Discount;
					
					/*
						-3 == ppn fiscal,
						$row->Invoice_Type == PO/DP, dan PI/Invoice 
					*/
					if($row->ItemCategoryID == -3){
						/*
							Update vendor outstanding fiscal
						*/
						$total_payment_fiscal = $row->Payment_Amount / $row->InvoiceFiscalRate;
						$vendor_saldo   	= $this->m_vendors->get_saldo_by_id($vendor_code);
						$ppn_fiscal_debt    = $vendor_saldo[0]->OutStandingFiscal - $total_payment_fiscal;
						
						$data_vendor     = array (
							'LockStatus'    	=> 0,
							'OutStandingFiscal' => $ppn_fiscal_debt,
							'LastUser'          => $this->session->userdata("username")
						);
						$this->m_vendors->update($data_vendor, $vendor_code, $BranchCode);
						/*========================End===================================*/
						
						/*===================update paymen detail================================*/	
						$data_detail_ppaydet     = array (
							'PInvAmountTemp'    => $row->Invoice_Owing,
							'LastUser'          => $this->session->userdata("username")
						);
						$this->m_purchase_payment->update_detail($data_detail_ppaydet, $row->PPayDetailID);
						/*=========================end==============================================*/
					}
					else{
						if($row->Invoice_Type == "PI"){
							/*
								Update outstanding vendor
							*/
							$vendor_saldo   	= $this->m_vendors->get_saldo_by_id($vendor_code);
							$saldo_balance  	= $vendor_saldo[0]->OutStanding - $total_amount;
							$data_vendor    = array (
								'OutStanding'       => $saldo_balance,
								'LockStatus'    	=> 0,
								'LastUser'          => $this->session->userdata("username")
							 );
							 $this->m_vendors->update($data_vendor, $vendor_code, $BranchCode);
							 /*==============End================================================*/
							 
							 /*===================update paymen detail================================*/	
							$data_detail_ppaydet     = array (
								'PInvAmountTemp'    => $row->Invoice_Owing,
								'LastUser'          => $this->session->userdata("username")
							);
							$this->m_purchase_payment->update_detail($data_detail_ppaydet, $row->PPayDetailID);
							/*=========================end==============================================*/
						}
						else{
							/*===============================calculate dp partial=========================================================*/
							$vendor_dp          = $this->m_vendors->get_saldo_by_id($vendor_code);
							//$saldodp_paid       = $vendor_dp[0]->SaldoDPPaid - $total_amount;
							$DP_Vendor   		= $vendor_dp[0]->SaldoDPBalance;
							
							/*
								Jika pembayaran dp tidak sesuai currency di customer
								contoh customer usd bayar dp pake idr sedangkan dp yang disimpan di customer adalah usd
								maka rumus ini dijalankan
							*/
							$Amount_DP_customer = $row->InvoiceCurrCode == 'IDR' ? $total_amount / $row->InvoiceCurrRate : $total_amount; 
							$Inv_Amount_DP 		= $row->InvoiceCurrCode == 'IDR' ? $total_invoice / $row->InvoiceCurrRate : $total_invoice; 
							/*==================End====================================================*/
							
							//get sordetail dp
							$pordetail_dp    		= $this->m_purchase_payment->get_saldo_detail_dp_for_pj($invoice_number);
							$dp_used 		 = 0;
							foreach($pordetail_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_purchase_payment->update_po_detail_dp_by_vendor($update_sordetail, $vendor_code, $invoice_number);
								}
							}
							//end
					
							if($row->Invoice_Owing == 0){
								$DP_Vendor 	 = $DP_Vendor - $Inv_Amount_DP;
								$DPPartial	 = $DPPartial + $Amount_DP_customer;
								$DPPartial   = $DPPartial - $Inv_Amount_DP;
							}
							else{
								$DP_Vendor	 = $DP_Vendor;
								$DPPartial 	 = $DPPartial + $Amount_DP_customer;
							}
							/*========================end=================================================================================*/
						
							/*
								Update dp paid di vendor
							*/
							$data_vendor_dp     = array (
								//'SaldoDPPaid'       => $saldodp_paid,
								'SaldoDPBalance'    => $DP_Vendor,
								'LockStatus'    	=> 0,
								'SaldoDPPartial' 	=> $DPPartial,
								'LastUser'          => $this->session->userdata("username")
							);

							$this->m_vendors->update($data_vendor_dp, $vendor_code, $BranchCode);
							/*=================End==============================================================*/
						}
					}
					/*============================End======================================================================*/
					
					/*
						Update Invoice Payment table
					*/
					$data_ppay_detail   = $this->m_purchase_payment->get_ppay_detail($invoice_number, $ppay_number);
					
					foreach($data_ppay_detail as $row_detail){
						$inv_payment_id     = $row_detail->InvoicePaymentID;
						$payment_currency   = $Cust_curr_code == 'IDR' ? $row_detail->PPayCurrency : $row_detail->PPayCurrency * $currency_rate;
						
						$inv_disc_date  = empty($row_detail->PPayDiscDate) ? null: date("Y-m-d",strtotime($row_detail->PPayDiscDate));
						$data_payment   = $this->m_purchase_payment->get_payment_by_id($inv_payment_id);

						$payment_update = array(
											'InvoiceOwing'          => $row_detail->PInvOwing,
											'PaymentDiscDate'       => $inv_disc_date,
											'PaymentDiscount'       => $data_payment[0]->PaymentDiscount + $row_detail->PPayDiscount,
											'PaymentDPUsed'         => $data_payment[0]->PaymentDPUsed + $row_detail->PPayDPUsed,
											'PaymentAmount'         => $data_payment[0]->PaymentAmount + $row_detail->PPayAmount,
											'PaymentTotal'          => $data_payment[0]->PaymentTotal + $row_detail->PPayTotalAmnt,
											'PaymentCurrency'       => $data_payment[0]->PaymentCurrency + $payment_currency,
											'InvoiceCurrency'       => $data_payment[0]->InvoiceCurrency + $row_detail->PInvCurrency,
											'PaymentRealizedGL'     => $data_payment[0]->PaymentRealizedGL + $row_detail->PPayRealizedGL,
											'PaymentRounded'        => $data_payment[0]->PaymentRounded + $row_detail->PPayRounded,
										);

					   $this->m_purchase_payment->update_payment($payment_update, $inv_payment_id);
					}  
					/*==================End================================================================================================*/
				}
			 }
			//8. Update Approval Finished for update Journal
			if($status == 1) {
				if($data->AppLevel2Status != 1) {$trans_status = 5;}

				$data_pp = array (
								'TransStatus'       => $trans_status,						
								'AppLevel1Status'   => 1,
								'AppLevel1Code'     => $this->session->userdata("username"),
								'AppLevel1Date'     => date("Y-m-d"),	
								'AppFinished'       => $app_finished, 
								'LastUser'          => $this->session->userdata("username")
							);
			}
			else {
				if($data->AppLevel1Status != 1) {$trans_status = 4;}

				$data_pp = array (
								'TransStatus'       => $trans_status,						
								'AppLevel2Status'   => 1,
								'AppLevel2Code'     => $this->session->userdata("username"),
								'AppLevel2Date'     => date("Y-m-d"),	
								'AppFinished'       => $app_finished, 
								'LastUser'          => $this->session->userdata("username")
							);                
			}
			
			$this->m_purchase_payment->update($data_pp, $ppay_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();
	}
	
	function to_print_detail(){
        $data['menu_link']  = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $id = str_replace($data['menu_link'].'/to_print_detail/',"",$this->uri->uri_string());
        
        if($id!=""){		
            $data['detail'] = $this->m_purchase_expense->get_detail_print($id);
			//echo $this->db->last_query();
            $data['list'] = $this->m_purchase_expense->get_detail_invoice_print($data['detail']->PPayNumber);	
			
            $this->load->view('v_header');
            $this->load->view('purchase/purchase_expense/v_print_detail_purchasejournal', $data);	
            $this->load->view('v_footer');	
        }
    }
	
	public function suspend_data() {
		$ppay_number 			= $this->input->post('id');
		$get_purchase_jornal 	= $this->m_purchase_payment->check_app_level_end_grid($ppay_number);
		
		$this->db->trans_begin();
		$data_group = array(
			'TransStatus' => 3,
			'LastUser'      => $this->session->userdata("username")
		);
		$this->m_purchase_payment->update($data_group, $ppay_number);
		
		/*
			Update lock status 
		*/
		$data_vendor  = array (
			'LockStatus'    => 0,
			'LastUser'      => $this->session->userdata("username")
		);

		$this->m_vendors->update($data_vendor, $get_purchase_jornal->VendorCode, $get_purchase_jornal->BranchPaidFor);
		/*===============End============================================*/
		
		/*===================Get Sordetail DP==========================================*/
		//if($Dp_Receipt > 0){
			$pordetail_dp    		= $this->m_purchase_payment->get_saldo_detail_dp_for_pj($get_purchase_jornal->PInvNumber);
			
			$saldo_dp 		 = $get_purchase_jornal->PPayTotalAmount;
			foreach($pordetail_dp as $row_detail_dp){
				$is_edit 	 = 1;
				$dp_book 	 = $row_detail_dp->DPUsedBook - $saldo_dp;
				$update_sordetail = array(
					'DPUsedBook' 			=> $dp_book,
					'IsEdit' 				=> $is_edit
				);
				$this->m_purchase_payment->update_po_detail_dp_by_sal($update_sordetail, $get_purchase_jornal->PInvNumber);
			}
		//}
		/*========================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);		
	}
	
	public function ajax_account_expense(){
        echo json_encode($this->m_purchase_expense->get_account_expense());
    }
}