<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * Author 	: Ferry / 29-01-2015
 */

class Purchases_payment extends CI_Controller {

    public $menu_id = 172;
    public $menu_model = array('m_purchase_order', 'm_purchase_invoice', 'm_purchase_payment', 'm_vendors', 'm_account_journal', 'm_employee','m_purchase_dp','m_purchase_giro');
    public $name = "Purchase Payment";
    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');
        $this->load->helper('convert_date');
        $this->load->helper('custom_string_helper');
		$this->load->model('login/m_login');
	
		$is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
		if($is_login){

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

			$uri_func = $this->uri->segment(3);
			if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
				redirect(base_url() . 'login', 'refresh');
			}else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
				$result['status']   = 'session';
				$result['message']  = get_notification('session_destroy',0);
				echo json_encode($result);
				die();
			}
		}
    }

    public function index() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    //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['list_vendor'] = $this->m_purchase_order->get_all_vendor();

                    $this->load->view('v_header');
                    $this->load->view('purchase/purchase_payment/v_purchase_payment', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function add($PInvNumber = '', $branch = '', $VendorCode = '', $CurrencyCode = '', $txt_cheque_no = '', $txt_rate_bank = '') {
        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);
					$InvoiceNumber = str_replace('_','-',$PInvNumber);
					$InvoiceNumber_new = str_replace('--','/',$InvoiceNumber);
					
                    $get_pgir_number_to_payment = $this->m_purchase_payment->get_pgir_number_to_payment($InvoiceNumber_new);
					if($get_pgir_number_to_payment == false){
						$data['PInvNumber'] = $PInvNumber;
						$data['branch'] = $branch;
						$data['VendorCode'] = $VendorCode;
						$data['CurrencyCode'] = $CurrencyCode;
						$data['txt_cheque_no'] = str_replace("_","-",$txt_cheque_no);
						$data['txt_bank_curr_rate'] = $txt_rate_bank;
					}
					else{
						$data['PInvNumber'] = "";
						$data['branch'] = "";
						$data['VendorCode'] = "";
						$data['CurrencyCode'] = "";
						$data['txt_cheque_no'] = "";
						$data['txt_bank_curr_rate'] = "";
					}
					
					
					
                    //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_payment/v_new_purchase_payment', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function insert() {
        /* =============Deklar variabel====================================================================== */
        $BranchCode = $this->session->userdata('branch');
        $VendorCode = $this->input->post('cbg_vendor');
        $Branch_PaidFor = $this->input->post('cbg_branch');

        $Currency_Code = $this->input->post('hdn_vend_curr_code');
        $BankPayment = $this->input->post('cbg_bank');

        $Bank_Curr_Code = $this->input->post('hdn_bank_curr_code');
        $Bank_Number = $this->input->post('hdn_bank_number');

        $Bank_Curr_Rate = $this->input->post('txt_bank_curr_rate');
        $PPayDate = date("Y-m-d", strtotime($this->input->post('txt_ppay_date')));
        $PPayNumber = $this->m_purchase_payment->create_pp_number($PPayDate, $Bank_Number);
        $PPayDesc = $this->input->post('txa_description');
		$PGirNumber = $this->input->post('hdn_pgir_number');
		
        $ppnfiscal_status = $this->input->post('chk_fiscal_payment');
        $ChequeNumber = $this->input->post('txt_cheque_no');
        $ChequeAmount = $this->input->post('txt_cheque_amount');
        $DPTotal = $this->input->post('txt_vendor_dp_return');

        $TotalAmount = $this->input->post('txt_total_amount');
        $AmountVendorDP = $this->input->post('txt_vendor_dp_return');
        $VendorDpPartial = $this->input->post('txt_vend_dp_part');
        $hdn_total_currency = $this->input->post('hdn_total_currency');
        $hdn_PInvTotalAmount = $this->input->post('hdn_PInvTotalAmount');
        $hdn_PPayTotalOwing = $this->input->post('hdn_PPayTotalOwing');
        $hdn_PPayTotalDPUsed = $this->input->post('hdn_PPayTotalDPUsed');
        $hdn_PPayTotalDiscount = $this->input->post('hdn_PPayTotalDiscount');
        /* =====================End======================================================================= */

        $detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);

//       print_r($detail);die();

        if (count($detail) > 0) {
            $this->db->trans_begin();

            $total_dp_used = 0;
            $total_disc_used = 0;
            $total_amount_paid = 0;
            $total_currency_paid = 0;
            $total_ppay_realizedgl = 0;

            $total_invoice = 0;
            $total_owing = 0;
			
			$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 . "";
                $this->db->trans_rollback();
                echo json_encode($result);
                die();
            }
            /*
              Insert group purchase payment
             */
            $this->insert_group($PGirNumber, $hdn_PPayTotalDPUsed, $hdn_PPayTotalDiscount, $hdn_PPayTotalOwing, $hdn_PInvTotalAmount, $TotalAmount, $AmountVendorDP, $hdn_total_currency, $BranchCode, $Branch_PaidFor, $VendorCode, $PPayDate, $PPayDesc, $PPayNumber, $PPayNumber, $BankPayment, $Currency_Code, $Bank_Curr_Code, $Bank_Curr_Rate, $ChequeNumber, $ChequeAmount, $ppnfiscal_status);
            /* ==============================End============================================== */

            foreach ($detail as $row) {
                if ($row->Paid == 'Yes') {
                    $item_category_id = $row->ItemCategoryID;

                    $invoice_rate = $row->InvoiceCurrRate;
                    $fiscal_rate = $row->InvoiceFiscalRate;
                    $invoice_number = $row->Invoice_Number;
                    $invoice_amount = $row->Invoice_Amount;
                    $invoice_owing = $row->Invoice_Owing;
                    $invoice_copy = $row->InvoiceAmountCopy;
                    $invoice_owing_temp = $row->InvoiceOwingHiddenNew;
                    $invoice_owing_copy = $row->InvoiceOwingHidden;

                    $total_hutang = $invoice_owing_copy - $invoice_owing_temp;

                    $payment_dp = $row->Payment_DP;
                    $payment_disc = $row->Payment_Discount;
                    $payment_amount = $row->Payment_Amount;
                    $payment_currency = $row->Payment_Currency;
                    $Load_Rounding = $row->Load_Rounding;
                    $Select_DP = $row->Select_DP;
                    $Relized_all_trans = $payment_disc + $payment_amount;

                    $Advanced = '';
                    $total_dp = 0;
                    $relize_dp = 0;
                    $total_relize = 0;

                    $invoice_currency = $Currency_Code == 'IDR' ? $payment_amount : $payment_amount * $invoice_rate;
                    if ($Currency_Code == 'IDR') {
                        $invoice_currency = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;
                    } else {
                        $invoice_currency = $Bank_Curr_Code == 'IDR' ? $payment_amount * $Bank_Curr_Rate : $payment_amount;
                    }

//                    $payment_realizedgl = $Bank_Curr_Rate == 'IDR' ? $payment_currency : $payment_currency * $Bank_Curr_Rate) - $invoice_currency;

                    $invoice_date = date("Y-m-d", strtotime($row->Invoice_Date));
                    $ppay_disc_date = empty($row->Payment_DiscDate) ? null : date("Y-m-d", strtotime($row->Payment_DiscDate));

                    $total_invoice += $invoice_amount;
                    $total_owing += $invoice_owing;

                    //-------------------------------------------------------------------------------------------------//

                    /*
                      Insert Fiscal, PI OR PO
                     */
                    if ($item_category_id == -3) {
                        $total_amount_paid += $payment_amount;
                        $total_currency_paid += $payment_currency;

                        $this->insert_ppn_fiscal($total_hutang, $invoice_owing_temp, $payment_currency, $Bank_Curr_Code, $payment_amount, $Load_Rounding, $total_currency_paid, $total_amount_paid, $item_category_id, $BankPayment, $Currency_Code, $invoice_number, $invoice_date, $Bank_Curr_Rate, $PPayNumber, $PPayDate, $PPayDesc, $invoice_amount, $invoice_owing, $invoice_rate, $fiscal_rate, $payment_currency, $invoice_currency, $Branch_PaidFor);
                    } else {

                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                        if ($RealizedAccount == false) {
                            $this->trans_rollback('journal', 'Realized G/L, Purchase', '');
                        }

                        if (($row->Invoice_Type == 'PI') && ($item_category_id != -3)) {

                            $curr_account_no = '';
                            $CategoryIDDisc = array();
                            $CategoryIDCode = array();
                            $CategoryType = array();

                            $payable_value = 0;
                            $total_loop = 0;
                            $payable_amount = 0;
                            $payable_currency = 0;
                            $total_ppay_realizedgl = 0;
                            $total_ppay_realizedgl_new = 0;

                            $total_hutang_beban = 0;
                            $total_hutang_beban_new = 0;

                            $total_amount_paid = 0;
                            $total_currency_paid = 0;
                            /* =====================Get Invoice Payment new Tabel============================================= */
                            $data_payment = $this->m_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;
                                $ipay_item_type = $row_payment->ItemType;
                                $ipay_ItemCategoryRatio = $row_payment->ItemCategoryRatio;
                                $ipay_InvoiceCurrRate = $row_payment->InvoiceCurrRate;


                                if ($ipay_item_type == 0) {
                                    $PurchaseAccount = $this->m_account_journal->get_cat_purchase_account('Payable', $ipay_category_id, $Currency_Code);
                                    if ($Currency_Code == 'IDR') {
                                        if ($PurchaseAccount == false) {
                                            $this->trans_rollback('preference', 'Purchase Account -> Account Payable', $Currency_Code);
                                        }
                                    } else {
                                        if ($PurchaseAccount == false) {
                                            $this->trans_rollback('journal', 'Hutang Dagang', $Currency_Code);
                                        }
                                    }
                                    $Sign_Status_PurchaseAccount = 1;
                                } else {
                                    if ($ipay_item_type == 1) {
                                        $PurchaseAccount = $this->m_account_journal->get_sys_service_account('Unbilled', $Currency_Code); // PPh Jasa / Service 
                                        if ($Currency_Code == 'IDR') {
                                            if ($PurchaseAccount == false) {
                                                $this->trans_rollback('preference', 'Expense Account -> Purchase Unbilled (Owing)', $Currency_Code);
                                            }
                                        } else {
                                            if ($PurchaseAccount == false) {
                                                $this->trans_rollback('journal', 'Hutang Expense', $Currency_Code);
                                            }
                                        }
                                        $Sign_Status_PurchaseAccount = 1;
                                    } else {
                                        $PurchaseAccount = $this->m_account_journal->get_sys_advance_account('Unbilled', $Currency_Code); // Adv. Payment
                                        if ($Currency_Code == 'IDR') {
                                            if ($PurchaseAccount == false) {
                                                $this->trans_rollback('preference', 'Adv Payment Account -> Unbilled (Owing)', $Currency_Code);
                                            }
                                        } else {
                                            if ($PurchaseAccount == false) {
                                                $this->trans_rollback('journal', 'Hutang Advanced Payment', $Currency_Code);
                                            }
                                        }
                                        $Sign_Status_PurchaseAccount = 1;
                                    }
                                }

                                $amount_invoice = $invoice_copy * ($ipay_category_ratio / 100);
                                $amount_owing_real = $invoice_owing * ($ipay_category_ratio / 100);
                                $amount_owing_temp = $invoice_owing_temp * ($ipay_category_ratio / 100);
                                $amount_owing_copy = $total_hutang * ($ipay_category_ratio / 100);

                                $currency_payable = $payment_currency * ($ipay_category_ratio / 100);
                                $amount_payment = $payment_amount * ($ipay_category_ratio / 100);
                                $currency_payable = $payment_currency * ($ipay_category_ratio / 100);

                                $amount_dpused = $payment_dp * ($ipay_category_ratio / 100);
                                $amount_discount = $payment_disc * ($ipay_category_ratio / 100);
                                $amount_rounded = $Load_Rounding * ($ipay_category_ratio / 100);

                                if ($invoice_owing == 0) {
                                    $amount_total_journal = $amount_owing_copy;
                                } else {
                                    $amount_total_journal = $amount_dpused + $amount_discount + $amount_rounded + $amount_payment;
                                }

                                if ($Currency_Code == 'IDR') {
                                    $amount_total = $amount_dpused + $amount_discount + $amount_payment;
                                    $amount_total_selisih = $amount_discount + $amount_payment;
                                } else {
                                    if ($Bank_Curr_Code == 'IDR') {
                                        $amount_total = $amount_dpused + $amount_discount + ($currency_payable / $Bank_Curr_Rate);
                                        $amount_total_selisih = $amount_discount + ($currency_payable / $Bank_Curr_Rate);
                                    } else {
                                        $amount_total = $amount_dpused + $amount_discount + $amount_payment;
                                        $amount_total_selisih = $amount_discount + $amount_payment;
                                    }
                                }

                                if ($Currency_Code == 'IDR') {
                                    $inv_cat_curr_amount = $amount_total;
                                    $pay_cat_curr_amount = $amount_total;
                                } else {
                                    $inv_cat_curr_amount = $amount_total_selisih * $invoice_rate;
                                    $pay_cat_curr_amount = $amount_total_selisih * $Bank_Curr_Rate;
                                }

                                $ppay_cat_realizedgl = $pay_cat_curr_amount - $inv_cat_curr_amount;
                                //$new_invoice_owing      = $amount_invoice - ($amount_total + $amount_rounded);

                                if ($total_loop == 1) {
                                    $curr_account_no = $PurchaseAccount->AccountNumber;
                                }

                                if ($payment_disc > 0) {
                                    @$CategoryIDDisc[$ipay_category_id] = $amount_discount;
                                    @$CategoryIDCode[$ipay_category_id] = $ipay_category_code;
                                    @$CategoryType[$ipay_category_id] = $ipay_item_type;
                                }

                                //2.Insert ppaydetail
                                $this->insert_detail(
                                        $PPayDate,NULL, $ipay_ItemCategoryRatio, $Select_DP, $ipay_payment_id, $PPayNumber, $invoice_number, $invoice_date, $ipay_InvoiceAmount, $amount_owing_temp, $invoice_rate, $fiscal_rate, $Bank_Curr_Rate, $ppay_disc_date, $amount_discount, $amount_dpused, $amount_payment, $amount_total, $currency_payable, $inv_cat_curr_amount, $ppay_cat_realizedgl, $amount_rounded, 0, $ipay_category_id, $ipay_category_code, $ipay_category_amount, $ipay_item_type, 0
                                );
                                //---------------------------------------------------------------------------------------------//

                                /*
                                  Journal Hutang dagang
                                 */
                                if ($Currency_Code == 'IDR') {
                                    $payable_amount = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal;
                                    $payable_currency = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal / $Bank_Curr_Rate;
                                } else {
                                    $payable_amount = $Bank_Curr_Code == 'IDR' ? $amount_total_journal * $ipay_InvoiceCurrRate : $amount_total_journal * $ipay_InvoiceCurrRate;
                                    $payable_currency = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal;
                                }

                                $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment($PurchaseAccount->AccountNumber, $PPayNumber, $invoice_number);
                                /*
                                  Check Invoice sama atau tidak
                                 */
                                if (empty($get_journal_purchase_payment->PPayAccountNumber)) {
                                    $journal_purchase = array(
                                        'PPayDate' => $PPayDate,
                                        'PPayNumber' => $PPayNumber,
                                        'PPayDesc' => $PPayDesc,
                                        'PPayAccountNumber' => $PurchaseAccount->AccountNumber,
                                        'PPaySaldoDebet' => $payable_amount,
                                        'PPaySaldoCredit' => 0,
                                        'AmountCurrency' => $payable_currency,
                                        'PPaySignStatus' => $Sign_Status_PurchaseAccount,
                                        'ItemCategoryID' => $ipay_category_id,
                                        'BranchTransCode' => $Branch_PaidFor,
                                        'PInvNumber' => $invoice_number,
                                        'LastUser' => $this->session->userdata("username")
                                    );

                                    $this->m_purchase_payment->insert_journal($journal_purchase);
                                } else {
                                    $payable_amount = $payable_amount + $get_journal_purchase_payment->PPaySaldoDebet;
                                    $payable_currency = $payable_currency + $get_journal_purchase_payment->AmountCurrency;

                                    $journal_purchase = array(
                                        'PPaySaldoDebet' => $payable_amount,
                                        'PPaySaldoCredit' => 0,
                                        'AmountCurrency' => $payable_currency
                                    );

                                    $this->m_purchase_payment->update_journal_invoice($PPayNumber, $journal_purchase, $get_journal_purchase_payment->PPayAccountNumber, $invoice_number);
                                }
                                /* =========================End=============================== */
                            }
                            /* =============================End=============================================================== */

                            /*
                              Journal Bank Payment - Invoice Payment
                             */
                            $payment_val = doubleval($payment_amount);
                            $bank_amount = 0;
                            $bank_currency = 0;

                            if ($payment_val > 0) {

                                if ($Currency_Code == 'IDR') {
                                    $bank_amount = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;
                                    $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val / $Bank_Curr_Rate;
                                } else {
                                    $bank_amount = $Bank_Curr_Code == 'IDR' ? ($payment_currency / $Bank_Curr_Rate) * $Bank_Curr_Rate : $payment_val * $Bank_Curr_Rate;
                                    $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_currency / $Bank_Curr_Rate : $payment_val;
                                }

                                $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment_no_invoice($BankPayment, $PPayNumber);


                                $journal_bank = array(
                                    'PPayDate' => $PPayDate,
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BankPayment,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => $bank_amount,
                                    'AmountCurrency' => $bank_currency,
                                    'PPaySignStatus' => 1,
                                    'PInvNumber' => $invoice_number,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($journal_bank);

                                $total_amount_paid += $payment_amount;
                                $total_currency_paid += $payment_currency;
                            }
                            /* =======================End================================================================== */


                            /*
                              Journal Advance Purchase - Uang Muka Pembelian
                             */
                            $total_dp = 0;
                            $total_dp_no_currency = 0;

                            if ($payment_dp > 0) {

                                /* ===================Get Pordetail DP========================================== */
                                $sordetail_dp = $this->m_purchase_payment->get_saldo_detail_dp($VendorCode, $Select_DP, 1);

                                $saldo_dp = $payment_dp;
                                $saldo_dp_new = $payment_dp;

                                $jurnal_dp = 0;
                                $jurnal_dp_currency = 0;
                                $jurnal_dp_no_currency = 0;
                                $currency_rate_detail = 0;
                                $is_edit = "";
                                $PaymentBefore = 0;
                                $PaymentBefore_Sum = 0;
                                $PaymentPlus = 0;
                                $PaymentPlus_Sum = 0;

                                $relize_debet = 0;
                                $relize_kredit = 0;
                                $total_dp = 0;

                                foreach ($sordetail_dp as $row_detail_dp) {
                                    $DPUsed = $row_detail_dp->DPUsed;
                                    $JVoucherBalance = $row_detail_dp->JVoucherBalance;
                                    $SaldoDPBalance = $row_detail_dp->SaldoDPBalance;
                                    $currency_rate_detail = $row_detail_dp->CurrencyRate;

                                    $DPUsed = $DPUsed + $JVoucherBalance;
                                    if ($DPUsed != $SaldoDPBalance) {
                                        $dp_used_book = 0;
                                        $saldo_balance_detail = $row_detail_dp->PaymentAmount;
                                        $SOrdDetailDPID = $row_detail_dp->POrdDetailDPID;
                                        $SaldoDPBalance = $row_detail_dp->SaldoDPBalance;

                                        if ($saldo_dp > 0) {
                                            //echo $saldo_dp;
                                            $saldo_dp = doubleval($saldo_dp_new - ($PaymentPlus_Sum + $saldo_balance_detail));
                                            //$saldo_dp = doubleval($saldo_dp_new - $saldo_balance_detail);

                                            if ($saldo_dp < 0) {
                                                $dp_used_old = $DPUsed;
                                                $dp_used_book = doubleval($DPUsed + ($saldo_dp_new - $PaymentBefore_Sum));
                                                $jurnal_dp = (doubleval(($saldo_dp_new - $PaymentBefore_Sum) * $currency_rate_detail));
                                                $jurnal_dp_currency = (doubleval($saldo_dp_new - $PaymentBefore_Sum / $currency_rate_detail));
                                                $jurnal_dp_no_currency = doubleval($saldo_dp_new - $PaymentBefore_Sum);
                                                $update_sordetail = array(
                                                    'DPUsed' => $dp_used_book
                                                );
                                                $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_sordetail, $VendorCode, $SOrdDetailDPID, $Select_DP);

                                                $DPAccount = $this->m_account_journal->get_account_name('Uang Muka Pembelian', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
                                                if ($DPAccount == false) {
                                                    $this->trans_rollback('journal', 'Uang Muka Pembelian', '');
                                                }

                                                if ($Currency_Code == 'IDR') {
                                                    $dp_currency = $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_currency / $Bank_Curr_Rate;
                                                } else {
                                                    $dp_currency = $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_no_currency;
                                                }

                                                $journal_dp = array(
                                                    'PPayDate' => $PPayDate,
                                                    'PPayNumber' => $PPayNumber,
                                                    'PPayDesc' => $PPayDesc,
                                                    'PPayAccountNumber' => $DPAccount->AccountNumber,
                                                    'PPaySaldoDebet' => 0,
                                                    'PPaySaldoCredit' => $jurnal_dp,
                                                    'AmountCurrency' => $dp_currency,
                                                    'PPaySignStatus' => 1,
                                                    'ItemCategoryID' => $item_category_id,
                                                    'BranchTransCode' => $Branch_PaidFor,
                                                    'PInvNumber' => $invoice_number,
                                                    'POrdDetailDPID' => $row_detail_dp->POrdDetailDPID,
                                                    'LastUser' => $this->session->userdata("username")
                                                );
                                                if ($jurnal_dp > 0) {
                                                    $this->m_purchase_payment->insert_journal($journal_dp);
                                                }

                                                if ($Currency_Code != 'IDR') {
                                                    $inv_dp_selisih_kurs = doubleval($jurnal_dp) - doubleval($jurnal_dp_no_currency * $invoice_rate);
                                                    if ($inv_dp_selisih_kurs > 0) {
                                                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                                                        if ($RealizedAccount == false) {
                                                            $this->trans_rollback('journal', 'Realized, Purchase', $Currency_Code);
                                                        }

                                                        $realized_amount = abs($inv_dp_selisih_kurs);
                                                        $realized_currency = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;

                                                        $journal_RealizedAccount = array(
                                                            'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                                            'PPayNumber' => $PPayNumber,
                                                            'PPayDesc' => $PPayNumber,
                                                            'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                                            'PPaySaldoDebet' => $realized_amount,
                                                            'PPaySaldoCredit' => 0,
                                                            'AmountCurrency' => 0,
                                                            'PPaySignStatus' => 0,
                                                            'ItemCategoryID' => $item_category_id,
                                                            'BranchTransCode' => $Branch_PaidFor,
                                                            'PInvNumber' => $invoice_number,
                                                            'LastUser' => $this->session->userdata("username")
                                                        );

                                                        $this->m_purchase_payment->insert_journal($journal_RealizedAccount);
                                                    } else if ($inv_dp_selisih_kurs < 0) {
                                                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                                                        if ($RealizedAccount == false) {
                                                            $this->trans_rollback('journal', 'Realized, Purchase', $Currency_Code);
                                                        }

                                                        $realized_amount = abs($inv_dp_selisih_kurs);
                                                        $realized_currency = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;

                                                        $journal_RealizedAccount = array(
                                                            'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                                            'PPayNumber' => $PPayNumber,
                                                            'PPayDesc' => $PPayNumber,
                                                            'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                                            'PPaySaldoDebet' => 0,
                                                            'PPaySaldoCredit' => $realized_amount,
                                                            'AmountCurrency' => 0,
                                                            'PPaySignStatus' => 1,
                                                            'ItemCategoryID' => $item_category_id,
                                                            'BranchTransCode' => $Branch_PaidFor,
                                                            'PInvNumber' => $invoice_number,
                                                            'LastUser' => $this->session->userdata("username")
                                                        );
                                                        $this->m_purchase_payment->insert_journal($journal_RealizedAccount);
                                                    }
                                                }
                                                $total_dp += $jurnal_dp;
                                                $total_dp_no_currency += $jurnal_dp_no_currency;
                                            } else {
                                                $PaidStatus = $DPUsed;
                                                $dp_used_book = doubleval(($saldo_balance_detail - $DPUsed) + $PaidStatus);
                                                $jurnal_dp = (doubleval($saldo_balance_detail - $DPUsed) * doubleval($currency_rate_detail));
                                                $jurnal_dp_currency = (doubleval($saldo_balance_detail - $DPUsed) / doubleval($currency_rate_detail));
                                                $jurnal_dp_no_currency = doubleval($saldo_balance_detail - $DPUsed);

                                                $update_sordetail = array(
                                                    'DPUsed' => $dp_used_book
                                                );
                                                $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_sordetail, $VendorCode, $SOrdDetailDPID, $Select_DP);
                                                $PaymentBefore = doubleval($saldo_balance_detail - $DPUsed);
                                                $PaymentBefore_Sum += $PaymentBefore;
                                                $PaymentPlus = doubleval($saldo_balance_detail + $DPUsed);
                                                $PaymentPlus_Sum += $PaymentPlus;

                                                $DPAccount = $this->m_account_journal->get_account_name('Uang Muka Pembelian', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
                                                if ($DPAccount == false) {
                                                    $this->trans_rollback('journal', 'Uang Muka Pembelian', '');
                                                }

                                                if ($Currency_Code == 'IDR') {
                                                    $dp_currency = $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_currency / $Bank_Curr_Rate;
                                                } else {
                                                    $dp_currency = $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_no_currency;
                                                }

                                                $journal_dp = array(
                                                    'PPayDate' => $PPayDate,
                                                    'PPayNumber' => $PPayNumber,
                                                    'PPayDesc' => $PPayDesc,
                                                    'PPayAccountNumber' => $DPAccount->AccountNumber,
                                                    'PPaySaldoDebet' => 0,
                                                    'PPaySaldoCredit' => $jurnal_dp,
                                                    'AmountCurrency' => $dp_currency,
                                                    'PPaySignStatus' => 1,
                                                    'ItemCategoryID' => $item_category_id,
                                                    'BranchTransCode' => $Branch_PaidFor,
                                                    'PInvNumber' => $invoice_number,
                                                    'POrdDetailDPID' => $row_detail_dp->POrdDetailDPID,
                                                    'LastUser' => $this->session->userdata("username")
                                                );
                                                if ($jurnal_dp > 0) {
                                                    $this->m_purchase_payment->insert_journal($journal_dp);
                                                }

                                                if ($Currency_Code != 'IDR') {
                                                    $inv_dp_selisih_kurs = doubleval($jurnal_dp) - doubleval($jurnal_dp_no_currency * $invoice_rate);
                                                    if ($inv_dp_selisih_kurs > 0) {
                                                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                                                        if ($RealizedAccount == false) {
                                                            $this->trans_rollback('journal', 'Realized, Purchase', $Currency_Code);
                                                        }

                                                        $realized_amount = abs($inv_dp_selisih_kurs);
                                                        $realized_currency = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;

                                                        $journal_RealizedAccount = array(
                                                            'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                                            'PPayNumber' => $PPayNumber,
                                                            'PPayDesc' => $PPayNumber,
                                                            'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                                            'PPaySaldoDebet' => $realized_amount,
                                                            'PPaySaldoCredit' => 0,
                                                            'AmountCurrency' => 0,
                                                            'PPaySignStatus' => 0,
                                                            'ItemCategoryID' => $item_category_id,
                                                            'BranchTransCode' => $Branch_PaidFor,
                                                            'PInvNumber' => $invoice_number,
                                                            'LastUser' => $this->session->userdata("username")
                                                        );

                                                        $this->m_purchase_payment->insert_journal($journal_RealizedAccount);
                                                    } else if ($inv_dp_selisih_kurs < 0) {
                                                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                                                        if ($RealizedAccount == false) {
                                                            $this->trans_rollback('journal', 'Realized, Purchase', $Currency_Code);
                                                        }

                                                        $realized_amount = abs($inv_dp_selisih_kurs);
                                                        $realized_currency = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;

                                                        $journal_RealizedAccount = array(
                                                            'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                                            'PPayNumber' => $PPayNumber,
                                                            'PPayDesc' => $PPayNumber,
                                                            'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                                            'PPaySaldoDebet' => 0,
                                                            'PPaySaldoCredit' => $realized_amount,
                                                            'AmountCurrency' => 0,
                                                            'PPaySignStatus' => 1,
                                                            'ItemCategoryID' => $item_category_id,
                                                            'BranchTransCode' => $Branch_PaidFor,
                                                            'PInvNumber' => $invoice_number,
                                                            'LastUser' => $this->session->userdata("username")
                                                        );
                                                        $this->m_purchase_payment->insert_journal($journal_RealizedAccount);
                                                    }
                                                }

                                                $total_dp += $jurnal_dp;
                                                $total_dp_no_currency += $jurnal_dp_no_currency;
                                            }
                                        }
                                        $update_isedit = array(
                                            'IsEdit' => 1
                                        );
                                        $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_isedit, $VendorCode, $SOrdDetailDPID, $Select_DP);
                                    }
                                }
                                /* ========================End=================================================== */
                            }
                            /* =======================End================================================================== */

                            /*
                              Journal Discount Invoice - Potongan Pembelian
                             */
                            $total_discount = 0;
                            if ($payment_disc > 0) {
                                $total_loop = 0;
                                $curr_account_no = '';

                                $discount_amount = 0;
                                $discount_currency = 0;
                                $invoice_loop_disc = "";

                                foreach ($data_payment as $row_disc) {
                                    $ipay_payment_id_disc = $row_disc->InvoicePaymentID;
                                    $ipay_category_id_disc = $row_disc->ItemCategoryID;
                                    $ipay_category_code_disc = $row_disc->ItemCategoryCode;
                                    $ipay_category_ratio_disc = $row_disc->ItemCategoryRatio;
                                    $ipay_category_amount_disc = $row_disc->InvoiceOwing;
                                    $ipay_InvoiceAmount_disc = $row_disc->InvoiceAmount;
                                    $ipay_item_type_disc = $row_disc->ItemType;
                                    $ipay_InvoiceNumber = $row_disc->InvoiceNumber;

                                    if ($ipay_item_type_disc == 0) {
                                        $DiscountAccount = $this->m_account_journal->get_cat_purchase_account('PaymentDiscount', $ipay_category_id_disc, $Currency_Code); // Potongan Pembelian
                                        if ($Currency_Code == 'IDR') {
                                            if ($DiscountAccount == false) {
                                                $this->trans_rollback('preference', 'Purchase Account -> Payment Discount', $Currency_Code);
                                            }
                                        } else {
                                            if ($DiscountAccount == false) {
                                                $this->trans_rollback('journal', 'Discount Pembelian atau Retur Pembelian Purchase', $Currency_Code);
                                            }
                                        }
                                    } else {
                                        if ($ipay_item_type_disc == 1) {
                                            $DiscountAccount = $this->m_account_journal->get_sys_service_account('PaymentDiscount', $Currency_Code); // Potongan Pembelian
                                            if ($Currency_Code == 'IDR') {
                                                if ($DiscountAccount == false) {
                                                    $this->trans_rollback('preference', 'Expense Account -> Purchase Payment Discount', $Currency_Code);
                                                }
                                            } else {
                                                if ($DiscountAccount == false) {
                                                    $this->trans_rollback('journal', 'Discount Pembelian atau Retur Pembelian', $Currency_Code);
                                                }
                                            }
                                        } else {
                                            $DiscountAccount = $this->m_account_journal->get_sys_advance_account('PaymentDiscount', $Currency_Code); // Uang Muka Pembelian Expense
                                            if ($Currency_Code == 'IDR') {
                                                if ($DiscountAccount == false) {
                                                    $this->trans_rollback('preference', 'Adv Payment Account -> Payment Discount', $Currency_Code);
                                                }
                                            } else {
                                                if ($DiscountAccount == false) {
                                                    $this->trans_rollback('journal', 'Discount Pembelian atau Retur Pembelian Purchase', $Currency_Code);
                                                }
                                            }
                                        }
                                    }

                                    $amount_discount = $payment_disc * ($ipay_category_ratio_disc / 100);
                                    if ($Currency_Code == 'IDR') {
                                        $discount_amount = $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount;
                                        $discount_currency = $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount / $Bank_Curr_Rate;
                                    } else {
                                        $discount_amount = $Bank_Curr_Code == 'IDR' ? $amount_discount * $Bank_Curr_Rate : $amount_discount * $Bank_Curr_Rate;
                                        $discount_currency = $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount;
                                    }

                                    $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment($DiscountAccount->AccountNumber, $PPayNumber, $ipay_InvoiceNumber);
                                    if (empty($get_journal_purchase_payment->PPayAccountNumber)) {
                                        $journal_discount = array(
                                            'PPayDate' => $PPayDate,
                                            'PPayNumber' => $PPayNumber,
                                            'PPayDesc' => $PPayDesc,
                                            'PPayAccountNumber' => $DiscountAccount->AccountNumber,
                                            'PPaySaldoDebet' => 0,
                                            'PPaySaldoCredit' => $discount_amount,
                                            'AmountCurrency' => $discount_currency,
                                            'PPaySignStatus' => 0,
                                            'PInvNumber' => $invoice_number,
                                            'ItemCategoryID' => $item_category_id,
                                            'BranchTransCode' => $Branch_PaidFor,
                                            'LastUser' => $this->session->userdata("username")
                                        );

                                        if ($amount_discount > 0) {
                                            $this->m_purchase_payment->insert_journal($journal_discount);
                                        }
                                    } else {
                                        $discount_amount = $discount_amount + $get_journal_purchase_payment->PPaySaldoCredit;
                                        $discount_currency = $discount_currency + $get_journal_purchase_payment->AmountCurrency;

                                        $journal_discount = array(
                                            'PPaySaldoDebet' => 0,
                                            'PPaySaldoCredit' => $discount_amount,
                                            'AmountCurrency' => $discount_currency
                                        );
                                        if ($amount_discount > 0) {
                                            $this->m_purchase_payment->update_journal_invoice($PPayNumber, $journal_discount, $get_journal_purchase_payment->PPayAccountNumber, $ipay_InvoiceNumber);
                                        }
                                    }

                                    $total_discount = $discount_amount;
                                }
                            }
                            /* =====================End=================================================================== */

                            /*
                              Beban Pembulatan
                             */
                            if ($Load_Rounding > 0) {
                                $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccount == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                                if ($Currency_Code == 'IDR') {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                } else {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                }

                                $beban_pembulatan = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => abs($beban_amount),
                                    'AmountCurrency' => abs($beban_currency),
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan);
                            } else if ($Load_Rounding < 0) {
                                $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccount == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                                if ($Currency_Code == 'IDR') {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                } else {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                }

                                $beban_pembulatan = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                    'PPaySaldoDebet' => abs($beban_amount),
                                    'PPaySaldoCredit' => 0,
                                    'AmountCurrency' => abs($beban_currency),
                                    'PPaySignStatus' => 0,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan);
                            }
                            /* ========================End========================== */

                            /*
                              Beban Pembulatan Auto
                             */
                            if ($invoice_owing == 0) {
                                $total_hutang_real = $total_hutang;
                            } else {
                                $total_hutang_real = $payment_dp + $payment_disc + $Load_Rounding + $payment_amount;
                            }

                            $total_relize = ($Relized_all_trans * $Bank_Curr_Rate) - ($Relized_all_trans * $invoice_rate);

                            $realizegl_value_beban = $total_relize / $Bank_Curr_Rate;
                            $realized_amount_beban = $Currency_Code == 'IDR' ? abs($realizegl_value_beban) : abs($realizegl_value_beban) * $Bank_Curr_Rate;

                            if ($total_relize > 0) {
                                $total_relize_all_kredit = abs($realized_amount_beban);
                                $total_relize_all_debet = 0;
                            } else {
                                $total_relize_all_kredit = 0;
                                $total_relize_all_debet = abs($realized_amount_beban);
                            }

                            $Bank = empty($bank_amount) ? 0 : $bank_amount;
                            $Disc = empty($total_discount) ? 0 : $total_discount;
                            $Round = empty($Load_Rounding) ? 0 : $Load_Rounding;
                            $Relize_Debet = empty($total_relize_all_debet) ? 0 : $total_relize_all_debet;
                            $Relize_Kredit = empty($total_relize_all_kredit) ? 0 : $total_relize_all_kredit;
                            $TotalDP_No_Curren = empty($total_dp_no_currency) ? 0 : $total_dp_no_currency;
                            $TotalDP = empty($total_dp) ? 0 : $total_dp;
                            $Beban = empty($total_hutang_real) ? 0 : $total_hutang_real;
                            $selisih_kurs_dp = doubleval($TotalDP) - doubleval($TotalDP_No_Curren * $invoice_rate);

                            if ($selisih_kurs_dp > 0) {
                                $RelizeDP_Debet = 0;
                                $RelizeDP_Kredit = abs($selisih_kurs_dp);
                            } else {
                                $RelizeDP_Debet = abs($selisih_kurs_dp);
                                $RelizeDP_Kredit = 0;
                            }

                            $Total_Beban = ($Bank + $Disc + $Round + $Relize_Debet + ($RelizeDP_Debet + $TotalDP)) - (($Beban * $invoice_rate) + $RelizeDP_Kredit + $Relize_Kredit);

                            if ($Total_Beban > 0) {
                                $BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccountAuto == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                if ($Currency_Code == 'IDR') {
                                    $beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
                                } else {
                                    $beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
                                }

                                $beban_pembulatan_auto = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayNumber,
                                    'PPayAccountNumber' => $BebanAccountAuto->AccountNumber,
                                    'PPaySaldoDebet' => abs($beban_amount_auto),
                                    'PPaySaldoCredit' => 0,
                                    'AmountCurrency' => 0,
                                    'PPaySignStatus' => 0,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan_auto);
                            } else if ($Total_Beban < 0) {
                                $BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccountAuto == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                if ($Currency_Code == 'IDR') {
                                    $beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
                                } else {
                                    $beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
                                }

                                $beban_pembulatan_auto = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayNumber,
                                    'PPayAccountNumber' => $BebanAccountAuto->AccountNumber,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => abs($beban_amount_auto),
                                    'AmountCurrency' => 0,
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan_auto);
                            }
                            /* ==========================End====================== */

                            /*
                              Insert Journal Payment Realized Account
                             */
                            if ($total_relize > 0) {
                                $realizegl_value = $total_relize / $Bank_Curr_Rate;
                                $realized_amount = $Currency_Code == 'IDR' ? abs($realizegl_value) : abs($realizegl_value) * $Bank_Curr_Rate;
                                $realized_currency = $Bank_Curr_Code == 'IDR' ? 0 : 0;
                                //$realized_currency  = 0;    //abs($realizegl_value);

                                $journal_realized = array(
                                    'PPayDate' => $PPayDate,
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                    'PPaySaldoDebet' => $realized_amount,
                                    'PPaySaldoCredit' => 0,
                                    'AmountCurrency' => $realized_currency,
                                    'PPaySignStatus' => 0,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($journal_realized);
                            }
                            /* =======================End================================================================== */

                            /*
                              Insert Journal Payment Realized Account
                             */
                            if ($total_relize < 0) {
                                $realizegl_value = $total_relize / $Bank_Curr_Rate;
                                $realized_amount = $Currency_Code == 'IDR' ? $realizegl_value : $realizegl_value * $Bank_Curr_Rate;
                                $realized_currency = $Bank_Curr_Code == 'IDR' ? 0 : 0;
                                //$realized_currency  = 0;    //$realizegl_value;

                                $journal_realized = array(
                                    'PPayDate' => $PPayDate,
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => abs($realized_amount),
                                    'AmountCurrency' => abs($realized_currency),
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($journal_realized);
                            }
                            /* =======================End================================================================== */
                        } elseif (($row->Invoice_Type == 'PO')) {

                            $data_payment = $this->m_purchase_payment->get_payment($invoice_number, 1, 0);
                            $total_ppay_realizedgl = 0;
                            $ppay_realizedgl = 0;
                            $advance_value = 0;
                            $advance_currency = 0;
                            $total_amount_advance = 0;
                            /*
                              Get invoicepayment new table
                             */
                            foreach ($data_payment as $row_payment) {
                                $ipay_payment_id = $row_payment->InvoicePaymentID;
                                $ipay_category_id = $row_payment->ItemCategoryID;
                                $ipay_category_code = $row_payment->ItemCategoryCode;
                                $ipay_category_ratio = $row_payment->ItemCategoryRatio;
                                $ipay_InvoiceAmount = $row_payment->InvoiceAmount;
                                $ipay_category_amount = $row_payment->InvoiceOwing;
                                $ipay_item_type = $row_payment->ItemType;
                                $ipay_ItemCategoryRatio = $row_payment->ItemCategoryRatio;

                                $currency_payable = $payment_currency * ($ipay_category_ratio / 100);
                                $amount_invoice = $invoice_copy * ($ipay_category_ratio / 100);
                                $amount_advance = ($payment_amount) * ($ipay_category_ratio / 100);
                                $amount_advance_curr = ($payment_currency) * ($ipay_category_ratio / 100);

                                $amount_rounded = $Load_Rounding * ($ipay_category_ratio / 100);

                                $amount_advance_owing = ($payment_amount + $Load_Rounding) * ($ipay_category_ratio / 100);

                                $BankAccount = $BankPayment;

                                if ($Currency_Code == 'IDR') {
                                    $total_amount_advance = $amount_advance + $amount_rounded;
                                } else {
                                    if ($Bank_Curr_Code == 'IDR') {
                                        $total_amount_advance = ($amount_advance_curr / $Bank_Curr_Rate) + $amount_rounded;
                                    } else {
                                        $total_amount_advance = $amount_advance + $amount_rounded;
                                    }
                                }



                                if ($Currency_Code == 'IDR') {
                                    $inv_curr_amount = $amount_advance;
                                    $ppay_curr_amount = $amount_advance;
                                } else {
                                    $inv_curr_amount = $amount_advance * $invoice_rate;
                                    $ppay_curr_amount = $amount_advance * $Bank_Curr_Rate;
                                }

                                $ppay_realizedgl = $ppay_curr_amount - $inv_curr_amount;
                                $inv_owing = $amount_invoice - ($amount_advance_owing);

                                /* ==========Insert PPayDetail================================================================= */
                                $this->insert_detail($PPayDate, NULL, $ipay_ItemCategoryRatio, $Select_DP, $ipay_payment_id, $PPayNumber, $invoice_number, $invoice_date, $ipay_InvoiceAmount, $inv_owing, $invoice_rate, $fiscal_rate, $Bank_Curr_Rate, NULL, '0', '0', $amount_advance, $amount_advance, $currency_payable, $inv_curr_amount, $ppay_realizedgl, $amount_rounded, '1', $ipay_category_id, $ipay_category_code, $amount_invoice, $ipay_item_type, 0
                                );
                                /* ======================End==================================================================== */

                                if ($ipay_item_type == 0) {
                                    $AdvanceAccount = $this->m_account_journal->get_cat_purchase_account('AdvancePurchase', $ipay_category_id, $Currency_Code); // Uang Muka Category -> 1-4-03-001-00                            
                                    if ($Currency_Code == 'IDR') {
                                        if ($AdvanceAccount == false) {
                                            $this->trans_rollback('preference', 'Purchase Account -> Advance Purchase,', $Currency_Code);
                                        }
                                    } else {
                                        if ($AdvanceAccount == false) {
                                            $this->trans_rollback('journal', 'Uang Muka Pembelian,', $Currency_Code);
                                        }
                                    }
                                } else {
                                    if ($ipay_item_type == 1) {
                                        $AdvanceAccount = $this->m_account_journal->get_sys_service_account('Advance', $Currency_Code); // Uang Muka Pembelian Expense
                                        if ($Currency_Code == 'IDR') {
                                            if ($AdvanceAccount == false) {
                                                $this->trans_rollback('preference', 'Expense Account -> Purchase Advance', $Currency_Code);
                                            }
                                        } else {
                                            if ($AdvanceAccount == false) {
                                                $this->trans_rollback('journal', 'Uang Muka Pembelian,', $Currency_Code);
                                            }
                                        }
                                    } else {
                                        $AdvanceAccount = $this->m_account_journal->get_sys_advance_account('DownPayment', $Currency_Code); // Uang Muka Pembelian Expense
                                        if ($Currency_Code == 'IDR') {
                                            if ($AdvanceAccount == false) {
                                                $this->trans_rollback('preference', 'Adv Payment Account ->Purchase Advance', $Currency_Code);
                                            }
                                        } else {
                                            if ($AdvanceAccount == false) {
                                                $this->trans_rollback('journal', 'Uang Muka Pembelian,', $Currency_Code);
                                            }
                                        }
                                    }
                                }

                                if ($Currency_Code == 'IDR') {
                                    $advance_value = $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance;
                                    $advance_currency = $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance / $Bank_Curr_Rate;
                                } else {
                                    $advance_value = $Bank_Curr_Code == 'IDR' ? $total_amount_advance * $Bank_Curr_Rate : $total_amount_advance * $Bank_Curr_Rate;
                                    $advance_currency = $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance;
                                }

                                /*
                                  Insert Journal DP Account Purchase
                                 */
                                $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment($AdvanceAccount->AccountNumber, $PPayNumber, $invoice_number);
                                if (empty($get_journal_purchase_payment->PPayAccountNumber)) {
                                    $journal_dp = array(
                                        'PPayDate' => $PPayDate,
                                        'PPayNumber' => $PPayNumber,
                                        'PPayDesc' => $PPayDesc,
                                        'PPayAccountNumber' => $AdvanceAccount->AccountNumber,
                                        'PPaySaldoDebet' => $advance_value,
                                        'PPaySaldoCredit' => 0,
                                        'AmountCurrency' => $advance_currency,
                                        'PPaySignStatus' => 0,
                                        'ItemCategoryID' => $item_category_id,
                                        'BranchTransCode' => $Branch_PaidFor,
                                        'PInvNumber' => $invoice_number,
                                        'LastUser' => $this->session->userdata("username")
                                    );

                                    if ($advance_value > 0) {
                                        $this->m_purchase_payment->insert_journal($journal_dp);
                                    }
                                } else {
                                    $advance_value = $advance_value + $get_journal_purchase_payment->PPaySaldoDebet;
                                    $advance_currency = $advance_currency + $get_journal_purchase_payment->AmountCurrency;

                                    $journal_dp = array(
                                        'PPaySaldoDebet' => $advance_value,
                                        'PPaySaldoCredit' => 0,
                                        'AmountCurrency' => $advance_currency
                                    );

                                    if ($advance_value > 0) {
                                        $this->m_purchase_payment->update_journal_invoice($PPayNumber, $journal_dp, $get_journal_purchase_payment->PPayAccountNumber, $invoice_number);
                                    }
                                }

                                $total_ppay_realizedgl = $total_ppay_realizedgl + $ppay_realizedgl;
                                /* =======================End=============================================================== */
                            }
                            /* ===========================End================================================================ */


                            /*
                              Insert Journal Bank Acccount
                             */
                            $payment_val = doubleval($payment_amount);
                            $bank_amount = 0;
                            $bank_currency = 0;

                            if ($Currency_Code == 'IDR') {
                                $bank_amount = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;
                                $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val / $Bank_Curr_Rate;
                            } else {
                                $bank_amount = $Bank_Curr_Code == 'IDR' ? ($payment_currency / $Bank_Curr_Rate) * $Bank_Curr_Rate : $payment_val * $Bank_Curr_Rate;
                                $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;
                            }

                            $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment($BankPayment, $PPayNumber, $invoice_number);
                            if (empty($get_journal_purchase_payment->PPayAccountNumber)) {
                                $journal_bank = array(
                                    'PPayDate' => $PPayDate,
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BankPayment,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => $bank_amount,
                                    'AmountCurrency' => $bank_currency,
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PinvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($journal_bank);
                            } else {
                                $bank_amount = $bank_amount + $get_journal_purchase_payment->PPaySaldoCredit;
                                $bank_currency = $bank_currency + $get_journal_purchase_payment->AmountCurrency;

                                $journal_bank = array(
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => $bank_amount,
                                    'AmountCurrency' => $bank_currency
                                );
                                $this->m_purchase_payment->update_journal_invoice($PPayNumber, $journal_bank, $get_journal_purchase_payment->PPayAccountNumber, $invoice_number);
                            }
                            /* ===================End======================================================================== */

                            /*
                              RoundingLoad greater than 0 (Beban Pembulatan)
                             */
                            if ($Load_Rounding > 0) {
                                $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccount == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                                if ($Currency_Code == 'IDR') {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                } else {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                }

                                $beban_pembulatan = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => abs($beban_amount),
                                    'AmountCurrency' => abs($beban_currency),
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan);
                            } else if ($Load_Rounding < 0) {
                                $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccount == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                                if ($Currency_Code == 'IDR') {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                } else {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                }

                                $beban_pembulatan = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                    'PPaySaldoDebet' => abs($beban_amount),
                                    'PPaySaldoCredit' => 0,
                                    'AmountCurrency' => abs($beban_currency),
                                    'PPaySignStatus' => 0,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan);
                            }
                            /* ====================================================================================== */

                            $total_amount_paid += $payment_amount;
                            $total_currency_paid += $payment_currency;
                        }
                    }
                    /* =====================End============================================= */
                }//Akhir Paid = Yes
            }//Akhir foreach



            /*
              Update Purchase Payment data.
             */
            /* $data_pp_edit   = array (
              'PPayDesc'              => $PPayDesc,
              'ChequeNumber'          => $ChequeNumber,
              'PInvTotalAmount'       => $hdn_PInvTotalAmount,
              'PPayTotalDiscount'     => $hdn_PPayTotalDiscount,
              'PPayTotalDPUsed'       => $hdn_PPayTotalDPUsed,
              'PPayTotalAmount'       => $total_amount_paid,
              'PPayTotalCurrency'     => $total_currency_paid,
              'PPayTotalOwing'        => $hdn_PPayTotalOwing,
              'LastUser'              => $this->session->userdata("username")
              );

              $this->m_purchase_payment->update($data_pp_edit, $PPayNumber); */
            /* ====================End======================================================== */

            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, "$PPayNumber");

                $result['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                $result['number'] = $PPayNumber;
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, "$PPayNumber");
            }
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'insert', 0, "$PPayNumber");
        }

        echo json_encode($result);
    }

    /* =======================Insert group ====================================== */

    function insert_group($PGirNumber, $hdn_PPayTotalDPUsed, $hdn_PPayTotalDiscount, $hdn_PPayTotalOwing, $hdn_PInvTotalAmount, $TotalAmount, $AmountVendorDP, $hdn_total_currency, $BranchCode, $Branch_PaidFor, $VendorCode, $PPayDate, $PPayDesc, $PPayNumber, $PPayNumber, $BankPayment, $Currency_Code, $Bank_Curr_Code, $Bank_Curr_Rate, $ChequeNumber, $ChequeAmount, $ppnfiscal_status) {
        $data_group = array(
            'BranchCode' => $BranchCode,
            'BranchPaidFor' => $Branch_PaidFor,
            'VendorCode' => $VendorCode,
            'PPayDate' => $PPayDate,
            'PPayDesc' => $PPayDesc,
            'PPayNumber' => $PPayNumber,
            'BankPayment' => $BankPayment,
            'CurrencyCode' => $Currency_Code,
            'BankCurrCode' => $Bank_Curr_Code,
            'BankCurrRate' => $Bank_Curr_Rate,
            'ChequeNumber' => $ChequeNumber,
            'ChequeAmount' => $ChequeAmount,
            'PInvTotalAmount' => $hdn_PInvTotalAmount,
            'PPayTotalDiscount' => $hdn_PPayTotalDiscount,
            'PPayTotalDPUsed' => $hdn_PPayTotalDPUsed,
            'PPayTotalAmount' => $TotalAmount,
            'PPayTotalCurrency' => $hdn_total_currency,
            'PPayTotalOwing' => $hdn_PPayTotalOwing,
            'TransStatus' => 5,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d'),
            'PPnFiscalStatus' => $ppnfiscal_status,
			'PGirNumber' => $PGirNumber,
            '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, $BranchCode);
        /* ===========================end================================================= */
    }

    /* ===================End==================================================== */

    /* ===================Insert PPN Fiscal====================================== */

    function insert_ppn_fiscal($total_hutang, $invoice_owing_temp, $payment_currency, $Bank_Curr_Code, $payment_amount, $Load_Rounding, $total_currency_paid, $total_amount_paid, $item_category_id, $BankPayment, $Currency_Code, $invoice_number, $invoice_date, $Bank_Curr_Rate, $PPayNumber, $PPayDate, $PPayDesc, $inv_amount, $invoice_owing, $invoice_rate, $fiscal_rate, $payment_currency, $invoice_currency, $Branch_PaidFor) {
        /* ====================Fiscal Rate============================================================ */
        $data_payment = $this->m_purchase_payment->get_payment($invoice_number, 0, 1);
        foreach ($data_payment as $row_payment) {
            $ipay_payment_id = $row_payment->InvoicePaymentID;
            $ipay_category_code = $row_payment->ItemCategoryCode;
            $ipay_category_id = $row_payment->ItemCategoryID;
            $ipay_item_type = $row_payment->ItemType;
            $ipay_ItemCategoryRatio = $row_payment->ItemCategoryRatio;

            $inv_amount = $row_payment->InvoiceAmount;

            $payment_total = $payment_amount + $Load_Rounding;
            //$payment_rounded        = ($payment_currency / $Bank_Curr_Rate) - $payment_amount;
        }
        //----------------------------------------------------------------------------------------------//

        /* =======================Insert PPay Detail=================================================================== */
        $this->insert_detail(
               $PPayDate, NULL, $ipay_ItemCategoryRatio, NULL, $ipay_payment_id, $PPayNumber, $invoice_number, $invoice_date, $inv_amount, $invoice_owing_temp, $invoice_rate, $fiscal_rate, $Bank_Curr_Rate, NULL, '0', '0', $payment_amount, $payment_total, $payment_currency, $invoice_currency, 0, $Load_Rounding, '1', $ipay_category_id, $ipay_category_code, $inv_amount, $ipay_item_type, 1
        );
        /* ===========================End============================================================================= */

        $BankAccount = $BankPayment;

        /*
          Insert Journal Hutang PPn Fiscal
         */
        $PPnFiscalAccount = $this->m_account_journal->get_account_name('Hutang PPn Fiscal');
        if ($PPnFiscalAccount == false) {
            $this->trans_rollback('journal', 'Purchase PPn Fiscal, Taxable', '');
        }

        $fiscal_value = $Bank_Curr_Code == 'IDR' ? $total_hutang : $total_hutang;
        $fiscal_currency = $Bank_Curr_Code == 'IDR' ? $total_hutang : $total_hutang / $Bank_Curr_Rate;
        $fiscal_realize = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;

        $journal_fiscal = array(
            'PPayDate' => $PPayDate,
            'PPayNumber' => $PPayNumber,
            'PPayDesc' => $PPayDesc,
            'PPayAccountNumber' => $PPnFiscalAccount->AccountNumber,
            'PPaySaldoDebet' => $fiscal_value,
            'PPaySaldoCredit' => 0,
            'AmountCurrency' => $fiscal_currency,
            'PPaySignStatus' => 1,
            'ItemCategoryID' => $item_category_id,
            'BranchTransCode' => $Branch_PaidFor,
            'PInvNumber' => $invoice_number,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_payment->insert_journal($journal_fiscal);

        //$total_ppay_realizedgl = $total_ppay_realizedgl + $ppay_realizedgl;
        /* =====================End================================================================= */

        /*
          Insert Journal Bank Acccount
         */
        //$BankValue	= $CurrencyCode == 'IDR' ? $receipt_amount : $receipt_currency * $CurrencyRate;		
        $bank_amount = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;
        $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_currency;

        $journal_bank = array(
            'PPayDate' => $PPayDate,
            'PPayNumber' => $PPayNumber,
            'PPayDesc' => $PPayDesc,
            'PPayAccountNumber' => $BankAccount,
            'PPaySaldoDebet' => 0,
            'PPaySaldoCredit' => $bank_amount,
            'AmountCurrency' => $bank_currency,
            'PPaySignStatus' => 1,
            'ItemCategoryID' => $item_category_id,
            'BranchTransCode' => $Branch_PaidFor,
            'PInvNumber' => $invoice_number,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_payment->insert_journal($journal_bank);
        /* =====================End============================================================================= */
		
		/*
		  Beban Pembulatan Auto
		*/
		
		$Total_Beban = ($payment_amount + $Load_Rounding) - ($total_hutang);

		if ($Total_Beban > 0) {
			$BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
			if ($BebanAccountAuto == false) {
				$this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
			}

			if ($Currency_Code == 'IDR') {
				$beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
			} else {
				$beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
			}

			$beban_pembulatan_auto = array(
				'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
				'PPayNumber' => $PPayNumber,
				'PPayDesc' => $PPayNumber,
				'PPayAccountNumber' => $BebanAccountAuto->AccountNumber,
				'PPaySaldoDebet' => abs($beban_amount_auto),
				'PPaySaldoCredit' => 0,
				'AmountCurrency' => 0,
				'PPaySignStatus' => 0,
				'ItemCategoryID' => $item_category_id,
				'BranchTransCode' => $Branch_PaidFor,
				'PInvNumber' => $invoice_number,
				'LastUser' => $this->session->userdata("username")
			);

			$this->m_purchase_payment->insert_journal($beban_pembulatan_auto);
		} else if ($Total_Beban < 0) {
			$BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
			if ($BebanAccountAuto == false) {
				$this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
			}

			if ($Currency_Code == 'IDR') {
				$beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
			} else {
				$beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
			}

			$beban_pembulatan_auto = array(
				'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
				'PPayNumber' => $PPayNumber,
				'PPayDesc' => $PPayNumber,
				'PPayAccountNumber' => $BebanAccountAuto->AccountNumber,
				'PPaySaldoDebet' => 0,
				'PPaySaldoCredit' => abs($beban_amount_auto),
				'AmountCurrency' => 0,
				'PPaySignStatus' => 1,
				'ItemCategoryID' => $item_category_id,
				'BranchTransCode' => $Branch_PaidFor,
				'PInvNumber' => $invoice_number,
				'LastUser' => $this->session->userdata("username")
			);

			$this->m_purchase_payment->insert_journal($beban_pembulatan_auto);
		}
		/* ==========================End====================== */
							
        /*
          Beban Pembulatan
         */
        if ($Load_Rounding > 0) {
            $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
            if ($BebanAccount == false) {
                $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
            }

            $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
            if ($Currency_Code == 'IDR') {
                $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
            } else {
                $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
            }

            $beban_pembulatan = array(
                'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                'PPayNumber' => $PPayNumber,
                'PPayDesc' => $PPayDesc,
                'PPayAccountNumber' => $BebanAccount->AccountNumber,
                'PPaySaldoDebet' => 0,
                'PPaySaldoCredit' => abs($beban_amount),
                'AmountCurrency' => 0,
                'PPaySignStatus' => 1,
                'ItemCategoryID' => $item_category_id,
                'BranchTransCode' => $Branch_PaidFor,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_payment->insert_journal($beban_pembulatan);
        } else if ($Load_Rounding < 0) {
            $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
            if ($BebanAccount == false) {
                $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
            }

            $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
            if ($Currency_Code == 'IDR') {
                $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
            } else {
                $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
            }

            $beban_pembulatan = array(
                'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                'PPayNumber' => $PPayNumber,
                'PPayDesc' => $PPayDesc,
                'PPayAccountNumber' => $BebanAccount->AccountNumber,
                'PPaySaldoDebet' => abs($beban_amount),
                'PPaySaldoCredit' => 0,
                'AmountCurrency' => 0,
                'PPaySignStatus' => 0,
                'ItemCategoryID' => $item_category_id,
                'BranchTransCode' => $Branch_PaidFor,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_payment->insert_journal($beban_pembulatan);
        }
        /* ========================End========================== */



        $total_amount_paid += $payment_amount;
        $total_currency_paid += $payment_currency;
    }

    /* ====================End================================================== */

    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());
                    $data['detail'] = $this->m_purchase_payment->get_detail($id);

                    $data['vendor'] = $this->m_vendors->get_saldo_by_id($data['detail']->VendorCode);
                    $data['vendor'] = $data['vendor'][0];
                    $result = $this->m_purchase_payment->get_saldo_detail_dp_update($data['detail']->VendorCode);

                    $TotalSuming = 0;
                    foreach ($result as $row_detail_dp) {
                        $get_detail = $this->m_purchase_payment->get_saldo_detail($row_detail_dp->POrdDetailDPID, $data['detail']->VendorCode, $id);
						
						if($data['detail']->CurrencyCode == 'IDR'){
							if(empty($get_detail->AmountCurrency)){
								$DPUsed = 0;
							}
							else{
								$DPUsed    = $data['detail']->BankCurrCode == 'IDR' ? $get_detail->AmountCurrency : $get_detail->SRecSaldoDebet;
							}
						}
						else{
							if(empty($get_detail->AmountCurrency)){
								$DPUsed = 0;
							}
							else{
								$DPUsed    = $data['detail']->BankCurrCode == 'IDR' ? $get_detail->AmountCurrency : $get_detail->AmountCurrency;
							}
						}
						

                        $Total_Balance = $row_detail_dp->PaymentAmount_SUM + $DPUsed;
                        $TotalSuming += $Total_Balance;
                    }

                    $data['po_detail_dp'] = $TotalSuming;
                    $result_dp_invoice = $this->m_purchase_payment->get_pordetail_dp_balance_invoice($data['detail']->VendorCode);
                    if (empty($result_dp_invoice->DownPayment)) {
                        $data['po_detail_dp_invoice'] = 0;
                    } else {
                        $data['po_detail_dp_invoice'] = $result_dp_invoice->DownPayment;
                    }

                    if ($data['detail'] != false) {
                        $this->load->view('v_header');
                        $this->load->view('purchase/purchase_payment/v_edit_purchase_payment', $data);
                        $this->load->view('v_footer');
                    }
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function update() {
        /* ================Deklar variabel============================================================ */
        $Vendor_Code = $this->input->post('cbg_vendor');
        $Branch_PaidFor = $this->input->post('cbg_branch');

        $PPayNumber = $this->input->post('txt_ppay_no');
        $PPayDate = date("Y-m-d", strtotime($this->input->post('txt_ppay_date')));
        $PPayDesc = $this->input->post('txa_description');
        $BankPayment = $this->input->post('cbg_bank');

        $Currency_Code = $this->input->post('hdn_vend_curr_code');
        $Bank_Curr_Code = $this->input->post('hdn_bank_curr_code');
        $Bank_Curr_Rate = $this->input->post('txt_bank_curr_rate');
        $ChequeNumber = $this->input->post('txt_cheque_no');
        $ChequeAmount = $this->input->post('txt_cheque_amount');

        $ppnfiscal_status = $this->input->post('chk_fiscal_payment');
        $DPTotal = $this->input->post('txt_vendor_dp_return');

        $hdn_total_currency = $this->input->post('hdn_total_currency');
        $hdn_PInvTotalAmount = $this->input->post('hdn_PInvTotalAmount');
        $hdn_PPayTotalOwing = $this->input->post('hdn_PPayTotalOwing');
        $hdn_PPayTotalDPUsed = $this->input->post('hdn_PPayTotalDPUsed');
        $hdn_PPayTotalDiscount = $this->input->post('hdn_PPayTotalDiscount');

        $total_dp_used = 0;
        $total_disc_used = 0;
        $total_amount_paid = 0;
        $total_currency_paid = 0;
        $total_ppay_realizedgl = 0;
        $total_ppay_realizedgl_new = 0;
        $total_hutang_beban = 0;
        $total_hutang_beban_new = 0;

        $total_invoice = 0;
        $total_owing = 0;
        $invoice_loop = 0;

        $detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);
        /* =====================End========================================================================= */

        if (count($detail) > 0) {
            $this->db->trans_begin();

            /*
              Jika Select dp dirubah
             */
            if ($hdn_PPayTotalDPUsed > 0) {
                $DPAccount = $this->m_account_journal->get_sys_purchase_account('AdvancePurchase', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
                $sordetail_dp_new = $this->m_purchase_payment->get_payment_detail_dp_update($Vendor_Code, $DPAccount->AccountNumber);
                foreach ($sordetail_dp_new as $row_dp_suspend) {
                    $DPUsed = $row_dp_suspend->DPUsed;
                    $POrdDetailDPID = $row_dp_suspend->POrdDetailDPID;
                    $POrdNumber_DP = $row_dp_suspend->POrdNumber;
                    $total_pordetail = $row_dp_suspend->AmountCurrency - $DPUsed;
                    $total_pordetail_new = $row_dp_suspend->PPaySaldoCredit - $DPUsed;

                    if ($Currency_Code == 'IDR') {
                        $dp_total_amount = $Bank_Curr_Code == 'IDR' ? $total_pordetail : $total_pordetail_new;
                    } else {
                        $dp_total_amount = $Bank_Curr_Code == 'IDR' ? $total_pordetail : $total_pordetail;
                    }

                    $update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => abs($total_pordetail));
                    $this->m_purchase_payment->update_po_detail_dp_for_pp($update_sordstatus, $Vendor_Code, $POrdDetailDPID);
                }
            }


            /* ====================End===================================================================== */

            /*
              Delete Journal Transaction.
             */
            $this->m_purchase_payment->delete_journal($PPayNumber);
            /* ===============End======================================= */

            foreach ($detail as $row) {
                $invoice_number = $row->Invoice_Number;

                if ($row->Paid == 'Yes') {
                    $ppay_detail_id = $row->PPayDetailID;
                    $item_category_id = $row->ItemCategoryID;
                    $invoice_rate = $row->InvoiceCurrRate;
                    $invoice_amount = $row->Invoice_Amount;
                    $invoice_owing = $row->Invoice_Owing;
                    $invoice_amount_copy = $row->InvoiceAmountCopy;
                    $invoice_temp_owing = $row->InvoiceOwingHiddenNew;
                    $InvoiceOwingHidden = $row->InvoiceOwingHidden;
                    $total_hutang = $InvoiceOwingHidden - $invoice_temp_owing;

                    $payment_dp = $row->Payment_DP;
                    $payment_disc = $row->Payment_Discount;
                    $payment_amount = $row->Payment_Amount;
                    $payment_currency = $row->Payment_Currency;
                    $Load_Rounding = $row->Load_Rounding;
                    $fiscal_rate = $row->InvoiceFiscalRate;
                    $Select_DP = $row->Select_DP;
                    $Relized_all_trans = $payment_disc + $payment_amount;

                    $invoice_currency = $Currency_Code == 'IDR' ? $payment_amount : $payment_amount * $invoice_rate;
                    $payment_realizedgl = ($Bank_Curr_Rate == 'IDR' ? $payment_currency : $payment_currency * $Bank_Curr_Rate) - $invoice_currency;

                    $ppay_disc_date = empty($row->Payment_DiscDate) ? null : date("Y-m-d", strtotime($row->Payment_DiscDate));
                    $Advanced = '';
                    $total_dp = 0;
                    $relize_dp = 0;
                    $total_relize = 0;

                    $invoice_loop++;

                    $total_invoice += $invoice_amount;
                    $total_owing += $invoice_owing;
                    //-----------------------------------------------------------------------------------------------------------//
                    //Insert Journal Transaction

                    if ($item_category_id == -3) {
                        $payment_total = $payment_amount + $Load_Rounding;
                        //$payment_rounded        = ($payment_currency / $Bank_Curr_Rate) - $payment_amount;

                        /*
                          Update ppaydetail
                         */
                        $this->update_detail(
                                $Select_DP, $ppay_detail_id, $invoice_temp_owing, $Bank_Curr_Rate, NULL, 0, 0, $payment_amount, $payment_total, $payment_currency, $invoice_currency, $payment_realizedgl, $Load_Rounding
                        );	
                        /* ===============End=================================================================================== */

                        $BankAccount = $BankPayment;

                        /*
                          Insert Journal Hutang PPn Fiscal
                         */
                        $PPnFiscalAccount = $this->m_account_journal->get_account_name('Hutang PPn Fiscal');
                        if ($PPnFiscalAccount == false) {
                            $this->trans_rollback('journal', 'Purchase PPn Fiscal, Taxable', '');
                        }

                        $fiscal_value = $Bank_Curr_Code == 'IDR' ? $total_hutang : $total_hutang;
                        $fiscal_currency = $Bank_Curr_Code == 'IDR' ? $total_hutang : $total_hutang / $Bank_Curr_Rate;
                        $fiscal_realize = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;

                        $journal_fiscal = array(
                            'PPayDate' => $PPayDate,
                            'PPayNumber' => $PPayNumber,
                            'PPayDesc' => $PPayDesc,
                            'PPayAccountNumber' => $PPnFiscalAccount->AccountNumber,
                            'PPaySaldoDebet' => $fiscal_value,
                            'PPaySaldoCredit' => 0,
                            'AmountCurrency' => $fiscal_currency,
                            'PPaySignStatus' => 1,
                            'ItemCategoryID' => $item_category_id,
                            'BranchTransCode' => $Branch_PaidFor,
                            'PinvNumber' => $invoice_number,
                            'LastUser' => $this->session->userdata("username")
                        );

                        $this->m_purchase_payment->insert_journal($journal_fiscal);

                        //$total_ppay_realizedgl = $total_ppay_realizedgl + $ppay_realizedgl;
                        /* =====================End================================================================= */

                        /*
                          Insert Journal Bank Acccount
                         */
                        //$BankValue	= $CurrencyCode == 'IDR' ? $receipt_amount : $receipt_currency * $CurrencyRate;		
                        $bank_amount = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount;
                        $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_amount : $payment_amount / $Bank_Curr_Rate;

                        $journal_bank = array(
                            'PPayDate' => $PPayDate,
                            'PPayNumber' => $PPayNumber,
                            'PPayDesc' => $PPayDesc,
                            'PPayAccountNumber' => $BankAccount,
                            'PPaySaldoDebet' => 0,
                            'PPaySaldoCredit' => $bank_amount,
                            'AmountCurrency' => $bank_currency,
                            'PPaySignStatus' => 1,
                            'ItemCategoryID' => $item_category_id,
                            'BranchTransCode' => $Branch_PaidFor,
                            'PinvNumber' => $invoice_number,
                            'LastUser' => $this->session->userdata("username")
                        );

                        $this->m_purchase_payment->insert_journal($journal_bank);
                        /* =====================End============================================================================= */
						
						/*
						  Beban Pembulatan Auto
						*/
						
						$Total_Beban = ($payment_amount + $Load_Rounding) - ($total_hutang);
				
						if ($Total_Beban > 0) {
							$BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
							if ($BebanAccountAuto == false) {
								$this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
							}
				
							if ($Currency_Code == 'IDR') {
								$beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							} else {
								$beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
				
							$beban_pembulatan_auto = array(
								'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
								'PPayNumber' => $PPayNumber,
								'PPayDesc' => $PPayNumber,
								'PPayAccountNumber' => $BebanAccountAuto->AccountNumber,
								'PPaySaldoDebet' => abs($beban_amount_auto),
								'PPaySaldoCredit' => 0,
								'AmountCurrency' => 0,
								'PPaySignStatus' => 0,
								'ItemCategoryID' => $item_category_id,
								'BranchTransCode' => $Branch_PaidFor,
								'PInvNumber' => $invoice_number,
								'LastUser' => $this->session->userdata("username")
							);
				
							$this->m_purchase_payment->insert_journal($beban_pembulatan_auto);
						} else if ($Total_Beban < 0) {
							$BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
							if ($BebanAccountAuto == false) {
								$this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
							}
				
							if ($Currency_Code == 'IDR') {
								$beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							} else {
								$beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
							}
				
							$beban_pembulatan_auto = array(
								'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
								'PPayNumber' => $PPayNumber,
								'PPayDesc' => $PPayNumber,
								'PPayAccountNumber' => $BebanAccountAuto->AccountNumber,
								'PPaySaldoDebet' => 0,
								'PPaySaldoCredit' => abs($beban_amount_auto),
								'AmountCurrency' => 0,
								'PPaySignStatus' => 1,
								'ItemCategoryID' => $item_category_id,
								'BranchTransCode' => $Branch_PaidFor,
								'PInvNumber' => $invoice_number,
								'LastUser' => $this->session->userdata("username")
							);
				
							$this->m_purchase_payment->insert_journal($beban_pembulatan_auto);
						}
						/* ==========================End====================== */
						
                        /*
                          Beban Pembulatan
                         */
                        if ($Load_Rounding > 0) {
                            $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                            if ($BebanAccount == false) {
                                $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                            }

                            $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                            if ($Currency_Code == 'IDR') {
                                $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                            } else {
                                $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                            }

                            $beban_pembulatan = array(
                                'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                'PPayNumber' => $PPayNumber,
                                'PPayDesc' => $PPayDesc,
                                'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                'PPaySaldoDebet' => 0,
                                'PPaySaldoCredit' => abs($beban_amount),
                                'AmountCurrency' => 0,
                                'PPaySignStatus' => 1,
                                'ItemCategoryID' => $item_category_id,
                                'BranchTransCode' => $Branch_PaidFor,
                                'LastUser' => $this->session->userdata("username")
                            );

                            $this->m_purchase_payment->insert_journal($beban_pembulatan);
                        } else if ($Load_Rounding < 0) {
                            $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                            if ($BebanAccount == false) {
                                $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                            }

                            $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                            if ($Currency_Code == 'IDR') {
                                $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                            } else {
                                $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                            }

                            $beban_pembulatan = array(
                                'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                'PPayNumber' => $PPayNumber,
                                'PPayDesc' => $PPayDesc,
                                'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                'PPaySaldoDebet' => abs($beban_amount),
                                'PPaySaldoCredit' => 0,
                                'AmountCurrency' => 0,
                                'PPaySignStatus' => 0,
                                'ItemCategoryID' => $item_category_id,
                                'BranchTransCode' => $Branch_PaidFor,
                                'LastUser' => $this->session->userdata("username")
                            );

                            $this->m_purchase_payment->insert_journal($beban_pembulatan);
                        }
                        /* ========================End========================== */



                        $total_amount_paid += $payment_amount;
                        $total_currency_paid += $payment_currency;
                    } else {
                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                        if ($RealizedAccount == false) {
                            $this->trans_rollback('Realized G/L, Purchase');
                        }

                        if (($row->Invoice_Type == 'PI') && ($item_category_id != -3)) {
                            //PI and not PPn Fiscal
                            $curr_account_no = '';
                            $CategoryIDDisc = array();
                            $CategoryIDCode = array();
                            $CategoryType = array();

                            $payable_value = 0;
                            $total_loop = 0;
                            $invoice_number_loop = "";
                            $payable_amount = 0;
                            $payable_currency = 0;


                            /*
                              Get tabel invoice payment
                             */
                            $data_ppay_detail = $this->m_purchase_payment->get_ppay_detail($invoice_number, $PPayNumber);

                            foreach ($data_ppay_detail as $row_ppay) {
                                $total_loop++;
                                $payament_ratio = $this->m_purchase_payment->get_payment_by_id($row_ppay->InvoicePaymentID);
                                $ipay_category_ratio = $payament_ratio[0]->ItemCategoryRatio;
                                $ipay_ItemType = $payament_ratio[0]->ItemType;

                                $ppay_detail_id = $row_ppay->PPayDetailID;
                                $ppay_category_id = $row_ppay->ItemCategoryID;
                                $ppay_category_code = $row_ppay->ItemCategoryCode;
                                $ppay_ItemCategoryRatio = $row_ppay->ItemCategoryRatio;
                                $ppay_PInvCurrRate = $row_ppay->PInvCurrRate;


                                if ($ipay_ItemType == 0) {
                                    $PurchaseAccount = $this->m_account_journal->get_cat_purchase_account('Payable', $ppay_category_id, $Currency_Code);
                                    if ($Currency_Code == 'IDR') {
                                        if ($PurchaseAccount == false) {
                                            $this->trans_rollback('preference', 'Purchase Account -> Account Payable', $Currency_Code);
                                        }
                                    } else {
                                        if ($PurchaseAccount == false) {
                                            $this->trans_rollback('journal', 'Hutang Dagang', $Currency_Code);
                                        }
                                    }
                                    $Sign_Status_PurchaseAccount = 1;
                                } else {
                                    if ($ipay_ItemType == 1) {
                                        $PurchaseAccount = $this->m_account_journal->get_sys_service_account('Unbilled', $Currency_Code);
                                        if ($Currency_Code == 'IDR') {
                                            if ($PurchaseAccount == false) {
                                                $this->trans_rollback('preference', 'Expense Account -> Purchase Unbilled (Owing)', $Currency_Code);
                                            }
                                        } else {
                                            if ($PurchaseAccount == false) {
                                                $this->trans_rollback('journal', 'Hutang Expense', $Currency_Code);
                                            }
                                        }
                                        $Sign_Status_PurchaseAccount = 1;
                                    } else {
                                        $PurchaseAccount = $this->m_account_journal->get_sys_advance_account('Unbilled', $Currency_Code);
                                        if ($Currency_Code == 'IDR') {
                                            if ($PurchaseAccount == false) {
                                                $this->trans_rollback('preference', 'Adv Payment Account -> Unbilled (Owing)', $Currency_Code);
                                            }
                                        } else {
                                            if ($PurchaseAccount == false) {
                                                $this->trans_rollback('journal', 'Hutang Advanced Payment', $Currency_Code);
                                            }
                                        }
                                        $Sign_Status_PurchaseAccount = 1;
                                    }
                                }

                                $amount_invoice = $invoice_amount_copy * ($ipay_category_ratio / 100);
                                $amount_owing_real = $invoice_owing * ($ipay_category_ratio / 100);
                                $amount_owing_temp = $invoice_temp_owing * ($ipay_category_ratio / 100);

                                $amount_owing_copy = $total_hutang * ($ipay_category_ratio / 100);

                                $amount_dpused = $payment_dp * ($ipay_category_ratio / 100);
                                $amount_discount = $payment_disc * ($ipay_category_ratio / 100);
                                $amount_payable = $payment_amount * ($ipay_category_ratio / 100);
                                $currency_payable = $payment_currency * ($ipay_category_ratio / 100);

                                $amount_rounded = $Load_Rounding * ($ipay_category_ratio / 100);

                                if ($invoice_owing == 0) {
                                    $amount_total_journal = $amount_owing_copy;
                                } else {
                                    $amount_total_journal = $amount_dpused + $amount_discount + $amount_rounded + $amount_payable;
                                }

                                if ($Currency_Code == 'IDR') {
                                    $amount_total = $amount_dpused + $amount_discount + $amount_payable;
                                    $amount_total_selisih = $amount_discount + $amount_payable;
                                } else {
                                    if ($Bank_Curr_Code == 'IDR') {
                                        $amount_total = $amount_dpused + $amount_discount + ($currency_payable / $Bank_Curr_Rate);
                                        $amount_total_selisih = $amount_discount + ($currency_payable / $Bank_Curr_Rate);
                                    } else {
                                        $amount_total = $amount_dpused + $amount_discount + $amount_payable;
                                        $amount_total_selisih = $amount_discount + $amount_payable;
                                    }
                                }



                                if ($Currency_Code == 'IDR') {
                                    $inv_cat_curr_amount = $amount_total;
                                    $pay_cat_curr_amount = $amount_total;
                                } else {
                                    $inv_cat_curr_amount = $amount_total_selisih * $invoice_rate;
                                    $pay_cat_curr_amount = $amount_total_selisih * $Bank_Curr_Rate;
                                }

                                $ppay_cat_realizedgl = $pay_cat_curr_amount - $inv_cat_curr_amount;
                                //$new_invoice_owing      = $amount_invoice - ($amount_total + $amount_rounded);

                                if ($total_loop == 1) {
                                    $curr_account_no = $PurchaseAccount->AccountNumber;
                                }

                                if ($payment_disc > 0) {
                                    @$CategoryIDDisc[$ppay_category_id] = $amount_discount;
                                    @$CategoryIDCode[$ppay_category_id] = $ppay_category_code;
                                    @$CategoryType[$ppay_category_id] = $ipay_ItemType;
                                }

                                /*
                                  Update ppaydetail
                                 */
                                $this->update_detail(
                                        $Select_DP, $ppay_detail_id, $amount_owing_temp, $Bank_Curr_Rate, $ppay_disc_date, $amount_discount, $amount_dpused, $amount_payable, $amount_total, $currency_payable, $inv_cat_curr_amount, $ppay_cat_realizedgl, $amount_rounded
                                );
                                /* =====================End=================================================================== */

                                /*
                                  Journal Hutang dagang
                                 */
                                if ($Currency_Code == 'IDR') {
                                    $payable_amount = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal;
                                    $payable_currency = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal / $Bank_Curr_Rate;
                                } else {
                                    $payable_amount = $Bank_Curr_Code == 'IDR' ? $amount_total_journal * $ppay_PInvCurrRate : $amount_total_journal * $ppay_PInvCurrRate;
                                    $payable_currency = $Bank_Curr_Code == 'IDR' ? $amount_total_journal : $amount_total_journal;
                                }

                                $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment($PurchaseAccount->AccountNumber, $PPayNumber, $invoice_number);

                                /*
                                  Check Invoice sama atau tidak
                                 */
                                if (empty($get_journal_purchase_payment->PPayAccountNumber)) {
                                    $journal_purchase = array(
                                        'PPayDate' => $PPayDate,
                                        'PPayNumber' => $PPayNumber,
                                        'PPayDesc' => $PPayDesc,
                                        'PPayAccountNumber' => $PurchaseAccount->AccountNumber,
                                        'PPaySaldoDebet' => $payable_amount,
                                        'PPaySaldoCredit' => 0,
                                        'AmountCurrency' => $payable_currency,
                                        'PPaySignStatus' => $Sign_Status_PurchaseAccount,
                                        'ItemCategoryID' => $ppay_category_id,
                                        'BranchTransCode' => $Branch_PaidFor,
                                        'PInvNumber' => $invoice_number,
                                        'LastUser' => $this->session->userdata("username")
                                    );
                                    $this->m_purchase_payment->insert_journal($journal_purchase);
                                } else {
                                    $payable_amount = $payable_amount + $get_journal_purchase_payment->PPaySaldoDebet;
                                    $payable_currency = $payable_currency + $get_journal_purchase_payment->AmountCurrency;

                                    $journal_purchase = array(
                                        'PPaySaldoDebet' => $payable_amount,
                                        'PPaySaldoCredit' => 0,
                                        'AmountCurrency' => $payable_currency
                                    );
                                    $this->m_purchase_payment->update_journal_invoice($PPayNumber, $journal_purchase, $get_journal_purchase_payment->PPayAccountNumber, $invoice_number);
                                }
                            }

                            /* =====================End=================================================================== */


                            /*
                              Journal Bank Payment - Invoice Payment
                             */
                            $payment_val = doubleval($payment_amount);
                            $bank_amount = 0;
                            $bank_currency = 0;

                            if ($payment_val > 0) {
                                if ($Currency_Code == 'IDR') {
                                    $bank_amount = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;
                                    $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val / $Bank_Curr_Rate;
                                } else {
                                    $bank_amount = $Bank_Curr_Code == 'IDR' ? ($payment_currency / $Bank_Curr_Rate) * $Bank_Curr_Rate : $payment_val * $Bank_Curr_Rate;
                                    $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;
                                }

                                $journal_bank = array(
                                    'PPayDate' => $PPayDate,
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BankPayment,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => $bank_amount,
                                    'AmountCurrency' => $bank_currency,
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($journal_bank);

                                $total_amount_paid += $payment_amount;
                                $total_currency_paid += $payment_currency;
                            }
                            /* ====================================================================================== */

                            /*
                              Journal Advance Purchase - Uang Muka Pembelian
                             */
                            $total_dp = 0;
                            $total_dp_no_currency = 0;

                            if ($payment_dp > 0) {

                                /*
                                  rumus sordetail untuk save dan edit
                                 */
                                $sordetail_dp = $this->m_purchase_payment->get_saldo_detail_dp($Vendor_Code, $Select_DP, 1);
                                $saldo_dp = $payment_dp;
                                $saldo_dp_new = $payment_dp;

                                $jurnal_dp = 0;
                                $jurnal_dp_currency = 0;
                                $jurnal_dp_no_currency = 0;

                                $currency_rate_detail = 0;
                                $is_edit = "";
                                $PaymentBefore = 0;
                                $PaymentBefore_Sum = 0;
                                $PaymentPlus = 0;
                                $PaymentPlus_Sum = 0;

                                foreach ($sordetail_dp as $row_detail_dp) {
                                    $DPUsed = $row_detail_dp->DPUsed;
                                    $SaldoDPBalance = $row_detail_dp->SaldoDPBalance;
                                    $JVoucherBalance = $row_detail_dp->JVoucherBalance;
                                    $DPUsed = $DPUsed + $JVoucherBalance;
                                    $currency_rate_detail = $row_detail_dp->CurrencyRate;

                                    if ($DPUsed != $SaldoDPBalance) {
                                        $dp_used_book = 0;
                                        $saldo_balance_detail = $row_detail_dp->PaymentAmount;

                                        //$DPUsedBook 			=  $row_detail_dp->DPUsedBook;
                                        $SOrdDetailDPID = $row_detail_dp->POrdDetailDPID;
                                        $SaldoDPBalance = $row_detail_dp->SaldoDPBalance;

                                        if ($saldo_dp > 0) {
                                            $saldo_dp = doubleval($saldo_dp_new - ($PaymentPlus_Sum + $saldo_balance_detail));

                                            if ($saldo_dp < 0) {
                                                $dp_used_old = $DPUsed;
                                                $dp_used_book = doubleval($DPUsed + ($saldo_dp_new - $PaymentBefore_Sum));

                                                $jurnal_dp = (doubleval(($saldo_dp_new - $PaymentBefore_Sum) * $currency_rate_detail));
                                                $jurnal_dp_currency = (doubleval($saldo_dp_new - $PaymentBefore_Sum / $currency_rate_detail));
                                                $jurnal_dp_no_currency = doubleval($saldo_dp_new - $PaymentBefore_Sum);
                                                $total_dp += $jurnal_dp;
                                                $total_dp_no_currency += $jurnal_dp_no_currency;

                                                $update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => $dp_used_book);
                                                $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_sordstatus, $Vendor_Code, $SOrdDetailDPID, $Select_DP);

                                                $DPAccount = $this->m_account_journal->get_account_name('Uang Muka Pembelian', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
                                                if ($DPAccount == false) {
                                                    $this->trans_rollback('journal', 'Uang Muka Pembelian', $Currency_Code);
                                                }

                                                if ($Currency_Code == 'IDR') {
                                                    $dp_currency = $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_currency;
                                                } else {
                                                    $dp_currency = $Bank_Curr_Code == 'IDR' ? $jurnal_dp : $jurnal_dp_currency;
                                                }

                                                $journal_dp = array(
                                                    'PPayDate' => $PPayDate,
                                                    'PPayNumber' => $PPayNumber,
                                                    'PPayDesc' => $PPayDesc,
                                                    'PPayAccountNumber' => $DPAccount->AccountNumber,
                                                    'PPaySaldoDebet' => 0,
                                                    'PPaySaldoCredit' => $jurnal_dp,
                                                    'AmountCurrency' => $dp_currency,
                                                    'PPaySignStatus' => 1,
                                                    'ItemCategoryID' => $item_category_id,
                                                    'BranchTransCode' => $Branch_PaidFor,
                                                    'PinvNumber' => $invoice_number,
                                                    'POrdDetailDPID' => $row_detail_dp->POrdDetailDPID,
                                                    'LastUser' => $this->session->userdata("username")
                                                );

                                                if ($jurnal_dp > 0) {
                                                    $this->m_purchase_payment->insert_journal($journal_dp);
                                                }

                                                if ($Currency_Code != 'IDR') {
                                                    $inv_dp_selisih_kurs = doubleval($jurnal_dp) - doubleval($jurnal_dp_no_currency * $invoice_rate);
                                                    if ($inv_dp_selisih_kurs > 0) {
                                                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                                                        if ($RealizedAccount == false) {
                                                            $this->trans_rollback('journal', 'Realized, Purchase', $Currency_Code);
                                                        }

                                                        $realized_amount = abs($inv_dp_selisih_kurs);
                                                        $realized_currency = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;

                                                        $journal_RealizedAccount = array(
                                                            'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                                            'PPayNumber' => $PPayNumber,
                                                            'PPayDesc' => $PPayNumber,
                                                            'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                                            'PPaySaldoDebet' => $realized_amount,
                                                            'PPaySaldoCredit' => 0,
                                                            'AmountCurrency' => 0,
                                                            'PPaySignStatus' => 0,
                                                            'ItemCategoryID' => $item_category_id,
                                                            'BranchTransCode' => $Branch_PaidFor,
                                                            'PInvNumber' => $invoice_number,
                                                            'LastUser' => $this->session->userdata("username")
                                                        );

                                                        $this->m_purchase_payment->insert_journal($journal_RealizedAccount);
                                                    } else if ($inv_dp_selisih_kurs < 0) {
                                                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                                                        if ($RealizedAccount == false) {
                                                            $this->trans_rollback('journal', 'Realized, Purchase', $Currency_Code);
                                                        }

                                                        $realized_amount = abs($inv_dp_selisih_kurs);
                                                        $realized_currency = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;

                                                        $journal_RealizedAccount = array(
                                                            'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                                            'PPayNumber' => $PPayNumber,
                                                            'PPayDesc' => $PPayNumber,
                                                            'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                                            'PPaySaldoDebet' => 0,
                                                            'PPaySaldoCredit' => $realized_amount,
                                                            'AmountCurrency' => 0,
                                                            'PPaySignStatus' => 1,
                                                            'ItemCategoryID' => $item_category_id,
                                                            'BranchTransCode' => $Branch_PaidFor,
                                                            'PInvNumber' => $invoice_number,
                                                            'LastUser' => $this->session->userdata("username")
                                                        );
                                                        $this->m_purchase_payment->insert_journal($journal_RealizedAccount);
                                                    }
                                                }
                                            } else {
                                                $PaidStatus = $DPUsed;
                                                $dp_used_book = ($saldo_balance_detail - $DPUsed) + $PaidStatus;
                                                //$dp_used_book 	= $saldo_balance_detail;
                                                $jurnal_dp = (doubleval($saldo_balance_detail - $DPUsed) * doubleval($currency_rate_detail));
                                                $jurnal_dp_currency = (doubleval($saldo_balance_detail - $DPUsed) / doubleval($currency_rate_detail));
                                                $jurnal_dp_no_currency = doubleval($saldo_balance_detail - $DPUsed);
                                                $total_dp += $jurnal_dp;
                                                $total_dp_no_currency += $jurnal_dp_no_currency;

                                                $update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => $dp_used_book, 'TransactionNumber' => $PPayNumber);
                                                $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_sordstatus, $Vendor_Code, $SOrdDetailDPID, $Select_DP);
                                                $PaymentBefore = $saldo_balance_detail - $DPUsed;
                                                $PaymentBefore_Sum += $PaymentBefore;
                                                $PaymentPlus = doubleval($saldo_balance_detail + $DPUsed);
                                                $PaymentPlus_Sum += $PaymentPlus;

                                                $DPAccount = $this->m_account_journal->get_account_name('Uang Muka Pembelian', $Currency_Code); // Uang Muka Category -> 1-4-03-001-00
                                                if ($DPAccount == false) {
                                                    $this->trans_rollback('journal', 'Uang Muka Pembelian', $Currency_Code);
                                                }

                                                if ($Currency_Code == 'IDR') {
                                                    $dp_currency = $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_currency / $Bank_Curr_Rate;
                                                } else {
                                                    $dp_currency = $Bank_Curr_Code == 'IDR' ? $jurnal_dp_no_currency : $jurnal_dp_no_currency;
                                                }

                                                $journal_dp = array(
                                                    'PPayDate' => $PPayDate,
                                                    'PPayNumber' => $PPayNumber,
                                                    'PPayDesc' => $PPayDesc,
                                                    'PPayAccountNumber' => $DPAccount->AccountNumber,
                                                    'PPaySaldoDebet' => 0,
                                                    'PPaySaldoCredit' => $jurnal_dp,
                                                    'AmountCurrency' => $dp_currency,
                                                    'PPaySignStatus' => 1,
                                                    'ItemCategoryID' => $item_category_id,
                                                    'BranchTransCode' => $Branch_PaidFor,
                                                    'PinvNumber' => $invoice_number,
                                                    'POrdDetailDPID' => $row_detail_dp->POrdDetailDPID,
                                                    'LastUser' => $this->session->userdata("username")
                                                );

                                                if ($jurnal_dp > 0) {
                                                    $this->m_purchase_payment->insert_journal($journal_dp);
                                                }

                                                if ($Currency_Code != 'IDR') {
                                                    $inv_dp_selisih_kurs = doubleval($jurnal_dp) - doubleval($jurnal_dp_no_currency * $invoice_rate);
                                                    if ($inv_dp_selisih_kurs > 0) {
                                                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                                                        if ($RealizedAccount == false) {
                                                            $this->trans_rollback('journal', 'Realized, Purchase', $Currency_Code);
                                                        }

                                                        $realized_amount = abs($inv_dp_selisih_kurs);
                                                        $realized_currency = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;

                                                        $journal_RealizedAccount = array(
                                                            'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                                            'PPayNumber' => $PPayNumber,
                                                            'PPayDesc' => $PPayNumber,
                                                            'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                                            'PPaySaldoDebet' => $realized_amount,
                                                            'PPaySaldoCredit' => 0,
                                                            'AmountCurrency' => 0,
                                                            'PPaySignStatus' => 0,
                                                            'ItemCategoryID' => $item_category_id,
                                                            'BranchTransCode' => $Branch_PaidFor,
                                                            'PInvNumber' => $invoice_number,
                                                            'LastUser' => $this->session->userdata("username")
                                                        );

                                                        $this->m_purchase_payment->insert_journal($journal_RealizedAccount);
                                                    } else if ($inv_dp_selisih_kurs < 0) {
                                                        $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $Currency_Code);
                                                        if ($RealizedAccount == false) {
                                                            $this->trans_rollback('journal', 'Realized, Purchase', $Currency_Code);
                                                        }

                                                        $realized_amount = abs($inv_dp_selisih_kurs);
                                                        $realized_currency = $Bank_Curr_Code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $invoice_rate;

                                                        $journal_RealizedAccount = array(
                                                            'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                                            'PPayNumber' => $PPayNumber,
                                                            'PPayDesc' => $PPayNumber,
                                                            'PPayAccountNumber' => $RealizedAccount->AccountNumber,
                                                            'PPaySaldoDebet' => 0,
                                                            'PPaySaldoCredit' => $realized_amount,
                                                            'AmountCurrency' => 0,
                                                            'PPaySignStatus' => 1,
                                                            'ItemCategoryID' => $item_category_id,
                                                            'BranchTransCode' => $Branch_PaidFor,
                                                            'PInvNumber' => $invoice_number,
                                                            'LastUser' => $this->session->userdata("username")
                                                        );
                                                        $this->m_purchase_payment->insert_journal($journal_RealizedAccount);
                                                    }
                                                }
                                            }
                                        }

                                        $update_isedit = array(
                                            'IsEdit' => 1
                                        );
                                        $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_isedit, $Vendor_Code, $SOrdDetailDPID, $Select_DP);
                                    }
                                }
                                /* ======================End================================================================================ */
                            }
                            /* =====================End=================================================================== */

                            /*
                              Journal Discount Invoice - Potongan Pembelian
                             */
                            $total_discount = 0;

                            if ($payment_disc > 0) {
                                $total_loop = 0;
                                $curr_account_no = '';

                                $discount_amount = 0;
                                $discount_currency = 0;
                                $invoice_loop_disc = "";

                                foreach ($data_ppay_detail as $row_disc) {
                                    $payament_ratio_disc = $this->m_purchase_payment->get_payment_by_id($row_disc->InvoicePaymentID);
                                    $ipay_category_ratio = $payament_ratio_disc[0]->ItemCategoryRatio;
                                    $ipay_ItemType = $payament_ratio_disc[0]->ItemType;
                                    $ipay_InvoiceNumber = $payament_ratio_disc[0]->InvoiceNumber;

                                    $ppay_detail_id_disc = $row_disc->PPayDetailID;
                                    $ppay_category_id_disc = $row_disc->ItemCategoryID;
                                    $ppay_category_code_disc = $row_disc->ItemCategoryCode;

                                    if ($ipay_ItemType == 0) {
                                        $DiscountAccount = $this->m_account_journal->get_cat_purchase_account('PaymentDiscount', $ppay_category_id_disc, $Currency_Code); // Potongan Pembelian
                                        if ($Currency_Code == 'IDR') {
                                            if ($DiscountAccount == false) {
                                                $this->trans_rollback('preference', 'Purchase Account -> Payment Discount', $Currency_Code);
                                            }
                                        } else {
                                            if ($DiscountAccount == false) {
                                                $this->trans_rollback('journal', 'Discount Pembelian atau Retur Pembelian Purchase', $Currency_Code);
                                            }
                                        }
                                    } else {
                                        if ($ipay_ItemType == 1) {
                                            $DiscountAccount = $this->m_account_journal->get_sys_service_account('PaymentDiscount', $Currency_Code); // Potongan Pembelian
                                            if ($Currency_Code == 'IDR') {
                                                if ($DiscountAccount == false) {
                                                    $this->trans_rollback('preference', 'Expense Account -> Purchase Payment Discount', $Currency_Code);
                                                }
                                            } else {
                                                if ($DiscountAccount == false) {
                                                    $this->trans_rollback('journal', 'Discount Pembelian atau Retur Pembelian Purchase', $Currency_Code);
                                                }
                                            }
                                        } else {
                                            $DiscountAccount = $this->m_account_journal->get_sys_advance_account('PaymentDiscount', $Currency_Code); // Uang Muka Pembelian Expense
                                            if ($Currency_Code == 'IDR') {
                                                if ($DiscountAccount == false) {
                                                    $this->trans_rollback('preference', 'Adv Payment Account -> Payment Discount', $Currency_Code);
                                                }
                                            } else {
                                                if ($DiscountAccount == false) {
                                                    $this->trans_rollback('journal', 'Discount Pembelian atau Retur Pembelian Purchase', $Currency_Code);
                                                }
                                            }
                                        }
                                    }

                                    $amount_discount = $payment_disc * ($ipay_category_ratio / 100);

                                    if ($Currency_Code == 'IDR') {
                                        $discount_amount = $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount;
                                        $discount_currency = $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount / $Bank_Curr_Rate;
                                    } else {
                                        $discount_amount = $Bank_Curr_Code == 'IDR' ? $amount_discount * $Bank_Curr_Rate : $amount_discount * $Bank_Curr_Rate;
                                        $discount_currency = $Bank_Curr_Code == 'IDR' ? $amount_discount : $amount_discount;
                                    }

                                    $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment($DiscountAccount->AccountNumber, $PPayNumber, $ipay_InvoiceNumber);
                                    if (empty($get_journal_purchase_payment->PPayAccountNumber)) {
                                        $journal_discount = array(
                                            'PPayDate' => $PPayDate,
                                            'PPayNumber' => $PPayNumber,
                                            'PPayDesc' => $PPayDesc,
                                            'PPayAccountNumber' => $DiscountAccount->AccountNumber,
                                            'PPaySaldoDebet' => 0,
                                            'PPaySaldoCredit' => $discount_amount,
                                            'AmountCurrency' => $discount_currency,
                                            'PPaySignStatus' => 1,
                                            'ItemCategoryID' => $item_category_id,
                                            'BranchTransCode' => $Branch_PaidFor,
                                            'PInvNumber' => $invoice_number,
                                            'LastUser' => $this->session->userdata("username")
                                        );
                                        if ($amount_discount > 0) {
                                            $this->m_purchase_payment->insert_journal($journal_discount);
                                        }
                                    } else {
                                        $discount_amount = $discount_amount + $get_journal_purchase_payment->PPaySaldoCredit;
                                        $discount_currency = $discount_currency + $get_journal_purchase_payment->AmountCurrency;

                                        $journal_discount = array(
                                            'PPaySaldoDebet' => 0,
                                            'PPaySaldoCredit' => $discount_amount,
                                            'AmountCurrency' => $discount_currency
                                        );

                                        if ($amount_discount > 0) {
                                            $this->m_purchase_payment->update_journal_invoice($PPayNumber, $journal_discount, $get_journal_purchase_payment->PPayAccountNumber, $ipay_InvoiceNumber);
                                        }
                                    }

                                    $total_discount = $discount_amount;
                                }
                            }
                            /* =====================End=================================================================== */

                            /*
                              Beban Pembulatan
                             */
                            if ($Load_Rounding > 0) {
                                $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccount == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                                if ($Currency_Code == 'IDR') {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                } else {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                }

                                $beban_pembulatan = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => abs($beban_amount),
                                    'AmountCurrency' => abs($beban_currency),
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan);
                            } else if ($Load_Rounding < 0) {
                                $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccount == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                                if ($Currency_Code == 'IDR') {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                } else {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                }

                                $beban_pembulatan = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                    'PPaySaldoDebet' => abs($beban_amount),
                                    'PPaySaldoCredit' => 0,
                                    'AmountCurrency' => abs($beban_currency),
                                    'PPaySignStatus' => 0,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan);
                            }
                            /* ========================End========================== */

                            /*
                              Beban Pembulatan Auto
                             */
                            if ($invoice_owing == 0) {
                                $total_hutang_real = $total_hutang;
                            } else {
                                $total_hutang_real = $payment_dp + $payment_disc + $Load_Rounding + $payment_amount;
                            }

                            $total_relize = ($Relized_all_trans * $Bank_Curr_Rate) - ($Relized_all_trans * $invoice_rate);

                            $realizegl_value_beban = $total_relize / $Bank_Curr_Rate;
                            $realized_amount_beban = $Currency_Code == 'IDR' ? abs($realizegl_value_beban) : abs($realizegl_value_beban) * $Bank_Curr_Rate;

                            if ($total_relize > 0) {
                                $total_relize_all_kredit = abs($realized_amount_beban);
                                $total_relize_all_debet = 0;
                            } else {
                                $total_relize_all_kredit = 0;
                                $total_relize_all_debet = abs($realized_amount_beban);
                            }

                            $Bank = empty($bank_amount) ? 0 : $bank_amount;
                            $Disc = empty($total_discount) ? 0 : $total_discount;
                            $Round = empty($Load_Rounding) ? 0 : $Load_Rounding;
                            $Relize_Debet = empty($total_relize_all_debet) ? 0 : $total_relize_all_debet;
                            $Relize_Kredit = empty($total_relize_all_kredit) ? 0 : $total_relize_all_kredit;
                            $TotalDP_No_Curren = empty($total_dp_no_currency) ? 0 : $total_dp_no_currency;
                            $TotalDP = empty($total_dp) ? 0 : $total_dp;
                            $Beban = empty($total_hutang_real) ? 0 : $total_hutang_real;
                            $selisih_kurs_dp = doubleval($TotalDP) - doubleval($TotalDP_No_Curren * $invoice_rate);

                            if ($selisih_kurs_dp > 0) {
                                $RelizeDP_Debet = 0;
                                $RelizeDP_Kredit = abs($selisih_kurs_dp);
                            } else {
                                $RelizeDP_Debet = abs($selisih_kurs_dp);
                                $RelizeDP_Kredit = 0;
                            }

                            $Total_Beban = ($Bank + $Disc + $Round + $Relize_Debet + ($RelizeDP_Debet + $TotalDP)) - (($Beban * $invoice_rate) + $RelizeDP_Kredit + $Relize_Kredit);

                            if ($Total_Beban > 0) {
                                $BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccountAuto == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                if ($Currency_Code == 'IDR') {
                                    $beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
                                } else {
                                    $beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
                                }

                                $beban_pembulatan_auto = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayNumber,
                                    'PPayAccountNumber' => $BebanAccountAuto->AccountNumber,
                                    'PPaySaldoDebet' => abs($beban_amount_auto),
                                    'PPaySaldoCredit' => 0,
                                    'AmountCurrency' => 0,
                                    'PPaySignStatus' => 0,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan_auto);
                            } else if ($Total_Beban < 0) {
                                $BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccountAuto == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                if ($Currency_Code == 'IDR') {
                                    $beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
                                } else {
                                    $beban_amount_auto = $Bank_Curr_Code == 'IDR' ? $Total_Beban : $Total_Beban;
                                }

                                $beban_pembulatan_auto = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayNumber,
                                    'PPayAccountNumber' => $BebanAccountAuto->AccountNumber,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => abs($beban_amount_auto),
                                    'AmountCurrency' => 0,
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PInvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan_auto);
                            }
                            /* ========================End===================== */

                            /*
                              Insert Journal Payment Realized Account
                             */
                            if ($total_relize > 0) {
                                $realizegl_value = $total_relize / $Bank_Curr_Rate;
                                $realized_amount = $Currency_Code == 'IDR' ? abs($realizegl_value) : abs($realizegl_value) * $Bank_Curr_Rate;
                                $realized_currency = $Bank_Curr_Code == 'IDR' ? $realizegl_value * $Bank_Curr_Rate : 0;
                                //$realized_currency  = 0;    //abs($realizegl_value);

                                $this->Insert_Journal_Realized(
                                        $PPayDate, $PPayNumber, $PPayDesc, $RealizedAccount->AccountNumber, $realized_amount, 0, $realized_currency, 0, $item_category_id, $Branch_PaidFor
                                );
                            }
                            /* =====================End=================================================================== */

                            /*
                              Insert Journal Payment Realized Account
                             */
                            if ($total_relize < 0) {
                                $realizegl_value = $total_relize / $Bank_Curr_Rate;
                                $realized_amount = $Currency_Code == 'IDR' ? abs($realizegl_value) : abs($realizegl_value) * $Bank_Curr_Rate;
                                $realized_currency = $Bank_Curr_Code == 'IDR' ? $realizegl_value * $Bank_Curr_Rate : 0;
                                //$realized_currency  = 0;    //abs($realizegl_value);

                                $this->Insert_Journal_Realized(
                                        $PPayDate, $PPayNumber, $PPayDesc, $RealizedAccount->AccountNumber, 0, $realized_amount, $realized_currency, 1, $item_category_id, $Branch_PaidFor
                                );
                            }
                            /* =====================End=================================================================== */
                        } else if ($row->Invoice_Type == 'PO') {
                            $data_ppay_detail = $this->m_purchase_payment->get_ppay_detail($invoice_number, $PPayNumber);
                            $total_ppay_realizedgl = 0;
                            $ppay_realizedgl = 0;
                            $advance_value = 0;
                            $advance_currency = 0;
                            $total_amount_advance = 0;

                            foreach ($data_ppay_detail as $row_ppay) {
                                $payament_ratio = $this->m_purchase_payment->get_payment_by_id($row_ppay->InvoicePaymentID);
                                $cat_payment_ratio = $payament_ratio[0]->ItemCategoryRatio;
                                $ipay_ItemType = $payament_ratio[0]->ItemType;

                                $ppay_detail_id = $row_ppay->PPayDetailID;
                                $ppay_category_id = $row_ppay->ItemCategoryID;
                                $ppay_category_code = $row_ppay->ItemCategoryCode;
                                $ppay_ItemCategoryRatio = $row_ppay->ItemCategoryRatio;

                                $currency_payable = $payment_currency * ($cat_payment_ratio / 100);
                                $amount_invoice = $invoice_amount_copy * ($cat_payment_ratio / 100);
                                $amount_advance = $payment_amount * ($cat_payment_ratio / 100);
                                $amount_advance_curr = $payment_currency * ($cat_payment_ratio / 100);

                                $amount_rounded = $Load_Rounding * ($cat_payment_ratio / 100);

                                $amount_advance_owing = ($payment_amount + $Load_Rounding) * ($cat_payment_ratio / 100);

                                if ($Currency_Code == 'IDR') {
                                    $total_amount_advance = $amount_advance + $amount_rounded;
                                } else {
                                    if ($Bank_Curr_Code == 'IDR') {
                                        $total_amount_advance = ($amount_advance_curr / $Bank_Curr_Rate) + $amount_rounded;
                                    } else {
                                        $total_amount_advance = $amount_advance + $amount_rounded;
                                    }
                                }

                                if ($Currency_Code == 'IDR') {
                                    $inv_curr_amount = $amount_advance;
                                    $ppay_curr_amount = $amount_advance;
                                } else {
                                    $inv_curr_amount = $amount_advance * $invoice_rate;
                                    $ppay_curr_amount = $amount_advance * $Bank_Curr_Rate;
                                }

                                $ppay_realizedgl = $ppay_curr_amount - $inv_curr_amount;
                                $inv_owing = $amount_invoice - ($amount_advance_owing);

                                /*
                                  .Update ppaydetail
                                 */
                                $this->update_detail(
                                        $Select_DP, $ppay_detail_id, $inv_owing, $Bank_Curr_Rate, NULL, 0, 0, $amount_advance, $amount_advance, $currency_payable, $inv_curr_amount, $ppay_realizedgl, $amount_rounded
                                );
                                /* ====================================================================================== */

                                $BankAccount = $BankPayment;

                                if ($ipay_ItemType == 0) {
                                    $AdvanceAccount = $this->m_account_journal->get_cat_purchase_account('AdvancePurchase', $ppay_category_id, $Currency_Code); // Uang Muka Category -> 1-4-03-001-00                            
                                    if ($Currency_Code == 'IDR') {
                                        if ($AdvanceAccount == false) {
                                            $this->trans_rollback('preference', 'Purchase Account -> Advance Purchase,', $Currency_Code);
                                        }
                                    } else {
                                        if ($AdvanceAccount == false) {
                                            $this->trans_rollback('journal', 'Uang Muka Pembelian,', $Currency_Code);
                                        }
                                    }
                                } else {
                                    if ($ipay_ItemType == 1) {
                                        $AdvanceAccount = $this->m_account_journal->get_sys_service_account('Advance', $Currency_Code); // Uang Muka Pembelian Expense
                                        if ($Currency_Code == 'IDR') {
                                            if ($AdvanceAccount == false) {
                                                $this->trans_rollback('preference', 'Expense Account -> Purchase Advance', $Currency_Code);
                                            }
                                        } else {
                                            if ($AdvanceAccount == false) {
                                                $this->trans_rollback('journal', 'Uang Muka Pembelian,', $Currency_Code);
                                            }
                                        }
                                    } else {
                                        $AdvanceAccount = $this->m_account_journal->get_sys_advance_account('DownPayment', $Currency_Code); // Uang Muka Pembelian Advance
                                        if ($Currency_Code == 'IDR') {
                                            if ($AdvanceAccount == false) {
                                                $this->trans_rollback('preference', 'Adv Payment Account ->Purchase Advance', $Currency_Code);
                                            }
                                        } else {
                                            if ($AdvanceAccount == false) {
                                                $this->trans_rollback('journal', 'Uang Muka Pembelian,', $Currency_Code);
                                            }
                                        }
                                    }
                                }

                                if ($Currency_Code == 'IDR') {
                                    $advance_value = $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance;
                                    $advance_currency = $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance / $Bank_Curr_Rate;
                                } else {
                                    $advance_value = $Bank_Curr_Code == 'IDR' ? $total_amount_advance * $Bank_Curr_Rate : $total_amount_advance * $Bank_Curr_Rate;
                                    $advance_currency = $Bank_Curr_Code == 'IDR' ? $total_amount_advance : $total_amount_advance;
                                }

                                /*
                                  Journal DP Account Purchase
                                 */
                                $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment($AdvanceAccount->AccountNumber, $PPayNumber, $invoice_number);
                                if (empty($get_journal_purchase_payment->PPayAccountNumber)) {
                                    $journal_dp = array(
                                        'PPayDate' => $PPayDate,
                                        'PPayNumber' => $PPayNumber,
                                        'PPayDesc' => $PPayDesc,
                                        'PPayAccountNumber' => $AdvanceAccount->AccountNumber,
                                        'PPaySaldoDebet' => $advance_value,
                                        'PPaySaldoCredit' => 0,
                                        'AmountCurrency' => $advance_currency,
                                        'PPaySignStatus' => 0,
                                        'ItemCategoryID' => $ppay_category_id,
                                        'BranchTransCode' => $Branch_PaidFor,
                                        'PInvNumber' => $invoice_number,
                                        'LastUser' => $this->session->userdata("username")
                                    );

                                    if ($advance_value > 0) {
                                        $this->m_purchase_payment->insert_journal($journal_dp);
                                    }
                                } else {
                                    $advance_value = $advance_value + $get_journal_purchase_payment->PPaySaldoDebet;
                                    $advance_currency = $advance_currency + $get_journal_purchase_payment->AmountCurrency;

                                    $journal_dp = array(
                                        'PPaySaldoDebet' => $advance_value,
                                        'PPaySaldoCredit' => 0,
                                        'AmountCurrency' => $advance_currency
                                    );

                                    if ($advance_value > 0) {
                                        $this->m_purchase_payment->update_journal_invoice($PPayNumber, $journal_dp, $get_journal_purchase_payment->PPayAccountNumber, $invoice_number);
                                    }
                                }
                                $total_ppay_realizedgl = $total_ppay_realizedgl + $ppay_realizedgl;
                                /* ====================================================================================== */
                            }



                            /*
                              Journal Bank Acccount
                             */
                            $payment_val = doubleval($payment_amount);
                            $bank_amount = 0;
                            $bank_currency = 0;

                            if ($Currency_Code == 'IDR') {
                                $bank_amount = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;
                                $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val / $Bank_Curr_Rate;
                            } else {
                                $bank_amount = $Bank_Curr_Code == 'IDR' ? ($payment_currency / $Bank_Curr_Rate) * $Bank_Curr_Rate : $payment_val * $Bank_Curr_Rate;
                                $bank_currency = $Bank_Curr_Code == 'IDR' ? $payment_val : $payment_val;
                            }

                            $get_journal_purchase_payment = $this->m_purchase_payment->get_journal_purchase_payment($BankAccount, $PPayNumber, $invoice_number);

                            if (empty($get_journal_purchase_payment->PPayAccountNumber)) {
                                $journal_bank = array(
                                    'PPayDate' => $PPayDate,
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BankAccount,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => $bank_amount,
                                    'AmountCurrency' => $bank_currency,
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PinvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($journal_bank);
                            } else {
                                $bank_amount = $bank_amount + $get_journal_purchase_payment->PPaySaldoCredit;
                                $bank_currency = $bank_currency + $get_journal_purchase_payment->AmountCurrency;

                                $journal_bank = array(
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => $bank_amount,
                                    'AmountCurrency' => $bank_currency
                                );
                                $this->m_purchase_payment->update_journal_invoice($PPayNumber, $journal_bank, $get_journal_purchase_payment->PPayAccountNumber, $invoice_number);
                            }
                            /* ====================================================================================== */



                            /*
                              RoundingLoad greater than 0 (Beban Pembulatan)
                             */
                            if ($Load_Rounding > 0) {
                                $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccount == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                                if ($Currency_Code == 'IDR') {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                } else {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                }

                                $beban_pembulatan = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                    'PPaySaldoDebet' => 0,
                                    'PPaySaldoCredit' => abs($beban_amount),
                                    'AmountCurrency' => abs($beban_currency),
                                    'PPaySignStatus' => 1,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PinvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan);
                            } else if ($Load_Rounding < 0) {
                                $BebanAccount = $this->m_account_journal->get_account_name('Beban Pembulatan');
                                if ($BebanAccount == false) {
                                    $this->trans_rollback('journal', 'Beban Pembulatan', $Currency_Code);
                                }

                                $beban_amount = $Currency_Code == 'IDR' ? $Load_Rounding : $Load_Rounding;
                                if ($Currency_Code == 'IDR') {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                } else {
                                    $beban_currency = $Bank_Curr_Code == 'IDR' ? $Load_Rounding : $Load_Rounding / $Bank_Curr_Rate;
                                }

                                $beban_pembulatan = array(
                                    'PPayDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'PPayNumber' => $PPayNumber,
                                    'PPayDesc' => $PPayDesc,
                                    'PPayAccountNumber' => $BebanAccount->AccountNumber,
                                    'PPaySaldoDebet' => abs($beban_amount),
                                    'PPaySaldoCredit' => 0,
                                    'AmountCurrency' => abs($beban_currency),
                                    'PPaySignStatus' => 0,
                                    'ItemCategoryID' => $item_category_id,
                                    'BranchTransCode' => $Branch_PaidFor,
                                    'PinvNumber' => $invoice_number,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_payment->insert_journal($beban_pembulatan);
                            }
                            /* ====================================================================================== */



                            $total_amount_paid += $payment_amount;
                            $total_currency_paid += $payment_currency;
                        }
                    }
                } //akhir paid = Yes
                else {
                    //20. Delete PPay Detail for UnPaid Status
                    $this->m_purchase_payment->delete_detail($invoice_number);
                }
            }//akhir foreach

            /*
              Update PurchasePayment for header info only.
             */
            $data_group = array(
                'PPayDesc' => $PPayDesc,
                'ChequeNumber' => $ChequeNumber,
                'PInvTotalAmount' => $hdn_PInvTotalAmount,
                'PPayTotalDiscount' => $hdn_PPayTotalDiscount,
                'PPayTotalDPUsed' => $hdn_PPayTotalDPUsed,
                'PPayTotalAmount' => $total_amount_paid,
                'PPayTotalCurrency' => $total_currency_paid,
                'PPayTotalOwing' => $hdn_PPayTotalOwing,
                'BankCurrRate' => $Bank_Curr_Rate,
				'AppFinished' 	=> 2,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_payment->update($data_group, $PPayNumber);
            /* ====================End============================================================= */

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

        echo json_encode($result);
    }

    public function insert_detail($PPayDate, $PordetailDP, $ipay_ItemCategoryRatio, $Select_DP, $invoice_payment_id, $ppay_number, $invoice_number, $invoice_date, $invoice_amount, $invoice_owing, $invoice_rate, $fiscal_rate, $bank_curr_rate, $ppay_disc_date, $payment_disc, $payment_dp, $payment_amount, $payment_total, $payment_currency, $invoice_currency, $payment_real_gl, $payment_rounded, $invoice_type, $item_category_id, $item_category_code, $ipay_category_amount, $ppay_item_type, $ppn_fiscal_status) {
        $detail_data = array(
            'InvoicePaymentID' => $invoice_payment_id,
            'PPayNumber' => $ppay_number,
            'PInvNumber' => $invoice_number,
            'POrdNumber' => $Select_DP,
            'PInvDate' => $invoice_date,
            'PInvAmount' => $invoice_amount,
            'PInvAmountTemp' => $ipay_category_amount,
            'PInvOwing' => $invoice_owing,
            'PInvCurrRate' => $invoice_rate,
            'PInvFiscalRate' => $fiscal_rate,
            'PPayCurrRate' => $bank_curr_rate,
            'PPayDiscDate' => $ppay_disc_date,
            'PPayDiscount' => $payment_disc,
            'PPayDPUsed' => $payment_dp,
            'PPayAmount' => $payment_amount,
            'PPayTotalAmnt' => $payment_total,
            'PPayCurrency' => $payment_currency,
            'PInvCurrency' => $invoice_currency,
            'PPayRealizedGL' => $payment_real_gl,
            'PPayRounded' => $payment_rounded,
            'PPayPaidStatus' => 1,
            'PPayInvoiceType' => $invoice_type,
            'ItemCategoryID' => $item_category_id,
            'ItemCategoryCode' => $item_category_code,
            'ItemCategoryRatio' => $ipay_ItemCategoryRatio,
            'PPayItemType' => $ppay_item_type,
            'POrdDetailDPID' => $PordetailDP,
			'PPayTime' 		=> date('His'),
			'PPayDate' 		=> $PPayDate,
            'PPayFiscalStatus' => $ppn_fiscal_status,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_payment->insert_detail($detail_data);
    }

    public function update_detail($Select_DP, $ipay_payment_id, $pinv_owing, $bank_curr_rate, $ppay_disc_date, $payment_disc, $payment_dp, $payment_amount, $payment_total, $payment_currency, $invoice_currency, $payment_real_gl, $payment_rounded) {
        $detail_data = array(
            'PInvOwing' => $pinv_owing,
            'PPayCurrRate' => $bank_curr_rate,
            'PPayDiscDate' => $ppay_disc_date,
            'PPayDiscount' => $payment_disc,
            'PPayDPUsed' => $payment_dp,
            'PPayAmount' => $payment_amount,
            'PPayTotalAmnt' => $payment_total,
            'PPayCurrency' => $payment_currency,
            'PInvCurrency' => $invoice_currency,
            'PPayRealizedGL' => $payment_real_gl,
            'PPayRounded' => $payment_rounded,
            'POrdNumber' => $Select_DP,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_payment->update_detail($detail_data, $ipay_payment_id);
    }

    public function Insert_Journal_Realized($ppay_date, $ppay_number, $ppay_desc, $ppay_account_number, $ppay_saldo_debet, $ppay_saldo_credit, $ppay_saldo_currency, $ppay_sign_status, $item_category_id, $Branch_PaidFor) {
        $journal_realized = array(
            'PPayDate' => $ppay_date,
            'PPayNumber' => $ppay_number,
            'PPayDesc' => $ppay_desc,
            'PPayAccountNumber' => $ppay_account_number,
            'PPaySaldoDebet' => $ppay_saldo_debet,
            'PPaySaldoCredit' => $ppay_saldo_credit,
            'AmountCurrency' => $ppay_saldo_currency,
            'PPaySignStatus' => $ppay_sign_status,
            'ItemCategoryID' => $item_category_id,
            'BranchTransCode' => $Branch_PaidFor,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_payment->insert_journal($journal_realized);
    }

    public function suspend_data() {
        $ppay_number = $this->input->post('id');
        $data = $this->m_purchase_payment->get_detail_for_suspend($ppay_number);

        /*
          0=PI
          1=PO
         */
        $this->db->trans_begin();
		$detail_invoice = $this->m_purchase_payment->get_detail_invoice($ppay_number);
        foreach ($detail_invoice as $row_detail) {
            if (($row_detail->Select_DP != "") || ($row_detail->Select_DP != NULL)) {
                if ($row_detail->PPayInvoiceType == 0) {
                    if ($row_detail->Payment_DP > 0) {
                        $DPAccount = $this->m_account_journal->get_sys_purchase_account('AdvancePurchase', $data->CurrencyCode); // Uang Muka Category -> 1-4-03-001-00
                        $sordetail_dp_new = $this->m_purchase_payment->get_payment_detail_dp_suspend($data->VendorCode, $row_detail->Select_DP, $DPAccount->AccountNumber);

                        foreach ($sordetail_dp_new as $row_dp_suspend) {
                            $DPUsed = $row_dp_suspend->DPUsed;
                            $POrdDetailDPID = $row_dp_suspend->POrdDetailDPID;
                            $POrdNumber_DP = $row_dp_suspend->POrdNumber;
                            $total_pordetail = $row_dp_suspend->AmountCurrency - $DPUsed;

                            //if($Select_DP != $POrdNumber_DP){
                            $update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => abs($total_pordetail), 'DPTransaction' => 1, 'TransactionNumber' => NULL, 'IsEdit' => 0);
                            $this->m_purchase_payment->update_po_detail_dp_pay_before($update_sordstatus, $data->VendorCode, $row_detail->Select_DP, $POrdDetailDPID);
                            //}
                        }
                    }
                }
            }
        }

        $vendor_dp = $this->m_vendors->get_saldo_by_id($data->VendorCode);

        $data_dp_used = array(
            'LockStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_vendors->update($data_dp_used, $data->VendorCode, $data->BranchPaidFor);

        $data_pp = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_payment->update($data_pp, $ppay_number);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('suspend', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('suspend', 1);
        }
        echo json_encode($result);
    }

    public function approval() {
        if (in_array($this->session->userdata("jobtitle_status"), $this->jobtitle_status)) {
            $detail_post = $this->input->post('Detail');
            $detail = json_decode($detail_post);

            if (count($detail) > 0) {
                $this->db->trans_begin();

                $branch_code = $this->session->userdata('branch');
                $status = $this->input->post('Status');
                $vendor_code = $this->input->post('VendorCode');
                $ppay_number = $this->input->post('PPayNumber');
                $bank_curr_code = $this->input->post('BankCurrCode');
                $bank_curr_rate = $this->input->post('BankCurrRate');
                $Vend_Curr_Code = $this->input->post('Vend_Curr_Code');
                $PPayDate = $this->input->post('txt_ppay_date');
                $DPPartial = $this->input->post('DPPartial');
				$ChequeNo = $this->input->post('ChequeNo');
				$PGirNumber = $this->input->post('PGirNumber');
				
                $data = $this->m_purchase_payment->get_detail($ppay_number);

                /*
                  Cek Concuren For Approval Dir
                 */
				 if($ChequeNo != ""){
					$get_giro_check = $this->m_purchase_payment->get_giro_check_to_purchase_payment($PGirNumber);
					if ($get_giro_check != FALSE) {
						$result['status'] = false;
						$result['message'] = "Maaf Transaksi gagal di Approve, Purchase giro sudah dipakai di Purchase Payment dengan No Transaksi Giro" . $PGirNumber . " Silahkan Suspend Transaksi ini";
						$this->db->trans_rollback();
						echo json_encode($result);
						die();
					}
				}
			
                $get_employee = $this->m_employee->get_detail($data->AppLevel2Code);
                if (($data->AppLevel2Code != NULL)) {
                    $result['status'] = false;
                    $result['message'] = 'Maaf Transaksi gagal di Approve, karena transaksi sudah di approve terlebih dahulu oleh, ' . $get_employee->EmployeeName . ' pada tanggal ' . date("d-m-Y", strtotime($data->AppLevel2Date)) . '';

                    echo json_encode($result);
                    die();
                }
                /* =========================End======================================== */

                $app_finished = 1;
                $trans_status = 2;
                $total_amount = 0;
                $total_DP = 0;
                $total_round = 0;

                foreach ($detail as $row) {
                    if ($row->Paid == 'Yes') {
                        $invoice_number = $row->Invoice_Number;
                        $total_amount = $row->Payment_Amount;
                        $total_DP = $row->Payment_DP;
                        $total_discount = $row->Payment_Discount;
                        $total_round = $row->Load_Rounding;
                        $Select_DP = $row->Select_DP;
						$Invoice_Amount = $row->Invoice_Amount;

                        $DP_Partial = 0;
                        $DP_Vendor = 0;

                        if ($row->ItemCategoryID == -3) {
                            /*
                              Update vendor outstanding fiscal
                             */
                            $vendor_saldo = $this->m_vendors->get_saldo_by_id($vendor_code);
                            $ppn_fiscal_debt = $vendor_saldo[0]->OutStandingFiscal - ($total_amount + $total_round);

                            $data_vendor = array(
                                'LockStatus' => 0,
                                'OutStandingFiscal' => $ppn_fiscal_debt,
                                'LastUser' => $this->session->userdata("username")
                            );
                            $this->m_vendors->update($data_vendor, $vendor_code, $vendor_saldo[0]->BranchCode);
                            /* ========================End=================================== */
                        } else {
                            if ($row->Invoice_Type == 'PI') {
                                
								/*
									Cek Outstanding Giro,Journal Dan PP
								*/
								$get_purchase_giro_status_on_progres = $this->m_purchase_giro->get_purchase_giro_status_on_progres($invoice_number);
								$PGInvTotalAmount 		= empty($get_purchase_giro_status_on_progres->PaymentAmount) ? 0 : $get_purchase_giro_status_on_progres->PaymentAmount;
								
								$get_purchase_payment = $this->m_purchase_giro->get_purchase_payment($invoice_number);
								$PPTotalAmount 		= empty($get_purchase_payment->PaymentAmount) ? 0 : $get_purchase_payment->PaymentAmount;
								
								$get_purchase_payment_finish = $this->m_purchase_giro->get_purchase_payment_finish($invoice_number);
								$PPTotalAmount_Finish 		= empty($get_purchase_payment_finish->PaymentAmount) ? 0 : $get_purchase_payment_finish->PaymentAmount;
								
								$get_purchase_journal = $this->m_purchase_giro->get_purchase_journal($invoice_number);
								$PJTotalAmount 		= empty($get_purchase_journal->PaymentAmount) ? 0 : $get_purchase_journal->PaymentAmount;
								
								$get_purchase_invoice = $this->m_purchase_giro->get_purchase_invoice($invoice_number);
								$PInvTotalDP 		= empty($get_purchase_invoice->PInvTotalDP) ? 0 : $get_purchase_invoice->PInvTotalDP;
								
								$Outstanding = ($Invoice_Amount - $PInvTotalDP) - ($PGInvTotalAmount + $PPTotalAmount + $PJTotalAmount + $PPTotalAmount_Finish);
								
								if($Outstanding < 0){
									$this->db->trans_rollback();
									$result['status'] = FALSE;
									$result['message'] = "Transaksi gagal di Approve Pembayaran sudah melebihi Invoice Amount dengan no Transaksi ".$invoice_number."";
									
									echo json_encode($result);
									die();
								}
			
								/*=================================End===========================================*/
								
								/*
                                  Update outstanding vendor
                                 */
                                $vendor_saldo = $this->m_vendors->get_saldo_by_id($vendor_code);

                                $saldo_balance = $vendor_saldo[0]->OutStanding - ($total_amount + $total_DP + $total_discount + $total_round);
                                $saldodp_balance = $vendor_saldo[0]->SaldoDPBalance - $total_DP;

                                $data_vendor = array(
                                    'OutStanding' => $saldo_balance,
                                    'SaldoDPBalance' => $saldodp_balance,
                                    'LockStatus' => 0,
                                    'LastUser' => $this->session->userdata("username")
                                );
                                $this->m_vendors->update($data_vendor, $vendor_code, $vendor_saldo[0]->BranchCode);

                                /* ==============End================================================ */

                                /*
                                  Update pordetail for status dp for
                                  jika dp used dan dp balance tidak sama maka status dp for berubah jadi 1
                                 */
                                $status_dp_for = $this->m_purchase_payment->get_pordetail_dp_invoice_or_return($vendor_code, $Select_DP, 1);
                                foreach ($status_dp_for as $row_dp_for) {
                                    $DPUsed = $row_dp_for->DPUsed;
                                    $SaldoDPBalance = $row_dp_for->SaldoDPBalance;
                                    $SOrdDetailDPID = $row_dp_for->POrdDetailDPID;

                                    if ($DPUsed != $SaldoDPBalance) {
                                        $IsEdit = 1;
                                    } else {
                                        $IsEdit = 0;
                                    }

                                    $update_dp_for = array(
                                        'IsEdit' => $IsEdit
                                    );
                                    $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_dp_for, $vendor_code, $SOrdDetailDPID, $Select_DP);
                                }
                            } else if ($row->Invoice_Type == 'PO') {

								/*
									Cek Outstanding Giro,Journal Dan PP
								*/
								$get_purchase_giro_status_on_progres = $this->m_purchase_giro->get_purchase_giro_status_on_progres($invoice_number);
								$PGInvTotalAmount 		= empty($get_purchase_giro_status_on_progres->PaymentAmount) ? 0 : $get_purchase_giro_status_on_progres->PaymentAmount;
								
								$get_purchase_payment = $this->m_purchase_giro->get_purchase_payment($invoice_number);
								$PPTotalAmount 		= empty($get_purchase_payment->PaymentAmount) ? 0 : $get_purchase_payment->PaymentAmount;
								
								$get_purchase_payment_finish = $this->m_purchase_giro->get_purchase_payment_finish($invoice_number);
								$PPTotalAmount_Finish 		= empty($get_purchase_payment_finish->PaymentAmount) ? 0 : $get_purchase_payment_finish->PaymentAmount;
								
								$get_purchase_invoice = $this->m_purchase_giro->get_purchase_invoice($invoice_number);
								$PInvTotalDP 		= empty($get_purchase_invoice->PInvTotalDP) ? 0 : $get_purchase_invoice->PInvTotalDP;
								
								$Outstanding = ($Invoice_Amount - $PInvTotalDP) - ($PGInvTotalAmount + $PPTotalAmount + $PPTotalAmount_Finish);
								
								if($Outstanding < 0){
									$this->db->trans_rollback();
									$result['status'] = FALSE;
									$result['message'] = "Transaksi gagal di Approve Pembayaran sudah melebihi Invoice Amount dengan no Transaksi ".$invoice_number."";
									
									echo json_encode($result);
									die();
								}
								/*================End===============*/
								
                                if ($Vend_Curr_Code == 'IDR') {
                                    $currency_rate_po = 1;
                                } else {
                                    $currency_rate_po = $bank_curr_rate;
                                }

                                if ($Vend_Curr_Code == 'IDR') {
                                    $Paymen_DP = doubleval($row->Payment_Amount + $row->Load_Rounding);
                                } else {
                                    $Paymen_DP = doubleval($row->Payment_Amount + $row->Load_Rounding);
                                }

                                /* ==============================================insert pordetail dp========================================== */
                                $data_detail_dp = array(
                                    'POrdNumber' => $row->Invoice_Number,
                                    'VendorCode' => $vendor_code,
                                    'PPayNumber' => $ppay_number,
                                    'POrdTotalDP' => $row->Invoice_Amount,
                                    'Owing' => $row->Invoice_Owing,
                                    'CurrencyRate' => $currency_rate_po,
                                    'PaymentAmount' => $Paymen_DP,
                                    'SaldoDPBalance' => $Paymen_DP,
                                    'PaymentDate' => date("Y-m-d", strtotime($PPayDate)),
                                    'SOrdStatus' => 1,
                                    'LastUser' => $this->session->userdata("username"),
                                    'LastEdited' => date('Ymdhis')
                                );

                                $this->m_purchase_payment->insert_po_detail_dp($data_detail_dp);
                                /* =========================================end=============================================================== */

                                /* ===============================calculate dp partial========================================================= */
                                $vendor_dp = $this->m_vendors->get_saldo_by_id($vendor_code);
                                $DP_Vendor = $vendor_dp[0]->SaldoDPBalance;

                                if ($row->Invoice_Owing == 0) {
                                    $DP_Vendor = $DP_Vendor + $row->Invoice_Amount;
                                    $DPPartial = $DPPartial + $row->Payment_Amount + $row->Load_Rounding;
                                    $DPPartial = $DPPartial - $row->Invoice_Amount;
                                } else {
                                    $DP_Vendor = $DP_Vendor;
                                    $DPPartial = $DPPartial + $row->Payment_Amount + $row->Load_Rounding;
                                }
                                /* ========================end================================================================================= */

                                /*
                                  Update dp paid di vendor
                                 */
                                $data_vendor_dp = array(
                                    'SaldoDPBalance' => $DP_Vendor,
                                    'LockStatus' => 0,
                                    'SaldoDPPartial' => $DPPartial,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_vendors->update($data_vendor_dp, $vendor_code, $vendor_dp[0]->BranchCode);
                                /* =================End============================================================== */

                                /*
                                  Update PO total payment DP
                                 */
                                $pord_totaldp = $this->m_purchase_order->get_ppay_total_dp($invoice_number);
                                $new_ppay_totaldp = $pord_totaldp[0]->PPayTotalDP + ($total_amount + $row->Load_Rounding);

                                $data_po = array(
                                    'PPayTotalDP' => $new_ppay_totaldp,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_order->update($data_po, $invoice_number);
                                /* =================End============================================================== */

                                /* ================Update purchase Order for Receive DP=============================================================== */
                                $this->m_purchase_order->set_on_progress_dp_paid($invoice_number);
                                /* ==============================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 = $bank_curr_code == 'IDR' ? $row_detail->PPayCurrency : $row_detail->PPayCurrency * $bank_curr_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' => $data_payment[0]->InvoiceOwing - ($row_detail->PPayDPUsed + $row_detail->PPayDiscount + $row_detail->PPayRounded + $row_detail->PPayAmount),
                                '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 + $row_detail->PPayCurrency,
                                //'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================================================================================================ */
                    }

                    //2. Set Finish Status as Purhcase Invoice table
                    if (($row->Invoice_Type == 'PI') || ($row->ItemCategoryID == -3)) {
                        $get_invoice_receipt = $this->m_purchase_payment->set_finish_invoice($invoice_number);
                        foreach ($get_invoice_receipt as $row_receipt) {
                            if (abs(round($row_receipt->InvoiceOwing, 1)) == 0) {
                                $data_pi = array(
                                    'TransStatus' => 2,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_invoice->update($data_pi, $invoice_number);
                            }
                        }
                    }
                    //-------------------------------------------------------------------------------------------------//
                }

                //8. Update Approval Finished for update Journal
                $data_pp = array(
                    'TransStatus' => $trans_status,
                    'AppLevel1Status' => 1,
                    'AppLevel1Code' => $this->session->userdata("username"),
                    'AppLevel1Date' => date("Y-m-d"),
                    'AppFinished' => $app_finished,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_payment->update($data_pp, $ppay_number);
                //-------------------------------------------------------------------------------------------------------------//
				
				if($PGirNumber != ""){
					$data_pgir = array(
						'TransStatus' => 2,
						'LastUser' => $this->session->userdata("username")
					);

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

            echo json_encode($result);
            die();
        }
    }
	
	function reverse_data_detail() {
		try{
			$txt_ppay_no  		= $this->input->post('txt_ppay_no');
			$vendor_code      	= $this->input->post('cbg_vendor');
			$bank_curr_code 	= $this->input->post('hdn_bank_curr_code');
			$bank_curr_rate 	= $this->input->post('txt_bank_curr_rate');
			$txt_ppay_date 		= $this->input->post('txt_ppay_date');
			$cbg_branch 		= $this->input->post('cbg_branch');
			$hdn_pgir_number 	= $this->input->post('hdn_pgir_number');
			
			$detail_post 		= $this->input->post('detail');
            $detail 			= json_decode($detail_post);
			
			$date_transaction 	= check_end_periode($txt_ppay_no);
			 
			$get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);//Check Periode End
			$get_customer 	 = $this->m_purchase_dp->get_vendor_code($vendor_code);
			 
			if ($get_end_periode) {
				throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
			} else if($get_customer->LockStatus == 1){
				throw new Exception("Maaf Vendor ini mempunya Transaksi yang belum di selesaikan di Purchase DP Journal atau Purchase Journal, Silahkan proses terlebih dahulu"); //sudah di end periode atau belum
			}
			
			foreach($detail as $row_detail){
				$invoice_number = $row_detail->Invoice_Number;
				$total_amount 	= $row_detail->Payment_Amount;
				$total_DP 		= $row_detail->Payment_DP;
				$total_discount = $row_detail->Payment_Discount;
				$total_round 	= $row_detail->Load_Rounding;
				$Select_DP 		= $row_detail->Select_DP;
				$Invoice_Type 	= $row_detail->Invoice_Type;
				
				$DPPartial  		= 0;
				$DP_Customer 		= 0;
				$SInvDate_Loop_new 		= "";	
				
				if(($Invoice_Type == "PO") && ($row_detail->ItemCategoryID != -3)){
					$get_sales_invoicedp = $this->m_purchase_payment->get_purchase_order_dp_detail($invoice_number);
					foreach($get_sales_invoicedp as $row_detail_dp){
						$PInvDate_Loop 		= $row_detail_dp->PPayDate.' '.$row_detail_dp->PPayTime;
						$PInvDate_detail 	= $row_detail->PPayDate.' '.$row_detail->PPayTime;
						
						if(($PInvDate_Loop > $PInvDate_detail)){
							throw new Exception('Reverse tidak berhasil, karna ada transaksi melebihi tanggal transaksi ini silahkan reverse terlebih dahulu transaki no '.$row_detail_dp->PPayNumber.''); //sudah di end periode atau belum
						}
					}
					
					$get_sales_receipt_useddp = $this->m_purchase_payment->get_purchase_payment_dp_used($invoice_number);
					if($get_sales_receipt_useddp != false){
						$PPayNumber 		= $get_sales_receipt_useddp->PPayNumber;
						
						throw new Exception('Reverse tidak berhasil, karena Dp ini sudah dipakai di Purchase Payment, silahkan Reverse transaki Purchase Payment dengan No '.$PPayNumber.''); //sudah di end periode atau belum
					}
					
					$get_purchase_dp_useddp = $this->m_purchase_payment->get_purchase_dp_useddp($invoice_number, 'at_purchasedp', 'PDpayNumber','POrdNumber');
					if($get_purchase_dp_useddp != false){
						$PDpayNumber 		= $get_sales_dp_useddp->PDpayNumber;
						
						throw new Exception('Reverse tidak berhasil, karena Dp ini sudah dipakai di Purchase Dp Journal, silahkan Reverse transaki Purchase Dp Journal dengan No '.$PDpayNumber.''); //sudah di end periode atau belum
					}
					
					$get_dp_on_purchase_invoice = $this->m_purchase_payment->get_purchase_dp_useddp($invoice_number, 'at_purchaseinvoice', 'PInvNumber','POrdNumber');
					if($get_dp_on_purchase_invoice != false){
						$PInvNumber 		= $get_dp_on_purchase_invoice->PInvNumber;
						
						throw new Exception('Reverse tidak berhasil, karena Dp ini sudah dipakai di Purchase Invoice, silahkan Reverse transaki Purchase Invoice dengan No '.$PInvNumber.''); //sudah di end periode atau belum
					}
					
					/* ===============================calculate dp partial========================================================= */
					$vendor_dp = $this->m_vendors->get_saldo_by_id($vendor_code);
					$DP_Vendor = $vendor_dp[0]->SaldoDPBalance;

					if ($row_detail->Invoice_Owing == 0) {
						$DP_Vendor = $DP_Vendor - $row_detail->Invoice_Amount;
						$DPPartial = $DPPartial - $row_detail->Payment_Amount + $row_detail->Load_Rounding;
						$DPPartial = $DPPartial + $row_detail->Invoice_Amount;
					} else {
						$DP_Vendor = $DP_Vendor;
						$DPPartial = $DPPartial - $row_detail->Payment_Amount + $row_detail->Load_Rounding;
					}
					/* ========================end================================================================================= */

					/*
					  Update dp paid di vendor
					 */
					$data_vendor_dp = array(
						'SaldoDPBalance' => $DP_Vendor,
						'LockStatus' => 1,
						'SaldoDPPartial' => $DPPartial,
						'LastUser' => $this->session->userdata("username")
					);
					$this->transaction['update_vendor']['data'][] = $data_vendor_dp;
					$this->transaction['update_vendor']['VendorCode'][] = $vendor_code;
					$this->transaction['update_vendor']['BranchCode'][] = $cbg_branch;
					/* =================End============================================================== */
					
					/*
					  Update PO total payment DP
					 */
					$pord_totaldp = $this->m_purchase_order->get_ppay_total_dp($invoice_number);
					$new_ppay_totaldp = $pord_totaldp[0]->PPayTotalDP - ($total_amount + $row_detail->Load_Rounding);

					$data_po = array(
						'PPayTotalDP' => $new_ppay_totaldp,
						'TransStatus'   => 0,
						'LastUser' => $this->session->userdata("username")
					);
					
					$this->transaction['update_po']['data'][] = $data_po;
					$this->transaction['update_po']['InvoiceNumber'][] = $invoice_number;
					/* =================End============================================================== */
					
					$this->transaction['delete_dp']['PPayNumber'][] = $txt_ppay_no;
				}
				else if($row_detail->ItemCategoryID == -3){
					 /*
					  Update vendor outstanding fiscal
					 */
					$vendor_saldo = $this->m_vendors->get_saldo_by_id($vendor_code);
					$ppn_fiscal_debt = $vendor_saldo[0]->OutStandingFiscal + ($total_amount + $total_round);

					$data_vendor = array(
						'LockStatus' => 1,
						'OutStandingFiscal' => $ppn_fiscal_debt,
						'LastUser' => $this->session->userdata("username")
					);
					$this->transaction['update_vendor']['data'][] = $data_vendor;
					$this->transaction['update_vendor']['VendorCode'][] = $vendor_code;
					$this->transaction['update_vendor']['BranchCode'][] = $cbg_branch;
					
					$data_pi = array (			
						'TransStatus'   => 1,
						'LastUser' 		=> $this->session->userdata("username")
					);
					$this->transaction['update_pi']['data'][] = $data_pi;
					$this->transaction['update_pi']['InvoiceNumber'][] = $invoice_number;
					
					//$this->m_vendors->update($data_vendor, $vendor_code, $vendor_saldo[0]->BranchCode);
				}
				else if(($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 + $total_DP + $total_discount + $total_round);
					$saldodp_balance = $vendor_saldo[0]->SaldoDPBalance + $total_DP;

					$data_vendor = array(
						'OutStanding' => $saldo_balance,
						'SaldoDPBalance' => $saldodp_balance,
						'LockStatus' => 1,
						'LastUser' => $this->session->userdata("username")
					);
					$this->transaction['update_vendor']['data'][] = $data_vendor;
					$this->transaction['update_vendor']['VendorCode'][] = $vendor_code;
					$this->transaction['update_vendor']['BranchCode'][] = $cbg_branch;
					//$this->m_vendors->update($data_vendor, $vendor_code, $vendor_saldo[0]->BranchCode);
					
					/*
					  Update pordetail for status dp for
					  jika dp used dan dp balance tidak sama maka status dp for berubah jadi 1
					 */
					$status_dp_for = $this->m_purchase_payment->get_pordetail_dp_invoice_or_return($vendor_code, $Select_DP, 1);
					foreach ($status_dp_for as $row_dp_for) {
						$DPUsed 		= $row_dp_for->DPUsed;
						$SaldoDPBalance = $row_dp_for->SaldoDPBalance;
						$SOrdDetailDPID = $row_dp_for->POrdDetailDPID;
						$IsEdit 		= 1;

						$update_dp_for = array(
							'IsEdit' => $IsEdit
						);
						$this->transaction['update_dp']['data'][] = $update_dp_for;
						$this->transaction['update_dp']['VendorCode'][] = $vendor_code;
						$this->transaction['update_dp']['SOrdDetailDPID'][] = $SOrdDetailDPID;
						$this->transaction['update_dp']['Select_DP'][] = $Select_DP;
						//$this->m_purchase_payment->update_po_detail_dp_by_vendor($update_dp_for, $vendor_code, $SOrdDetailDPID, $Select_DP);
					}
					
					$data_pi = array (			
						'TransStatus'   => 1,
						'LastUser' 		=> $this->session->userdata("username")
					);
					$this->transaction['update_pi']['data'][] = $data_pi;
					$this->transaction['update_pi']['InvoiceNumber'][] = $invoice_number;
				}
				/*
				  Update Invoice Payment table
				 */
				$data_ppay_detail = $this->m_purchase_payment->get_ppay_detail($invoice_number, $txt_ppay_no);

				foreach ($data_ppay_detail as $row_detail) {
					$inv_payment_id 	= $row_detail->InvoicePaymentID;
					$payment_currency 	= $bank_curr_code == 'IDR' ? $row_detail->PPayCurrency : $row_detail->PPayCurrency * $bank_curr_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' 		=> $data_payment[0]->InvoiceOwing + ($row_detail->PPayDPUsed + $row_detail->PPayDiscount + $row_detail->PPayRounded + $row_detail->PPayAmount),
						'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 - $row_detail->PPayCurrency,
						//'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->transaction['update_payment']['data'][] = $payment_update;
					$this->transaction['update_payment']['InvoicePaymentID'][] = $inv_payment_id;
					//$this->m_purchase_payment->update_payment($payment_update, $inv_payment_id);
				}
				/* ==================End================================================================================================ */
			}
			
			//8. Update Approval Finished for update Journal
			$data_pp = array(
				'TransStatus' => 5,
				'AppLevel1Status' => 0,
				'AppLevel1Code' => NULL,
				'AppLevel1Date' => NULL,
				'AppFinished' => 0,
				'LastUser' => $this->session->userdata("username")
			);
			$this->transaction['update_data']['data'] = $data_pp;
			$this->transaction['update_data']['PPayNumber'] = $txt_ppay_no;
					
			//$this->m_purchase_payment->update($data_pp, $ppay_number);
			//-------------------------------------------------------------------------------------------------------------//
			if($hdn_pgir_number != ""){
				$data_pgir = array(
					'TransStatus' => 1,
					'LastUser' => $this->session->userdata("username")
				);
				$this->transaction['update_data_giro']['data'] = $data_pgir;
				$this->transaction['update_data_giro']['PGirNumber'] = $hdn_pgir_number;
			}
			
			$result_approve = $this->m_purchase_payment->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_ppay_no);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_ppay_no);
            }
             //==================================end====================================================== 
			echo json_encode($result);
		}
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
	}
	
    function to_preview($obj_string = null) {
//        $data['list'] = $this->m_purchase_payment->get_all2($this->ho);
        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
        
        $data_filter            = arrayParamInUrlToStr($obj_string);
		$data['branch_code'] = $data_filter['cmb_branch'];
		$data['company_code'] = $data_filter['cmb_company'];
        $data['list']           = $this->m_purchase_payment->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('purchase/purchase_payment/v_preview_purchase_payment', $data);
        $this->load->view('v_footer');
    }
    function to_preview_LAMA() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $data['list'] = $this->m_purchase_payment->get_all2($this->ho);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_payment/v_preview_purchase_payment', $data);
        $this->load->view('v_footer');
    }

    function to_print() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $data['list'] = $this->m_purchase_payment->get_all2($this->ho);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_payment/v_print_purchase_payment', $data);
        $this->load->view('v_footer');
    }

    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_payment->get_detail_print($id);

            $data['list'] = $this->m_purchase_payment->get_detail_invoice_print($data['detail']->PPayNumber);
            $this->load->view('v_header');
			if($data['detail']->PPnFiscalStatus == 1){
				$this->load->view('purchase/purchase_payment/v_print_detail_purchase_payment_fiscal', $data);
			}
			else{
				$this->load->view('purchase/purchase_payment/v_print_detail_purchase_payment', $data);
			}
            $this->load->view('v_footer');
        }
    }

    function to_preview_journal() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $id = str_replace($data['menu_link'] . '/to_preview_journal/', "", $this->uri->uri_string());

        $data['detail'] = $this->m_purchase_payment->get_detail($id);
        $data['list'] = $this->m_purchase_payment->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_payment/v_preview_journal_purchase_payment', $data);
        $this->load->view('v_footer');
    }

    function to_print_journal() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $id = str_replace($data['menu_link'] . '/to_print_journal/', "", $this->uri->uri_string());
        $data['detail'] = $this->m_purchase_payment->get_detail($id);
        $data['list'] = $this->m_purchase_payment->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_payment/v_print_journal_purchase_payment', $data);
        $this->load->view('v_footer');
    }

    public function ajax() {
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $hasil = array();
        /* ===========rows*page tidak boleh melebihi dari jumlah data======= */

        /* =================================post dari find di kiri==================================================== */
        $param = $this->input->post('param');
        $Number = isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : '';
        $Desc = isset($param['txt_Description']) ? $param['txt_Description'] : '';

        $DateFrom = isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
        $DateTo = isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
        $TransStatus = isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
        $BranchCode = isset($param['cmb_branch']) ? $param['cmb_branch'] : '';

        $VendorCode = isset($param['cmb_VendorCode']) ? $param['cmb_VendorCode'] : '';
        $PaymentStatus = isset($param['cmb_PaymentStatus']) ? $param['cmb_PaymentStatus'] : '';
        /* ============================================end============================================================ */
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if================= */
        if ($BranchCode != "") {
            $this->db->where('BranchCode', $BranchCode);
        } else {
            $this->db->where('BranchCode', $this->session->userdata('branch'));
        }

        if ($Number != "") {
            $this->db->like('PPayNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('PPayDesc', $Desc);
        }
        if ($VendorCode != "") {
            $this->db->like('VendorCode', $VendorCode);
        }
        if ($TransStatus != '') {
            $this->db->where_in('TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('TransStatus', array(0, 1, 4, 5, 6, 7));
        }

        if ($PaymentStatus == "All") {
            
        } else {
            $this->db->like('PaymentStatus', $PaymentStatus);
        }

        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('at_purchasepayment.PPayDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_purchasepayment.PPayDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_purchasepayment');
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_purchase_payment->get_all();

        for ($i = 0; $i <= ($rows - 1); $i++) {
            // kalau master ambil dari get_status_master(), kalau transaksi get_status()
            $TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(//change
                'BranchName' => $result[$i]->BranchName,
                'VendorName' => $result[$i]->VendorName,
                'TransNumber' => $result[$i]->PPayNumber,
                'PPayDate' => $result[$i]->PPayDate,
                'PPayDesc' => $result[$i]->PPayDesc,
                'PInvTotalAmount' => $result[$i]->PInvTotalAmount,
                'PPayTotalDPUsed' => $result[$i]->PPayTotalDPUsed,
                'PPayTotalAmount' => $result[$i]->PPayTotalAmount,
                'PPayTotalOwing' => $result[$i]->PPayTotalOwing,
                'PPayTotalDiscount' => $result[$i]->PPayTotalDiscount,
                'PaymentStatus' => $result[$i]->PaymentStatus,
				'BranchPaid' => $result[$i]->BranchPaid,
				'CreatedBy' => $result[$i]->CreatedBy,
                'TransStatus' => $TransStatus
            );
        }

        $result['total'] = $count_data;
        $result['rows'] = $hasil;
        echo json_encode($result);
    }

    public function ajax_item() {
        $vendor_code = $this->input->post('VendorCode');
        $ppn_fiscal_status = $this->input->post('PPnFiscalStatus');
		$PGirNumber = str_replace("_","-",$this->input->post('PGirNumber'));
		
		if($PGirNumber == ""){
			if (!empty($vendor_code)) {
				$result = $this->m_purchase_invoice->get_detail_item_for_pp($vendor_code, $ppn_fiscal_status);
				
				echo json_encode($result);
			} else {
				echo '[]';
			}
		}
		else{
			if (!empty($vendor_code)) {
				$result = $this->m_purchase_payment->get_detail_item_for_pgir($vendor_code, $ppn_fiscal_status, $PGirNumber);
				
				echo json_encode($result);
			} else {
				echo '[]';
			}
		}
        //echo $this->db->last_query();
    }

    public function ajax_item_for_edit() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $invoice_number = str_replace($data['menu_link'] . '/ajax_item_for_edit/', "", $this->uri->uri_string());

        if (!empty($invoice_number)) {
            $result = $this->m_purchase_payment->get_detail_invoice($invoice_number);
            echo json_encode($result);
        } else {
            echo '[]';
        }
    }

    public function get_pp_number() {
        $ppay_date = $this->input->post('PPay_Date') == '' ? date('d-m-Y') : $this->input->post('PPay_Date');
        $bankout_code = $this->input->post('Bank_Out_Code');

        if (!empty($bankout_code)) {
            $result['status'] = true;
            $result['number'] = $this->m_purchase_payment->create_pp_number($ppay_date, $bankout_code);
        } else {
            $result['status'] = false;
            $result['number'] = '';
        }

        echo json_encode($result);
    }

    public function ajax_bank_account() {
        $currency_code = $this->input->post('CurrencyCode');

        if (!empty($currency_code)) {
            echo json_encode($this->m_purchase_payment->get_bank_account($currency_code));
        }
//        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 get_pordetail_dp() {
        $VendorCode = $this->input->post('VendorCode');
        $CurrencyCode = $this->input->post('CurrencyCode');
        //$PordNumber 	= $this->input->post('POrdNumber');
        $PPayNumber = $this->input->post('PPayNumber');
        $BankCurrCode = $this->input->post('BankCurrCode');

        $Total_Balance = 0;
        $hasil = [];
        $Summing_Array = array();
        $result = $this->m_purchase_payment->get_saldo_detail_dp_update($VendorCode);

        foreach ($result as $row_detail_dp) {

            $get_detail = $this->m_purchase_payment->get_saldo_detail($row_detail_dp->POrdDetailDPID, $VendorCode, $PPayNumber);
            //echo $this->db->last_query();
            if ($CurrencyCode == 'IDR') {
                if (empty($get_detail->AmountCurrency)) {
                    $DPUsed = 0;
                } else {
                    $DPUsed = $BankCurrCode == 'IDR' ? $get_detail->AmountCurrency : $get_detail->PPaySaldoCredit;
                }
            } else {
                if (empty($get_detail->AmountCurrency)) {
                    $DPUsed = 0;
                } else {
                    $DPUsed = $BankCurrCode == 'IDR' ? $get_detail->AmountCurrency : $get_detail->AmountCurrency;
                }
            }

            //echo 'DP SUM = '.$row_detail_dp->PaymentAmount_SUM;
            $Total_Balance = $row_detail_dp->PaymentAmount_SUM + $DPUsed;
            @$Summing_Array[$row_detail_dp->POrdNumber] += $Total_Balance;
        }

        //print_r($Summing_Array);
        foreach ($Summing_Array as $key => $value) {
            $hasil[] = array(
                'Status' => 'No',
                'POrdNumber' => $key,
                'PaymentAmount_SUM' => $value
            );
        }
        $result['rows'] = $hasil;
        echo json_encode($result);
    }

    function get_pordetail_dp_new() {
        $VendorCode = $this->input->post('VendorCode');
        //$CurrencyCode 	= $this->input->post('CurrencyCode');
        //$PordNumber 	= $this->input->post('POrdNumber');
        $result = $this->m_purchase_payment->get_saldo_detail_dp_new($VendorCode);
        echo json_encode($result);
    }

    function get_pordetail_dp_return() {
        $VendorCode = $this->input->post('vendor_code');
        $data_dp_payment = $this->m_purchase_payment->get_pordetail_dp_balance($VendorCode);

        $result['dp_vendor'] = $data_dp_payment->DownPayment;
        echo json_encode($result);
    }

    function get_pordetail_dp_invoice() {
        $VendorCode = $this->input->post('vendor_code');
        $data_dp = $this->m_purchase_payment->get_pordetail_dp_balance_invoice($VendorCode);
        $result['status'] = true;
        $result['dp_vendor_invoice'] = $data_dp->DownPayment;

        echo json_encode($result);
    }

}
