<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Ferry / Tanggal : 15-01-2015
  Revisi 	: Fachri Nugraha
 */

class Purchases_invoice extends CI_Controller {

    public $menu_id = 170;
    public $menu_model = array('m_receive_item', 'm_purchase_order', 'm_purchase_invoice',
        'm_vendors', 'm_taxes', 'm_account_journal', 'm_currency', 'm_employee', 'm_purchase_payment');
    public $name = "Purchase Invoice";
    public $jobtitle_status = array('0', '1');
    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('lables');
        $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();
                    $data['lables'] = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

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

    public function add($POrdNumber = '', $VendorCode = '') {
        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);
                    $data['POrdNumber'] = $POrdNumber;
                    $data['VendorCode'] = $VendorCode;

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
                    $data['taxes_ppn10'] = $this->m_taxes->get_by_code('PPN');
                    $data['taxes_pph22'] = $this->m_taxes->get_by_code('PPH22');
                    $data['taxes_pph23'] = $this->m_taxes->get_by_code('PPH23-1');

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

    public function insert() {
        /* ==================Deklar variabel array=================================== */
        $CategoryCodeAmount = array();
        $CategoryCodeType = array();

        $CategoryCodeAmount_Exp = array();
        $CategoryCodeType_Exp = array();

        $CategoryIDPPh22 = array();
        $CategoryIDPPh23 = array();
        $CategoryIDAmt = array();
        $CategoryIDCode = array();
        $CategoryIDName = array();
        $CategoryIDType = array();
        $CategoryIDAsset = array();
        $CategoryIDPPn10 = array();
        $CategoryDisc = array();
        $CategoryDPAmount = array();
        /* ==================End================================================== */

        /* ===================Deklar variabel post=============================================== */
        $branch_code = $this->session->userdata('branch');
        $vendor_code = $this->input->post('cbg_vendor');
        $vendor_address = $this->input->post('txa_address');

        $pinv_date = $this->input->post('txt_pinv_date');
        $prec_date = $this->input->post('txt_prec_date');
        $pinv_number = $this->m_purchase_invoice->create_pi_number($pinv_date);
        $prec_number = $this->input->post('txt_prec_no');
        $pord_number = $this->input->post('hdn_pord_no');
        $vend_inv_number = $this->input->post('txt_vendor_inv_no');

        $fob_id = $this->input->post('cbo_fob') == "" ? null : $this->input->post('cbo_fob');
        $terms_id = $this->input->post('cbo_terms') == "" ? null : $this->input->post('cbo_terms');
        $shipment_id = $this->input->post('cbo_ship_via') == "" ? null : $this->input->post('cbo_ship_via');
        $shipment_date = $this->input->post('txt_shipment_date');
        $description = $this->input->post('txa_description');

        $currency_code = $this->input->post('hdn_currency_code');
        $currency_rate = $this->input->post('txt_currency_rate');
        $fiscal_rate = $this->input->post('txt_fiscal_rate');
        $taxes_status = $this->input->post('hdn_taxes_status');
        $intax_status = $this->input->post('hdn_intax_status');

        $pinv_ppn10_val = $this->input->post('txt_ppn10_hide');
        $pinv_pph22_val = $this->input->post('txt_pph22_hide');
        $pinv_pph23_val = $this->input->post('txt_pph23_hide');

        $pinv_ppn10_val_real = $this->input->post('txt_ppn10');
        $pinv_pph22_val_real = $this->input->post('txt_pph22');
        $pinv_pph23_val_real = $this->input->post('txt_pph23');

        $pinv_ppn10_pcnt = $pinv_ppn10_val == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');
        $pinv_pph22_pcnt = $pinv_pph22_val == 0 ? 0 : $this->input->post('hdn_pph22_pcnt');
        $pinv_pph23_pcnt = $pinv_pph23_val == 0 ? 0 : $this->input->post('hdn_pph23_pcnt');

        $pinv_sub_total = $this->input->post('txt_sub_total_hide');
        $pinv_sub_total_real = $this->input->post('txt_sub_total');
        $pinv_discount = $this->input->post('txt_discount_hide');
        $pinv_est_freight = $this->input->post('txt_freight');
        $pinv_total_purchase = $this->input->post('txt_total_purchase_hide');
        $pinv_total_dp = $this->input->post('txt_total_dp');
        $pinv_total_invoice = $this->input->post('txt_total_invoice_hide');
        $hdn_pord_no = $this->input->post('hdn_pord_no');
        /* ======================End================================================================== */

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

        if (count($detail) > 0) {
            $this->db->trans_begin();
            $item_value = 0;
            $item_category = '';
            $item_category_code = '';

            $get_po_number_on_pi = $this->m_purchase_invoice->check_code_exist_pord_number($hdn_pord_no);
            if (!empty($get_po_number_on_pi->POrdNumber)) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = "Transaski gagal, No Purchase Order " . $get_po_number_on_pi->POrdNumber . " sudah tersedia di Purchase Invoice";
                echo json_encode($result);
                die();
            }

            $data = array(
                'BranchCode' => $branch_code,
                'VendorCode' => $vendor_code,
                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                'PInvNumber' => $pinv_number,
                'PRecDate' => $prec_date,
                'PRecNumber' => $prec_number,
                'POrdNumber' => $pord_number,
                'VendInvNumber' => $vend_inv_number,
                'ShipmentDate' => date("Y-m-d", strtotime($shipment_date)),
                'ShipmentID' => $shipment_id,
                'TermsPaymentID' => $terms_id,
                'FOBID' => $fob_id,
                'VendorAddress' => $vendor_address,
                'CurrencyCode' => $currency_code,
                'CurrencyRate' => $currency_rate,
                'FiscalRate' => $fiscal_rate,
                'PInvDesc' => $description,
                'PInvSubTotal' => $pinv_sub_total,
                'PInvDiscount' => $pinv_discount,
                'PInvPPn10Pcnt' => $pinv_ppn10_pcnt,
                'PInvPPh22Pcnt' => $pinv_pph22_pcnt,
                'PInvPPh23Pcnt' => $pinv_pph23_pcnt,
                'PInvPPn10' => $pinv_ppn10_val,
                'PInvPPh22' => $pinv_pph22_val,
                'PInvPPh23' => $pinv_pph23_val,
                'PInvEstFreight' => $pinv_est_freight,
                'PInvTotalAmount' => $pinv_total_purchase,
                'PInvTotalDP' => $pinv_total_dp,
                'PInvTotalInvoice' => $pinv_total_invoice,
                'PPayTotalAmount' => 0,
                'PInvTotalOwing' => $pinv_total_invoice,
                'PInvTaxesStatus' => $taxes_status,
                'PInvInTaxStatus' => $intax_status,
                'TransStatus' => 4,
                'CreatedBy' => $this->session->userdata("username"),
                'CreatedAt' => date('Y-m-d'),
                'LastUser' => $this->session->userdata("username")
            );

            //1. insert into table Purhcase Invoice
            $this->m_purchase_invoice->insert($data);

            foreach ($detail as $row) {
                $detail_data = array(
                    'PRecNumber' => $row->PRecNumber,
                    'PInvNumber' => $pinv_number,
                    'ItemCode' => $row->ItemCode,
                    'ItemDesc' => $row->ItemDesc,
                    'itemUnit' => $row->ItemUnit,
                    'itemQty' => $row->ItemQty,
                    'ItemPrice' => $row->ItemPrice,
                    'ItemDisc' => $row->ItemDisc,
                    'ItemAmount' => $row->ItemAmount_Hide,
                    'ItemTaxPPn10' => $row->ItemTaxPPn10,
                    'ItemTaxPPh22' => $row->ItemTaxPPh22,
                    'ItemTaxPPh23' => $row->ItemTaxPPh23,
                    'ItemTotalAmount' => $row->ItemTotalAmount,
                    'ItemCategoryID' => $row->ItemCategoryID,
                    'ItemCategoryCode' => $row->ItemCategoryCode,
                    'ItemType' => $row->ItemType,
                    'ItemStatus' => $row->ItemStatus,
                    'ItemPPh22Status' => $row->ItemPPh22Status,
                    'ItemPPh23Status' => $row->ItemPPh23Status,
                    'ItemAdvNetDueIn' => $row->ItemAdvNetDueIn,
                    'ItemPriceNTax' => $row->ItemPriceNTax,
					'ItemCodeVendor' => $row->ItemCodeVendor,
                    'LastUser' => $this->session->userdata("username")
                );

                //2. insert into Purchase Invoice Detail (PInvDetail)
                $this->m_purchase_invoice->insert_detail($detail_data);

                @$CategoryCodeAmount[$row->ItemCategoryID] += $row->ItemAmount_Hide;
                @$CategoryCodeType[$row->ItemCategoryID] = $row->ItemType;

                @$CategoryCodeAmount_Exp[$row->ItemCategoryCode] += $row->ItemAmount_Hide;
                @$CategoryCodeType_Exp[$row->ItemCategoryCode] = $row->ItemType;

                @$CategoryIDPPh22[$row->ItemCategoryID] += $row->ItemTaxPPh22;
                @$CategoryIDPPh23[$row->ItemCategoryID] += $row->ItemTaxPPh23;
                @$CategoryIDPPn10[$row->ItemCategoryID] += $row->ItemTaxPPn10;

                @$CategoryIDAmt[$row->ItemCategoryID] += $row->ItemAmount_Hide;
                @$CategoryIDCode[$row->ItemCategoryID] += $row->ItemCategoryID;
                @$CategoryDisc[$row->ItemCategoryID] += $row->AmountDisc;
                @$CategoryIDName[$row->ItemCategoryID] = $row->ItemCategoryCode;
                @$CategoryIDType[$row->ItemCategoryID] = $row->ItemType;
                @$CategoryIDAsset[$row->ItemCategoryID] = $row->ItemStatus;
                @$CategoryDPAmount[$row->ItemCategoryID] += $row->ItemAmount_Hide;

                if ($row->ItemType == 0) {
                    $item_category_code = $row->ItemCategoryCode;
                }
            }
            //---------------------------------------------------------------------------------------------------------------//                
            //3. Update Receive Item for status lock = 1
            $prec_number = explode(",", $prec_number);

            foreach ($prec_number as $key => $value) {
                $data_ri = array(
                    'LockedStatus' => 1,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_receive_item->update($data_ri, $value);
            }
            //---------------------------------------------------------------------------------------------------------------//

            $this->insert_journal($pinv_ppn10_val_real, $pinv_pph22_val_real, $pinv_pph23_val_real, $pinv_sub_total_real, $pinv_total_invoice, $pinv_total_purchase, $pord_number, $vendor_code, $fiscal_rate, $pinv_sub_total, $pinv_pph23_val, $pinv_total_dp, $pinv_discount, $taxes_status, $pinv_ppn10_pcnt, $pinv_pph22_val, $pinv_ppn10_val, $pinv_est_freight, $item_category_code, $item_category, $CategoryCodeAmount, $CategoryCodeType, $CategoryIDPPh22, $CategoryIDPPh23, $CategoryIDAmt, $CategoryIDCode, $CategoryIDName, $CategoryIDType, $CategoryIDAsset, $pinv_date, $pinv_number, $description, $currency_rate, $currency_code, $CategoryIDPPn10, $CategoryDisc, $CategoryCodeAmount_Exp, $CategoryCodeType_Exp, $CategoryDPAmount);

            /* =============================trans roll back dan trans commit============================/ */
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $pinv_number);

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

        echo json_encode($result);
        die();
    }

    function insert_journal($pinv_ppn10_val_real, $pinv_pph22_val_real, $pinv_pph23_val_real, $pinv_sub_total_real, $pinv_total_invoice, $pinv_total_purchase, $pord_number, $vendor_code, $fiscal_rate, $pinv_sub_total, $pinv_pph23_val, $pinv_total_dp, $pinv_discount, $taxes_status, $pinv_ppn10_pcnt, $pinv_pph22_val, $pinv_ppn10_val, $pinv_est_freight, $item_category_code, $item_category, $CategoryCodeAmount, $CategoryCodeType, $CategoryIDPPh22, $CategoryIDPPh23, $CategoryIDAmt, $CategoryIDCode, $CategoryIDName, $CategoryIDType, $CategoryIDAsset, $pinv_date, $pinv_number, $description, $currency_rate, $currency_code, $CategoryIDPPn10, $CategoryDisc, $CategoryCodeAmount_Exp, $CategoryCodeType_Exp, $CategoryDPAmount) {
        $item_value = 0;
        /* ===============================Journal Account Preference============================================================== */
        if ($item_category_code != '') {
            $UnbilledAccount = $this->m_account_journal->get_sys_item_account('Unbilled'); // Hutang Dagang Yang Belum DiTagih
            if ($UnbilledAccount == false) {
                $this->trans_rollback('preference', 'Item Account -> Unbilled Account (Owing)', '');
            }
        }
        /* ============================================================End======================================================== */

        /* ==============4. Insert Journal UnBilled Account - Hutang Dagang Yang Belum DiTagih==================================== */
        if ($item_category_code != '') {
            foreach ($CategoryCodeAmount as $key => $value) {
                if ($CategoryCodeType[$key] == 0) {
                    $item_value += $value;
                    $item_category = $item_category . $key . ', ';
                }
            }


            if ($item_category != '') {
                $item_category = substr($item_category, 0, (intval(strlen($item_category)) - 2));
            }

            $unbilled_value = $currency_code == 'IDR' ? doubleval($item_value) : doubleval($item_value) * $currency_rate;
            $unbilled_currency = doubleval($item_value);

            $journal_unbilled = array(
                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                'PInvNumber' => $pinv_number,
                'PInvAccountNumber' => $UnbilledAccount->AccountNumber,
                'PInvSaldoDebet' => $unbilled_value,
                'PInvSaldoCredit' => 0,
                'AmountCurrency' => $unbilled_currency,
                'PInvSignStatus' => 1,
                'PInvDesc' => $description,
                'ItemCategoryCode' => $item_category,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_invoice->insert_journal($journal_unbilled);
        }
        /* ====================End============================================================================================== */

        //5. Insert Journal Jasa / Adv. Payment Account - Biaya Jasa atau Biaya DiBayar DiMuka

        foreach ($CategoryCodeAmount as $key => $value) {
            if ($CategoryCodeType[$key] != 0) {
                if ($CategoryCodeType[$key] == 1) {
                    $ExpenseAccount = $this->m_account_journal->get_sys_service_account('Expense', 'IDR', $key); // Jasa / Service
                    if ($ExpenseAccount == false) {
                        $this->trans_rollback('preference', 'Expense Account -> Purchase Expense', '');
                    }
                } else {
                    $ExpenseAccount = $this->m_account_journal->get_sys_advance_account('Advance', 'IDR', $key); // Adv. Payment
                    if ($ExpenseAccount == false) {
                        $this->trans_rollback('preference', 'Adv Payment Account -> Purchase Expense', '');
                    }
                }
                $expense_value = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
                $expense_currency = doubleval($value);

                $journal_expense = array(
                    'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                    'PInvNumber' => $pinv_number,
                    'PInvAccountNumber' => $ExpenseAccount->AccountNumber,
                    'PInvSaldoDebet' => $expense_value,
                    'PInvSaldoCredit' => 0,
                    'AmountCurrency' => $expense_currency,
                    'PInvSignStatus' => 0,
                    'PInvDesc' => $description,
                    'ItemCategoryCode' => $ExpenseAccount->AccountName,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_invoice->insert_journal($journal_expense);
            }
        }
        //---------------------------------------------------------------------------------------------------------------//

        /* ===========6. Insert Journal Frieght - Debet jika besar dari 0 dan Credit jika kecil dari 0 ======================== */
        if ($pinv_est_freight != 0) {
            $PurchaseFreight = $this->m_account_journal->get_sys_purchase_account('PurchaseFreight', 'IDR'); // Extimate Freight
			if ($PurchaseFreight == false) {
				$this->trans_rollback('preference', 'Purchase Account -> Purchase Freight', '');
			}
		
			if ($pinv_est_freight > 0) {
                $freight_debet = $currency_code == 'IDR' ? $pinv_est_freight : doubleval($pinv_est_freight) * $currency_rate;
                $freight_credit = 0;
                $Sign_Status = 0;
            } else {
                $freight_debet = 0;
                $freight_credit = $currency_code == 'IDR' ? abs($pinv_est_freight) : doubleval(abs($pinv_est_freight)) * $currency_rate;
                $Sign_Status = 1;
            }

            $freight_currency = $pinv_est_freight;

            $journal_freight = array(
                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                'PInvNumber' => $pinv_number,
                'PInvAccountNumber' => $PurchaseFreight->AccountNumber,
                'PInvSaldoDebet' => $freight_debet,
                'PInvSaldoCredit' => $freight_credit,
                'AmountCurrency' => $freight_currency,
                'PInvSignStatus' => $Sign_Status,
                'PInvDesc' => $description,
                'ItemCategoryCode' => $PurchaseFreight->AccountName,
                'LastUser' => $this->session->userdata("username")
            );

            if ($pinv_est_freight > 0) {
                $this->m_purchase_invoice->insert_journal($journal_freight);
            }
        }
        /* ====================End===================================================================================== */

        /* ================7. Insert Journal PPn Masukan pada Debet ==================================================== */
        $taxppn_value = 0;
        $tax_currency = 0;

        if ($pinv_ppn10_val > 0) {
            if ($currency_code == 'IDR') {
                foreach ($CategoryIDPPn10 as $key => $value) {
                    if ($CategoryIDType[$key] == 0) {
                        $PPnAccount = $this->m_account_journal->get_sys_purchase_account('PurchaseTaxable', 'IDR'); // PPn Masukan
                        if ($PPnAccount == false) {
                            $this->trans_rollback('preference', 'Purchase Account -> Purchase Taxable', '');
                        }
                    } else {
                        if ($CategoryIDType[$key] == 1) {
                            $PPnAccount = $this->m_account_journal->get_sys_service_account('PurchaseTaxable', 'IDR'); // Jasa / Service
                            if ($PPnAccount == false) {
                                $this->trans_rollback('preference', 'Expense Account -> Purchase Taxable PPn 10', '');
                            }
                        } else {
                            $PPnAccount = $this->m_account_journal->get_sys_advance_account('PurchaseTaxable', 'IDR'); // Adv
                            if ($PPnAccount == false) {
                                $this->trans_rollback('preference', 'Adv Purchase Account -> Taxable Ppn 10', '');
                            }
                        }
                    }

                    $taxppn_value = $currency_code == 'IDR' ? $value : doubleval($value) * $fiscal_rate;
                    $ppn_fiscal = $currency_code == 'IDR' ? 0 : 1;
                    $tax_currency = $value;

                    $journal_taxppn10 = array(
                        'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                        'PInvNumber' => $pinv_number,
                        'PInvDesc' => $description,
                        'PInvAccountNumber' => $PPnAccount->AccountNumber,
                        'PInvSaldoDebet' => $taxppn_value,
                        'PInvSaldoCredit' => 0,
                        'AmountCurrency' => $tax_currency,
                        'PInvSignStatus' => 0,
                        'PInvPPnFiscal' => $ppn_fiscal,
                        'ItemCategoryCode' => $PPnAccount->AccountName,
                        'LastUser' => $this->session->userdata("username")
                    );


                    $get_journal_purchase_invoice = $this->m_purchase_invoice->get_journal_purchase_invoice($PPnAccount->AccountNumber, $pinv_number);

                    if (empty($get_journal_purchase_invoice->PInvAccountNumber)) {
                        $this->m_purchase_invoice->insert_journal($journal_taxppn10);
                    } else {
                        $taxppn_value = $taxppn_value + $get_journal_purchase_invoice->PInvSaldoDebet;
                        $tax_currency = $tax_currency + $get_journal_purchase_invoice->AmountCurrency;

                        $journal_update_ppn = array(
                            'PInvSaldoDebet' => $taxppn_value,
                            'PInvSaldoCredit' => 0,
                            'AmountCurrency' => $tax_currency
                        );
                        $this->m_purchase_invoice->update_journal($pinv_number, $journal_update_ppn, $get_journal_purchase_invoice->PInvAccountNumber);
                    }
                }
            }
        }
        /* =======================End============================================================================ */



        //8. Insert Journal PPh22 Import pada Debet                    
        if (($pinv_pph22_val > 0)) {
            $taxpph22_value = 0;
            $taxpph22_currency = 0;


            foreach ($CategoryIDPPh22 as $key => $value) {
                if ($CategoryIDType[$key] == 0) {
                    $PPh22Account = $this->m_account_journal->get_cat_item_account('TaxablePPH22', $key, 'IDR'); // PPn Import
                    if ($PPh22Account == false) {
                        $this->trans_rollback('preference', 'Item Account -> Taxable PPh 22', '');
                    }

                    $get_journal_purchase_invoice = $this->m_purchase_invoice->get_journal_purchase_invoice($PPh22Account->AccountNumber, $pinv_number);

                    $taxpph22_value = $currency_code == 'IDR' ? $value : doubleval($value) * $currency_rate;
                    $taxpph22_currency = $value;

                    if (empty($get_journal_purchase_invoice->PInvAccountNumber)) {
                        $journal_taxpph22 = array(
                            'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                            'PInvNumber' => $pinv_number,
                            'PInvAccountNumber' => $PPh22Account->AccountNumber,
                            'PInvSaldoDebet' => $taxpph22_value,
                            'PInvSaldoCredit' => 0,
                            'AmountCurrency' => $taxpph22_currency,
                            'PInvSignStatus' => 0,
                            'PInvDesc' => $description,
                            'ItemCategoryCode' => $key,
                            'LastUser' => $this->session->userdata("username")
                        );

                        if ($value > 0) {
                            $this->m_purchase_invoice->insert_journal($journal_taxpph22);
                        }
                    } else {
                        $taxpph22_value = $taxpph22_value + $get_journal_purchase_invoice->PInvSaldoDebet;
                        $taxpph22_currency = $taxpph22_currency + $get_journal_purchase_invoice->AmountCurrency;

                        $journal_taxpph22 = array(
                            'PInvSaldoDebet' => $taxpph22_value,
                            'PInvSaldoCredit' => 0,
                            'AmountCurrency' => $taxpph22_currency
                        );
                        if ($value > 0) {
                            $this->m_purchase_invoice->update_journal($pinv_number, $journal_taxpph22, $get_journal_purchase_invoice->PInvAccountNumber);
                        }
                    }
                }
            }
        }
        //---------------------------------------------------------------------------------------------------------//
        //9. Insert Journal Payable Acount pada Debet - Hutang Dagang
        $total_records = count($CategoryIDAmt);
        $total_loop = 0;
        $total_ratio = 0;
        $freight_ratio = 0;

        $total_dp_type = 0;
        $cat_item_type = -99;
        $cat_item_asset = -99;
        $cat_item_catid = -99;

        $category_code = '';
        $curr_account_no = '';
        $payable_val_cat = 0;
        $payable_value = 0;
        $payable_currency = 0;
        $advance_value = 0;
        $advance_currency = 0;
        $invoice_ratio = 0;

        $total_dp_array = array();
        $cat_id_array = array();
        $total_discount = array();
        $total_ppay_realizedgl = 0;

        foreach ($CategoryIDAmt as $key => $value) {
            $total_loop++;

            if ($total_loop == $total_records) {
                $item_ratio = 100 - $total_ratio;
            } else {
                $item_ratio = floor(abs((doubleval($value) / $pinv_sub_total) * 100));
            }
            $total_ratio = $total_ratio + $item_ratio;


            //$item_pph22     = $CategoryIDPPh22[$key];
            //$item_pph23     = $CategoryIDPPh23[$key];
            //$item_ppn10 	= $CategoryIDPPn10[$key];
            $invoice_ratio_real = $pinv_sub_total_real * ($item_ratio / 100);
            $ppn_ratio_real = $pinv_ppn10_val_real * ($item_ratio / 100);
            $pph22_ratio_real = $pinv_pph22_val_real * ($item_ratio / 100);
            $pph23_ratio_real = $pinv_pph23_val_real * ($item_ratio / 100);
            $item_ppn_real = ($currency_code == 'IDR' && $taxes_status == 1) ? (doubleval($ppn_ratio_real)) : 0;

            $invoice_ratio = $pinv_sub_total * ($item_ratio / 100);
            $ppn_ratio = $pinv_ppn10_val * ($item_ratio / 100);
            $pph23_ratio = $pinv_pph23_val * ($item_ratio / 100);
            $pph22_ratio = $pinv_pph22_val * ($item_ratio / 100);

            $discount_ratio = $pinv_discount * ($item_ratio / 100);
            $freight_ratio = $pinv_est_freight * ($item_ratio / 100);
            $dp_ratio = $pinv_total_dp * ($item_ratio / 100);

            $item_ppn = ($currency_code == 'IDR' && $taxes_status == 1) ? (doubleval($ppn_ratio)) : 0;

            $amount_ratio = doubleval($invoice_ratio) + doubleval($item_ppn) + doubleval($pph22_ratio) - doubleval($pph23_ratio) + doubleval($freight_ratio) - doubleval($dp_ratio);
            $amount_ratio_real = doubleval($invoice_ratio_real) + doubleval($item_ppn_real) + doubleval($pph22_ratio_real) - doubleval($pph23_ratio_real) + doubleval($freight_ratio) - doubleval($dp_ratio);

            if ($currency_code == 'IDR') {
                $inv_cat_curr_amount = 0;
                $pay_cat_curr_amount = 0;
            } else {
                $inv_cat_curr_amount = doubleval($pph22_ratio) - doubleval($pph23_ratio) * $currency_rate;
                $pay_cat_curr_amount = doubleval($pph22_ratio) - doubleval($pph23_ratio) * $fiscal_rate;
            }

            $pinv_cat_realizedgl = $pay_cat_curr_amount - $inv_cat_curr_amount;

            //echo doubleval($invoice_ratio) .'+'. doubleval($item_ppn) .'+'. doubleval($pph22_ratio) .'-'. doubleval($pph23_ratio) .'+'. doubleval($freight_ratio) .'-'. doubleval($dp_ratio).' = ';
            if ($CategoryIDType[$key] == 0) {
                $PayableAccount = $this->m_account_journal->get_cat_purchase_account('Payable', $key, $currency_code); // Hutang Dagang
                if ($currency_code == 'IDR') {
                    if ($PayableAccount == false) {
                        $this->trans_rollback('preference', 'Purchase Account -> Account Payable', '');
                    }
                } else {
                    if ($PayableAccount == false) {
                        $this->trans_rollback('journal', 'Hutang Dagang / Hutang Aktiva', $currency_code);
                    }
                }
                $category_name = 'Hutang Dagang';
            } else {
                if ($CategoryIDType[$key] == 1) {
                    $PayableAccount = $this->m_account_journal->get_sys_service_account('Unbilled', $currency_code, $key); // PPh Jasa / Service                

                    if ($currency_code == 'IDR') {
                        if ($PayableAccount == false) {
                            $this->trans_rollback('preference', 'Expense Account -> Purchase Unbilled (Owing)', '');
                        }
                    } else {
                        if ($PayableAccount == false) {
                            $this->trans_rollback('journal', 'Hutang Expebse', $currency_code);
                        }
                    }

                    $category_name = 'Hutang Expense';
                } else {
                    $PayableAccount = $this->m_account_journal->get_sys_advance_account('Unbilled', $currency_code, $key); // Adv. Payment
                    if ($currency_code == 'IDR') {
                        if ($PayableAccount == false) {
                            $this->trans_rollback('preference', 'Adv Purchase Account -> Unbilled (Owing)', '');
                        }
                    } else {
                        if ($PayableAccount == false) {
                            $this->trans_rollback('journal', 'Hutang Advanced Payment', $currency_code);
                        }
                    }
                    $category_name = 'Hutang Advance';
                }
            }

            if ($total_loop == 1) {
                $curr_account_no = $PayableAccount->AccountNumber;
            }
            if ($pinv_discount > 0) {
                array_push($total_discount, $discount_ratio);
            }

            $payable_value = $currency_code == 'IDR' ? $amount_ratio : $amount_ratio * $currency_rate;
            $payable_currency = $amount_ratio;

            $get_journal_purchase_invoice = $this->m_purchase_invoice->get_journal_purchase_invoice($PayableAccount->AccountNumber, $pinv_number);
            if (empty($get_journal_purchase_invoice->PInvAccountNumber)) {
                $journal_purchase = array(
                    'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                    'PInvNumber' => $pinv_number,
                    'PInvDesc' => $description,
                    'PInvAccountNumber' => $PayableAccount->AccountNumber,
                    'PInvSaldoDebet' => 0,
                    'PInvSaldoCredit' => $payable_value,
                    'AmountCurrency' => $payable_currency,
                    'PInvSignStatus' => 0,
                    'PInvPPnFiscal' => 0,
                    'ItemCategoryCode' => $category_name,
                    'LastUser' => $this->session->userdata("username")
                );

                if ($amount_ratio_real > 0) {
                    $this->m_purchase_invoice->insert_journal($journal_purchase);
                }
            } else {
                $payable_value = $payable_value + $get_journal_purchase_invoice->PInvSaldoCredit;
                $payable_currency = $payable_currency + $get_journal_purchase_invoice->AmountCurrency;

                $journal_purchase = array(
                    'PInvSaldoDebet' => 0,
                    'PInvSaldoCredit' => $payable_value,
                    'AmountCurrency' => $payable_currency
                );
                if ($amount_ratio_real > 0) {
                    $this->m_purchase_invoice->update_journal($pinv_number, $journal_purchase, $get_journal_purchase_invoice->PInvAccountNumber);
                }
            }
            //----------------------------------------------------------------------------------------------------------//
            //$total_ppay_realizedgl += $pinv_cat_realizedgl;
            @$Total_hutang += $amount_ratio;
        }
        //---------------------------------------------------------------------------------------------------------------//

        /*
          Jurnal Down Payment
         */
        if ($pinv_total_dp > 0) {

            /* ===================Get Pordetail DP========================================== */
            if ($currency_code == 'IDR') {
                if ($pinv_total_dp > $pinv_total_purchase) {
                    $saldo_dp = doubleval($pinv_total_purchase);
                    $saldo_dp_new = doubleval($pinv_total_purchase);
                    $sordetail_dp = $this->m_purchase_payment->get_saldo_detail_dp($vendor_code, $pord_number, 5);
                } else {
                    $saldo_dp = doubleval($pinv_total_dp);
                    $saldo_dp_new = doubleval($pinv_total_dp);
                    $sordetail_dp = $this->m_purchase_payment->get_saldo_detail_dp($vendor_code, $pord_number, 1);
                }
            } else {
                if ($pinv_ppn10_val > 0) {
                    $Total_Purchase = doubleval($pinv_total_purchase - $pinv_ppn10_val);
                    if ($Total_Purchase > $pinv_total_dp) {
                        $saldo_dp = doubleval($pinv_total_dp);
                        $saldo_dp_new = doubleval($pinv_total_dp);
                        $sordetail_dp = $this->m_purchase_payment->get_saldo_detail_dp($vendor_code, $pord_number, 1);
                    } else {
                        $saldo_dp = $Total_Purchase;
                        $saldo_dp_new = $Total_Purchase;
                        $sordetail_dp = $this->m_purchase_payment->get_saldo_detail_dp($vendor_code, $pord_number, 5);
                    }
                } else {
                    if ($pinv_total_dp > $pinv_total_purchase) {
                        $saldo_dp = doubleval($pinv_total_purchase);
                        $saldo_dp_new = doubleval($pinv_total_purchase);
                        $sordetail_dp = $this->m_purchase_payment->get_saldo_detail_dp($vendor_code, $pord_number, 5);
                    } else {
                        $saldo_dp = doubleval($pinv_total_dp);
                        $saldo_dp_new = doubleval($pinv_total_dp);
                        $sordetail_dp = $this->m_purchase_payment->get_saldo_detail_dp($vendor_code, $pord_number, 1);
                    }
                }
            }

            $jurnal_dp = 0;
            $jurnal_dp_currency = 0;
            $jurnal_dp_no_currency = 0;
            $currency_rate_detail = 0;
            $is_edit = "";
            $PaymentBefore = 0;
            $PaymentBefore_Sum = 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;

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

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

                        if ($saldo_dp < 0) {

                            $dp_used_old = $DPUsed;
                            $dp_used_book = doubleval($DPUsed + ($saldo_dp_new - $PaymentBefore_Sum));
                            //$dp_used_book 	= $saldo_balance_detail + $saldo_dp;
                            $jurnal_dp = (doubleval($dp_used_book * $currency_rate_detail));
                            $jurnal_dp_currency = (doubleval($dp_used_book / $currency_rate_detail));
                            $jurnal_dp_no_currency = doubleval($dp_used_book);
                            $update_sordetail = array(
                                'DPUsed' => $dp_used_book
                            );
                            $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_sordetail, $vendor_code, $SOrdDetailDPID, $pord_number);

                            $DPAccount = $this->m_account_journal->get_sys_purchase_account('AdvancePurchase', $currency_code); // Uang Muka Category -> 1-4-03-001-00
                            if ($DPAccount == false) {
                                $this->trans_rollback('journal', 'Uang Muka Pembelian', '');
                            }
                            $advance_value = doubleval($jurnal_dp);
                            $advance_currency = doubleval($jurnal_dp_no_currency);

                            $journal_advance = array(
                                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                                'PInvNumber' => $pinv_number,
                                'PInvAccountNumber' => $DPAccount->AccountNumber,
                                'PInvSaldoDebet' => 0,
                                'PInvSaldoCredit' => doubleval($advance_value),
                                'AmountCurrency' => doubleval($advance_currency),
                                'PInvSignStatus' => 1,
                                'PInvDesc' => $description,
                                'ItemCategoryCode' => $category_name,
                                'POrdDetailDPID' => $row_detail_dp->POrdDetailDPID,
                                'LastUser' => $this->session->userdata("username")
                            );

                            $this->m_purchase_invoice->insert_journal($journal_advance);

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

                                    $realized_amount = abs($inv_dp_selisih_kurs);
                                    $realized_currency = $currency_code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $currency_rate;

                                    $journal_RealizedAccount = array(
                                        'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                                        'PInvNumber' => $pinv_number,
                                        'PInvAccountNumber' => $RealizedAccount->AccountNumber,
                                        'PInvSaldoDebet' => $realized_amount,
                                        'PInvSaldoCredit' => 0,
                                        'AmountCurrency' => 0,
                                        'PInvSignStatus' => 0,
                                        'PInvDesc' => $description,
                                        'ItemCategoryCode' => $category_name,
                                        'LastUser' => $this->session->userdata("username")
                                    );
                                    $this->m_purchase_invoice->insert_journal($journal_RealizedAccount);
                                } else if ($inv_dp_selisih_kurs < 0) {
                                    $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $currency_code);
                                    if ($RealizedAccount == false) {
                                        $this->trans_rollback('journal', 'Realized, Purchase', $currency_code);
                                    }

                                    $realized_amount = abs($inv_dp_selisih_kurs);
                                    $realized_currency = $currency_code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $currency_rate;

                                    $journal_RealizedAccount = array(
                                        'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                                        'PInvNumber' => $pinv_number,
                                        'PInvAccountNumber' => $RealizedAccount->AccountNumber,
                                        'PInvSaldoDebet' => 0,
                                        'PInvSaldoCredit' => $realized_amount,
                                        'AmountCurrency' => 0,
                                        'PInvSignStatus' => 1,
                                        'PInvDesc' => $description,
                                        'ItemCategoryCode' => $category_name,
                                        'LastUser' => $this->session->userdata("username")
                                    );
                                    $this->m_purchase_invoice->insert_journal($journal_RealizedAccount);
                                }
                            }
                        } else {
                            $PaidStatus = $DPUsed;
                            $dp_used_book = doubleval(($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);
                            $update_sordetail = array(
                                'DPUsed' => $dp_used_book
                            );
                            $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_sordetail, $vendor_code, $SOrdDetailDPID, $pord_number);

                            $PaymentBefore = doubleval($saldo_balance_detail - $DPUsed);
                            $PaymentBefore_Sum += $PaymentBefore;

                            $DPAccount = $this->m_account_journal->get_sys_purchase_account('AdvancePurchase', $currency_code); // Uang Muka Category -> 1-4-03-001-00
                            if ($DPAccount == false) {
                                $this->trans_rollback('journal', 'Uang Muka Pembelian', '');
                            }
                            $advance_value = doubleval($jurnal_dp);
                            $advance_currency = doubleval($jurnal_dp_no_currency);

                            $journal_advance = array(
                                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                                'PInvNumber' => $pinv_number,
                                'PInvAccountNumber' => $DPAccount->AccountNumber,
                                'PInvSaldoDebet' => 0,
                                'PInvSaldoCredit' => doubleval($advance_value),
                                'AmountCurrency' => doubleval($advance_currency),
                                'PInvSignStatus' => 1,
                                'PInvDesc' => $description,
                                'ItemCategoryCode' => $category_name,
                                'POrdDetailDPID' => $row_detail_dp->POrdDetailDPID,
                                'LastUser' => $this->session->userdata("username")
                            );

                            $this->m_purchase_invoice->insert_journal($journal_advance);

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

                                    $realized_amount = abs($inv_dp_selisih_kurs);
                                    $realized_currency = $currency_code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $currency_rate;

                                    $journal_RealizedAccount = array(
                                        'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                                        'PInvNumber' => $pinv_number,
                                        'PInvAccountNumber' => $RealizedAccount->AccountNumber,
                                        'PInvSaldoDebet' => $realized_amount,
                                        'PInvSaldoCredit' => 0,
                                        'AmountCurrency' => 0,
                                        'PInvSignStatus' => 0,
                                        'PInvDesc' => $description,
                                        'ItemCategoryCode' => $category_name,
                                        'LastUser' => $this->session->userdata("username")
                                    );
                                    $this->m_purchase_invoice->insert_journal($journal_RealizedAccount);
                                } else if ($inv_dp_selisih_kurs < 0) {
                                    $RealizedAccount = $this->m_account_journal->get_sys_purchase_account('RealizedGainedLoss', $currency_code);
                                    if ($RealizedAccount == false) {
                                        $this->trans_rollback('journal', 'Realized, Purchase', $currency_code);
                                    }

                                    $realized_amount = abs($inv_dp_selisih_kurs);
                                    $realized_currency = $currency_code == 'IDR' ? doubleval($inv_dp_selisih_kurs) : doubleval($inv_dp_selisih_kurs) / $currency_rate;

                                    $journal_RealizedAccount = array(
                                        'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                                        'PInvNumber' => $pinv_number,
                                        'PInvAccountNumber' => $RealizedAccount->AccountNumber,
                                        'PInvSaldoDebet' => 0,
                                        'PInvSaldoCredit' => $realized_amount,
                                        'AmountCurrency' => 0,
                                        'PInvSignStatus' => 1,
                                        'PInvDesc' => $description,
                                        'ItemCategoryCode' => $category_name,
                                        'LastUser' => $this->session->userdata("username")
                                    );
                                    $this->m_purchase_invoice->insert_journal($journal_RealizedAccount);
                                }
                            }
                        }
                    }
                }
            }
            /* ========================End=================================================== */
        }
        /* ==========================End======================================================== */

        //12. Insert Journal Pajak PPh Jasa 
        if ($pinv_pph23_val > 0) {
            $taxpph23_value = $currency_code == 'IDR' ? $pinv_pph23_val : doubleval($pinv_pph23_val) * $currency_rate;
            ;
            $taxpph23_currency = $pinv_pph23_val;

            $PPh23Account = $this->m_account_journal->get_sys_service_account('TaxPPh23', 'IDR'); // PPh23 Jasa / Service   
            if ($PPh23Account == false) {
                $this->trans_rollback('preference', 'Expense Account -> Taxable PPh 23', '');
            }

            $journal_taxpph23 = array(
                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                'PInvNumber' => $pinv_number,
                'PInvAccountNumber' => $PPh23Account->AccountNumber,
                'PInvSaldoDebet' => 0,
                'PInvSaldoCredit' => $taxpph23_value,
                'AmountCurrency' => $taxpph23_currency,
                'PInvSignStatus' => 0,
                'PInvDesc' => $description,
                'ItemCategoryCode' => $PPh23Account->AccountName,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_invoice->insert_journal($journal_taxpph23);
        }
        //---------------------------------------------------------------------------------------------------------------//

        /*
          Insert Journal Realized Account untuk fiscal rate yang tidak sama dengan currency rate
         */
        /* $total_rate_invoice 	= ($pinv_pph22_val - $pinv_pph23_val) * $currency_rate;
          $total_rate_fiscal 		= ($pinv_pph22_val - $pinv_pph23_val) * $fiscal_rate;
          $total_ppay_realizedgl 	= $total_rate_fiscal - $total_rate_invoice;

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

          if($total_ppay_realizedgl > 0){
          $realizegl_value    = $total_ppay_realizedgl;
          $realized_currency  = $currency_code == 'IDR' ? $realizegl_value: 0;
          //$realized_currency  = 0;    //$realizegl_value;

          $journal_realized = array(
          'PInvDate'              => date("Y-m-d", strtotime($pinv_date)),
          'PInvNumber'            => $pinv_number,
          'PInvDesc'              => $description,
          'PInvAccountNumber'     => $RealizedAccount->AccountNumber,
          'PInvSaldoDebet'        => 0,
          'PInvSaldoCredit'       => abs($realizegl_value),
          'AmountCurrency'        => abs($realized_currency),
          'PInvSignStatus'        => 1,
          'PInvPPnFiscal'         => 0,
          'ItemCategoryCode'      => $category_name,
          'LastUser'              => $this->session->userdata("username")
          );

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

          if($total_ppay_realizedgl < 0){
          $realizegl_value    = $total_ppay_realizedgl;
          $realized_currency  = $currency_code == 'IDR' ? $realizegl_value: 0;
          //$realized_currency  = 0;    //$realizegl_value;

          $journal_realized = array(
          'PInvDate'              => date("Y-m-d", strtotime($pinv_date)),
          'PInvNumber'            => $pinv_number,
          'PInvDesc'              => $description,
          'PInvAccountNumber'     => $RealizedAccount->AccountNumber,
          'PInvSaldoDebet'        => abs($realizegl_value),
          'PInvSaldoCredit'       => 0,
          'AmountCurrency'        => abs($realized_currency),
          'PInvSignStatus'        => 0,
          'PInvPPnFiscal'         => 0,
          'ItemCategoryCode'      => $category_name,
          'LastUser'              => $this->session->userdata("username")
          );

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

        //13. insert journal Estimate Freight pada Purchase Account => Biaya Freight In (Negative)
        if ($pinv_est_freight < 0) {
            $this->m_purchase_invoice->insert_journal($journal_freight);
        }

        /*
          Beban Auto
         */
        /*
          Calculate beban pembulatan auto
         */
        if (($pinv_sub_total_real + $pinv_est_freight - $pinv_total_dp) > 0) {
            $Total_BebanAuto_Condition = 0;
            $Total_BebanAuto = 0;
        } else {
            if ($pinv_pph22_val > 0) {
                $Total_BebanAuto = 0;
            } else {
                $Total_BebanAuto = doubleval($pinv_sub_total + $pinv_est_freight - $pinv_total_dp);
            }
        }
        /* ==================END=================== */

        if (($Total_BebanAuto) > 0) {
            $BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
            if ($BebanAccountAuto == false) {
                $this->trans_rollback('journal', 'Beban Pembulatan', $CurrencyCode);
            }
            $payable_beban = $currency_code == 'IDR' ? $Total_BebanAuto : $Total_BebanAuto * $currency_rate;

            $journal_beban = array(
                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                'PInvNumber' => $pinv_number,
                'PInvDesc' => $description,
                'PInvAccountNumber' => $BebanAccountAuto->AccountNumber,
                'PInvSaldoDebet' => 0,
                'PInvSaldoCredit' => abs($payable_beban),
                'AmountCurrency' => 0,
                'PInvSignStatus' => 1,
                'PInvPPnFiscal' => 0,
                'ItemCategoryCode' => $category_name,
                'LastUser' => $this->session->userdata("username")
            );
            $this->m_purchase_invoice->insert_journal($journal_beban);
        } else if (($Total_BebanAuto) < 0) {
            $BebanAccountAuto = $this->m_account_journal->get_account_name('Beban Pembulatan');
            if ($BebanAccountAuto == false) {
                $this->trans_rollback('journal', 'Beban Pembulatan', $CurrencyCode);
            }
            $payable_beban = $currency_code == 'IDR' ? $Total_BebanAuto : $Total_BebanAuto * $currency_rate;

            $journal_beban = array(
                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                'PInvNumber' => $pinv_number,
                'PInvDesc' => $description,
                'PInvAccountNumber' => $BebanAccountAuto->AccountNumber,
                'PInvSaldoDebet' => abs($payable_beban),
                'PInvSaldoCredit' => 0,
                'AmountCurrency' => 0,
                'PInvSignStatus' => 0,
                'PInvPPnFiscal' => 0,
                'ItemCategoryCode' => $category_name,
                'LastUser' => $this->session->userdata("username")
            );
            $this->m_purchase_invoice->insert_journal($journal_beban);
        }
        /* =============================END================================ */

        /* ================7. Insert Journal PPn Masukan pada Fiscal ==================================================== */
        if ($pinv_ppn10_val > 0) {
            $taxppn_value = 0;
            $tax_currency = 0;
            if ($currency_code != 'IDR') {
                foreach ($CategoryIDPPn10 as $key => $value) {
                    $PPnAccount = $this->m_account_journal->get_sys_purchase_account('PurchaseTaxable', 'IDR'); // PPn Masukan
                    if ($PPnAccount == false) {
                        $this->trans_rollback('preference', 'Hutang PPn Masukan', '');
                    }

                    //$PPnAccount   = $this->m_account_journal->get_account_name('PPN Masukan (Fiscal)'); // Hutang PPn Fiscal
                    //if($PPnAccount == false) {$this->trans_rollback('journal','Hutang PPn Masukan Fiscal (Taxable),Taxable','');}

                    $taxppn_value = $currency_code == 'IDR' ? $value : doubleval($value) * $fiscal_rate;
                    $ppn_fiscal = $currency_code == 'IDR' ? 0 : 1;
                    $tax_currency = $value;

                    $journal_taxppn10 = array(
                        'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                        'PInvNumber' => $pinv_number,
                        'PInvDesc' => $description,
                        'PInvAccountNumber' => $PPnAccount->AccountNumber,
                        'PInvSaldoDebet' => $taxppn_value,
                        'PInvSaldoCredit' => 0,
                        'AmountCurrency' => $tax_currency,
                        'PInvSignStatus' => 0,
                        'PInvPPnFiscal' => $ppn_fiscal,
                        'ItemCategoryCode' => $PPnAccount->AccountName,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $get_journal_purchase_invoice = $this->m_purchase_invoice->get_journal_purchase_invoice($PPnAccount->AccountNumber, $pinv_number);
                    if (empty($get_journal_purchase_invoice->PInvAccountNumber)) {
                        $this->m_purchase_invoice->insert_journal($journal_taxppn10);
                    } else {
                        $taxppn_value = $taxppn_value + $get_journal_purchase_invoice->PInvSaldoDebet;
                        $tax_currency = $tax_currency + $get_journal_purchase_invoice->AmountCurrency;

                        $journal_update_ppn = array(
                            'PInvSaldoDebet' => $taxppn_value,
                            'PInvSaldoCredit' => 0,
                            'AmountCurrency' => $tax_currency
                        );
                        $this->m_purchase_invoice->update_journal($pinv_number, $journal_update_ppn, $get_journal_purchase_invoice->PInvAccountNumber);
                    }

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

                    $journal_ppnfiscal = array(
                        'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                        'PInvNumber' => $pinv_number,
                        'PInvDesc' => $description,
                        'PInvAccountNumber' => $PPnFiscalAccount->AccountNumber,
                        'PInvSaldoDebet' => 0,
                        'PInvSaldoCredit' => $taxppn_value,
                        'AmountCurrency' => $tax_currency,
                        'PInvSignStatus' => 0,
                        'PInvPPnFiscal' => $ppn_fiscal,
                        'ItemCategoryCode' => $PPnFiscalAccount->AccountName,
                        'LastUser' => $this->session->userdata("username")
                    );
                }
            }
        }
        /* =======================End============================================================================ */

        //14. Insert journal PPn Fiscal
        if (($pinv_ppn10_val > 0) && ($currency_code != 'IDR')) {
            //Insert journal Hutang PPn Fiscal pada credit
            $this->m_purchase_invoice->insert_journal($journal_ppnfiscal);
        }
    }

    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['app1']		= $this->app1;
                    //        $data['app2']		= $this->app2;

                    $data['detail'] = $this->m_purchase_invoice->get_pi_data($id);
                    $data['vendor'] = $this->m_vendors->get_by_id($data['detail']->VendorCode);

                    $porddatetemp = explode(",", $data["detail"]->PRecDate);

                    foreach ($porddatetemp as $row => $result) {
                        $porddatetemp[$row] = date("d-m-Y", strtotime($result));
                    }

                    $data["detail"]->PRecDate = implode(",", $porddatetemp);

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

    public function update() {
        /* ==============Deklar variabel array=========================== */
        $CategoryCodeAmount = array();
        $CategoryCodeType = array();

        $CategoryCodeAmount_Exp = array();
        $CategoryCodeType_Exp = array();

        $CategoryIDPPh22 = array();
        $CategoryIDPPh23 = array();
        $CategoryIDAmt = array();
        $CategoryIDCode = array();
        $CategoryIDName = array();
        $CategoryIDType = array();
        $CategoryIDAsset = array();
        $CategoryIDPPn10 = array();
        $CategoryDisc = array();
        $CategoryDPAmount = array();
        /* ===============End=========================================== */

        /* =======================Deklar variabel post=========================================== */
        $pinv_number = $this->input->post('txt_pinv_no');
        $prec_number = $this->input->post('txt_prec_no');
        $pinv_date = $this->input->post('txt_pinv_date');

        $currency_code = $this->input->post('hdn_currency_code');
        $currency_rate = $this->input->post('txt_currency_rate');
        $fiscal_rate = $this->input->post('txt_fiscal_rate');
        $vend_inv_number = $this->input->post('txt_vendor_inv_no');
        $vendor_code = $this->input->post('cbg_vendor');
        $pord_number = $this->input->post('hdn_pord_no');

        $fob_id = $this->input->post('cbo_fob') == "" ? null : $this->input->post('cbo_fob');
        $terms_id = $this->input->post('cbo_terms') == "" ? null : $this->input->post('cbo_terms');
        $shipment_id = $this->input->post('cbo_ship_via') == "" ? null : $this->input->post('cbo_ship_via');
        $description = $this->input->post('txa_description');
        $taxes_status = $this->input->post('hdn_taxes_status');

        $pinv_ppn10_val = $this->input->post('txt_ppn10_hide');
        $pinv_pph22_val = $this->input->post('txt_pph22_hide');
        $pinv_pph23_val = $this->input->post('txt_pph23_hide');

        $pinv_ppn10_val_real = $this->input->post('txt_ppn10');
        $pinv_pph22_val_real = $this->input->post('txt_pph22');
        $pinv_pph23_val_real = $this->input->post('txt_pph23');

        $pinv_ppn10_pcnt = $pinv_ppn10_val == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');

        $pinv_sub_total = $this->input->post('txt_sub_total_hide');
        $pinv_sub_total_real = $this->input->post('txt_sub_total');

        $pinv_discount = $this->input->post('txt_discount_hide');
        $pinv_est_freight = $this->input->post('txt_freight');
        $pinv_total_purchase = $this->input->post('txt_total_purchase_hide');
        $pinv_total_dp = $this->input->post('txt_total_dp');
        $pinv_total_invoice = $this->input->post('txt_total_invoice_hide');
        /* =======================End==================================================================== */

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

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

        if (count($detail) > 0) {
            $this->db->trans_begin();
            $item_value = 0;
            $item_category = '';
            $item_category_code = '';

            $data = array(
                'CurrencyRate' => $currency_rate,
                'FiscalRate' => $fiscal_rate,
                'VendInvNumber' => $vend_inv_number,
                'ShipmentID' => $shipment_id,
                'TermsPaymentID' => $terms_id,
                'FOBID' => $fob_id,
                'PInvDesc' => $description,
                'PInvDiscount' => $pinv_discount,
                'PInvPPn10' => $pinv_ppn10_val,
                'PInvEstFreight' => $pinv_est_freight,
                'PInvTotalAmount' => $pinv_total_purchase,
                'PInvTotalInvoice' => $pinv_total_invoice,
                'PPayTotalAmount' => 0,
                'PInvTotalOwing' => $pinv_total_invoice,
                'TransStatus' => 4,
				'AppFinished' => 2,
                'LastUser' => $this->session->userdata("username")
            );

            //1. insert into table Purhcase Invoice (PurchaseInvoice)
            $this->m_purchase_invoice->update($data, $pinv_number);

            foreach ($detail as $row) {
                $detail_data = array(
                    'ItemTaxPPn10' => $row->ItemTaxPPn10,
                    'ItemTaxPPh22' => $row->ItemTaxPPh22,
                    'ItemTaxPPh23' => $row->ItemTaxPPh23,
                    'ItemTotalAmount' => $row->ItemTotalAmount,
                    'LastUser' => $this->session->userdata("username")
                );

                //2. insert into Purchase Invoice Detail (PInvDetail)
                $this->m_purchase_invoice->update_detail($detail_data, $row->PInvDetailID);

                @$CategoryCodeAmount[$row->ItemCategoryID] += $row->ItemAmount;
                @$CategoryCodeType[$row->ItemCategoryID] = $row->ItemType;

                @$CategoryCodeAmount_Exp[$row->ItemCategoryCode] += $row->ItemAmount;
                @$CategoryCodeType_Exp[$row->ItemCategoryCode] = $row->ItemType;

                @$CategoryIDPPh22[$row->ItemCategoryID] += $row->ItemTaxPPh22;
                @$CategoryIDPPh23[$row->ItemCategoryID] += $row->ItemTaxPPh23;
                @$CategoryIDPPn10[$row->ItemCategoryID] += $row->ItemTaxPPn10;

                @$CategoryIDAmt[$row->ItemCategoryID] += $row->ItemAmount;
                @$CategoryIDCode[$row->ItemCategoryID] = $row->ItemCategoryID;
                @$CategoryDisc[$row->ItemCategoryID] += $row->AmountDisc;
                @$CategoryIDName[$row->ItemCategoryID] = $row->ItemCategoryCode;
                @$CategoryIDType[$row->ItemCategoryID] = $row->ItemType;
                @$CategoryIDAsset[$row->ItemCategoryID] = $row->ItemStatus;
                @$CategoryDPAmount[$row->ItemCategoryID] += $row->ItemAmount;

                if ($row->ItemType == 0) {
                    $item_category_code = $row->ItemCategoryCode;
                }
            }
            //---------------------------------------------------------------------------------------------------------------//

            if ($pinv_total_dp > 0) {

                /* ===================Get Pordetail DP========================================== */
                $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_saldo_detail_dp_suspend($vendor_code, $pord_number, $DPAccount->AccountNumber);

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

                    $update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => abs($total_pordetail));
                    $this->m_purchase_payment->update_po_detail_dp_pay_before($update_sordstatus, $vendor_code, $pord_number, $POrdDetailDPID);
                }
                /* ========================End=================================================== */
            }

            /* ================End Delete Journal ============================ */
            $this->m_purchase_invoice->delete_journal($pinv_number);
            /* ======================End====================================== */

            $this->insert_journal($pinv_ppn10_val_real, $pinv_pph22_val_real, $pinv_pph23_val_real, $pinv_sub_total_real, $pinv_total_invoice, $pinv_total_purchase, $pord_number, $vendor_code, $fiscal_rate, $pinv_sub_total, $pinv_pph23_val, $pinv_total_dp, $pinv_discount, $taxes_status, $pinv_ppn10_pcnt, $pinv_pph22_val, $pinv_ppn10_val, $pinv_est_freight, $item_category_code, $item_category, $CategoryCodeAmount, $CategoryCodeType, $CategoryIDPPh22, $CategoryIDPPh23, $CategoryIDAmt, $CategoryIDCode, $CategoryIDName, $CategoryIDType, $CategoryIDAsset, $pinv_date, $pinv_number, $description, $currency_rate, $currency_code, $CategoryIDPPn10, $CategoryDisc, $CategoryCodeAmount_Exp, $CategoryCodeType_Exp, $CategoryDPAmount);

            //3. Update Receive Item for status lock = 1
            $prec_number = explode(",", $prec_number);

            foreach ($prec_number as $key => $value) {
                $data_ri = array(
                    'LockedStatus' => 1,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_receive_item->update($data_ri, $value);
            }
            //---------------------------------------------------------------------------------------------------------------//

            /* =============================trans roll back dan trans commit============================/ */
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 0, $pinv_number);

                $result['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                $result['number'] = $pinv_number;
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 1, $pinv_number);
            }
            /* ==================================end====================================================== */
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'update', 0);
        }

        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);

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

            if (count($detail) > 0) {
                $this->db->trans_begin();
                $CategoryIDPPh22 = array();
                $CategoryIDPPh23 = array();
                $CategoryIDAmt = array();
                $CategoryIDCode = array();
                $CategoryIDType = array();
                $CategoryIDAsset = array();

                $trans_status = 1;
                $app_finished = 0;

                $branch_code = $this->session->userdata('branch');
                $vendor_code = $this->input->post('VendorCode');
                $status = $this->input->post('Status');

                $prec_number = $this->input->post('PRecNumber');
                $pinv_number = $this->input->post('PInvNumber');
                $pinv_date = $this->input->post('PInvDate');
                $pinv_desc = $this->input->post('PInvDesc');
                $POrdNumber = $this->input->post('POrdNumber');

                $currency_code = $this->input->post('CurrencyCode');
                $currency_rate = $this->input->post('CurrencyRate');
                $fiscal_rate = $this->input->post('FiscalRate');

                $taxppn10 = $this->input->post('TaxPPn10');
                $taxpph22 = $this->input->post('TaxPPh22');
                $taxpph23 = $this->input->post('TaxPPh23');

                $taxppn10_pcnt = $taxppn10 == 0 ? 0 : $this->input->post('TaxPPn10Pcnt');

                $sub_total = $this->input->post('SubTotal');
                $sub_total_Real = $this->input->post('SubTotal_Real');

                $total_discount = $this->input->post('TotalDiscount');
                $total_freight = $this->input->post('TotalFreight');
                $total_purchase = $this->input->post('TotalPurchase');
                $total_dp = $this->input->post('TotalDP');
                $total_invoice = $this->input->post('TotalInvoice');
                $total_invoice_hide = $this->input->post('TotalInvoice_Hide');

                $data = $this->m_purchase_invoice->get_pi_data($pinv_number);

                /*
                  Cek Concuren For Approval Mgr
                 */
                $get_employee = $this->m_employee->get_detail($data->AppLevel1Code);
                if (($data->AppLevel1Code != NULL)) {
                    $result['status'] = false;
                    $result['message'] = 'Maaf Transaksi gagal di Approve, karena transaksi sudah di approve terlebih dahulu oleh, ' . $get_employee->EmployeeName . ' pada tanggal ' . date("d-m-Y", strtotime($data->AppLevel1Date)) . '';

                    echo json_encode($result);
                    $this->db->trans_rollback();
                    die();
                }
                /* =========================End======================================== */

                $app_finished = 1;

                //1. Update Vendor For New OutStanding and PPnFiscalDebt
                $vendor_saldo = $this->m_vendors->get_saldo_by_id($vendor_code);

                if ($total_dp > $total_purchase) {
                    $saldo_balance = doubleval($vendor_saldo[0]->OutStanding) + doubleval($total_invoice_hide);
                } else {
                    $saldo_balance = doubleval($vendor_saldo[0]->OutStanding) + doubleval($total_invoice);
                }

                if (($taxppn10 > 0) && ($currency_code != 'IDR')) {
                    $data_vendor_saldo = array(
                        'OutStanding' => $saldo_balance,
                        'OutStandingFiscal' => $taxppn10,
                        'LastUser' => $this->session->userdata("username")
                    );
                } else {
                    $data_vendor_saldo = array(
                        'OutStanding' => $saldo_balance,
                        'LastUser' => $this->session->userdata("username")
                    );
                }

                $this->m_vendors->update($data_vendor_saldo, $vendor_code, $vendor_saldo[0]->BranchCode);

                /*
                  Kurangi nilai DP di vendor jika terdapat DP
                 */
                if ($total_dp > 0) {
                    if ($total_dp > $total_purchase) {
                        $saldo_dp_balance = doubleval($vendor_saldo[0]->SaldoDPBalance) - doubleval($total_purchase);
                    } else {
                        $saldo_dp_balance = doubleval($vendor_saldo[0]->SaldoDPBalance) - doubleval($total_dp);
                    }

                    $data_vendor_dp = array(
                        'SaldoDPBalance' => $saldo_dp_balance
                    );

                    $this->m_vendors->update($data_vendor_dp, $vendor_code, $vendor_saldo[0]->BranchCode);
                }
                //-------------------------------------------------------------------------------------------------------//
                //2. Update Receive Item for status = 2
                $prec_number = explode(",", $prec_number);

                foreach ($prec_number as $key => $value) {
                    $data_ri = array(
                        'TransStatus' => 2,
                        'LockedStatus' => 2,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $this->m_receive_item->update($data_ri, $value);
                }
                //-------------------------------------------------------------------------------------------------------//

                /*
                  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, $POrdNumber, 0);
                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) {
                        $StatusDPFor = 1;
                    } else {
                        $StatusDPFor = 0;
                    }

                    $update_dp_for = array(
                        'StatusDPFor' => $StatusDPFor
                    );
                    $this->m_purchase_payment->update_po_detail_dp_by_vendor($update_dp_for, $vendor_code, $SOrdDetailDPID, $POrdNumber);
                }

                /* ======================End================================================================================ */
                if ($total_invoice > 0) {

                    $trans_status = 1;

                    //3. Delete from InvoicePayment
                    $this->m_purchase_invoice->delete_payment($pinv_number);
                    //-------------------------------------------------------------------------------------------------------//

                    $CategoryIDPPh22 = array();
                    $CategoryIDPPh23 = array();
                    $CategoryIDAmt = array();
                    $CategoryIDCode = array();
                    $CategoryIDType = array();
                    $CategoryIDAsset = array();

                    foreach ($detail as $row) {
                        @$CategoryIDPPh22[$row->ItemCategoryID] += $row->ItemTaxPPh22;
                        @$CategoryIDPPh23[$row->ItemCategoryID] += $row->ItemTaxPPh23;
                        @$CategoryIDAmt[$row->ItemCategoryID] += $row->ItemAmount_Hide;
                        @$CategoryIDCode[$row->ItemCategoryID] = $row->ItemCategoryCode;
                        @$CategoryIDType[$row->ItemCategoryID] = $row->ItemType;
                        @$CategoryIDAsset[$row->ItemCategoryID] = $row->ItemStatus;
                    }

                    $total_loop = 0;
                    $total_ratio = 0;
                    $freight_ratio = 0;
                    $total_records = count($CategoryIDAmt);

                    foreach ($CategoryIDAmt as $key => $value) {
                        if (($CategoryIDAsset != 1)) {
                            $total_loop++;

                            if ($total_loop == $total_records) {
                                $item_ratio = 100 - $total_ratio;
                            } else {
                                $item_ratio = floor(abs((doubleval($value) / $sub_total) * 100));
                            }

                            $total_ratio = $total_ratio + $item_ratio;


                            $item_pph22 = $CategoryIDPPh22[$key];
                            $item_pph23 = $CategoryIDPPh23[$key];

                            $tax_ppn10 = $taxppn10 * ($item_ratio / 100);
                            $tax_pph22 = $taxpph22 * ($item_ratio / 100);
                            $tax_pph23 = $taxpph23 * ($item_ratio / 100);

                            $invoice_ratio = $total_purchase * ($item_ratio / 100);
                            $subtotal_ratio = $sub_total * ($item_ratio / 100);
                            //$discount_ratio = $total_discount * ($item_ratio / 100);
                            $freight_ratio = $total_freight * ($item_ratio / 100);
                            $dp_ratio = $total_dp * ($item_ratio / 100);
                            $item_ppn = ($currency_code == 'IDR' && $taxppn10_pcnt > 0) ? ($tax_ppn10) : 0;

                            $amount_ratio = doubleval($subtotal_ratio) + $item_ppn + $tax_pph22 - $tax_pph23 /* - $discount_ratio */ + $freight_ratio - $dp_ratio;

                            if (($sub_total_Real + $total_freight - $total_dp) > 0) {
                                $data_payment = array(
                                    'BranchCode' => $branch_code,
                                    'VendorCode' => $vendor_code,
                                    'InvoiceNumber' => $pinv_number,
                                    'InvoiceDate' => date("Y-m-d", strtotime($pinv_date)),
                                    'InvoiceCurrCode' => $currency_code,
                                    'InvoiceCurrRate' => $currency_rate,
                                    'InvoiceFiscalRate' => $fiscal_rate,
                                    'InvoicePurchase' => $invoice_ratio,
                                    'InvoiceTotalDP' => $dp_ratio,
                                    'InvoiceAmount' => $invoice_ratio,
                                    'InvoiceOwing' => $amount_ratio,
                                    'ItemCategoryRatio' => $item_ratio,
                                    'ItemCategoryID' => $key,
                                    'ItemCategoryCode' => $CategoryIDCode[$key],
                                    'ItemStatus' => $CategoryIDAsset[$key],
                                    'ItemType' => $CategoryIDType[$key],
                                    'InvoiceType' => 0,
                                    'PPnFiscalStatus' => 0,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_purchase_invoice->insert_payment($data_payment);
                            }
                        }
                    }

                    /*
                      PPN Fiscal
                     */
                    if (($taxppn10 > 0) && ($currency_code != 'IDR')) {
                        $data_payment = array(
                            'BranchCode' => $branch_code,
                            'VendorCode' => $vendor_code,
                            'InvoiceNumber' => $pinv_number,
                            'InvoiceDate' => date("Y-m-d", strtotime($pinv_date)),
                            'InvoiceCurrCode' => $currency_code,
                            'InvoiceCurrRate' => $currency_rate,
                            'InvoiceFiscalRate' => $fiscal_rate,
                            'InvoicePurchase' => (doubleval($taxppn10) * doubleval($fiscal_rate)),
                            'InvoiceAmount' => (doubleval($taxppn10) * doubleval($fiscal_rate)),
                            'InvoiceOwing' => (doubleval($taxppn10) * doubleval($fiscal_rate)),
                            'InvoiceTotalDP' => 0,
                            'ItemCategoryRatio' => $item_ratio,
                            'ItemCategoryID' => -3,
                            'ItemCategoryCode' => 'PPn Fiscal',
                            'InvoiceType' => 0,
                            'PPnFiscalStatus' => 1,
                            'LastUser' => $this->session->userdata("username")
                        );

                        $this->m_purchase_invoice->insert_payment($data_payment);
                    }
                    //-------------------------------------------------------------------------------------------------------//

                    /* ===================4. Insert into PInvDetail Recur========================== */
                    /*
                      Jika transaksi adalah advance
                     */
                    foreach ($detail as $row) {
                        if ($row->ItemType == 2) {
                            $item_qty = $row->ItemQty;
                            $item_amount = $row->ItemAmount_Hide * $currency_rate;

                            if ($currency_code == 'IDR') {
                                $item_tax_ppn10 = $row->ItemTaxPPn10 * $currency_rate;
                            } else {
                                $item_tax_ppn10 = $row->ItemTaxPPn10 * $fiscal_rate;
                            }

                            $item_tax_pph22 = $row->ItemTaxPPh22 * $currency_rate;
                            $item_total_amount = $item_amount;

                            $data_detail_recur = array(
                                'PInvDetailID' => $row->PInvDetailID,
                                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                                'PInvNumber' => $pinv_number,
                                'PInvMemo' => $pinv_desc,
                                'ItemCode' => $row->ItemCode,
                                'ItemDesc' => $row->ItemDesc,
                                'ItemQty' => $item_qty,
                                'ItemUnit' => $row->ItemUnit,
                                'ItemAmount' => $item_amount,
                                'ItemTaxPPn10' => $item_tax_ppn10,
                                'ItemTaxPPh22' => $item_tax_pph22,
                                'ItemTotalAmount' => $item_total_amount,
                                'ItemPPh22Status' => $row->ItemPPh22Status,
                                'ItemAdvNetDueIn' => $row->ItemAdvNetDueIn,
                                'LastUser' => $this->session->userdata("username")
                            );

                            //3. Insert POrdDetailRecure for Adv. Payment data only
                            $this->m_purchase_invoice->insert_detail_recur($data_detail_recur);
                        }
                    }
                    //-------------------------------------------------------------------------------------------------------//
                } else {
                    if ($currency_code == 'IDR') {
                        $trans_status = 2;
                    } else {
                        if ($taxppn10 > 0) {
                            /*
                              PPN Fiscal
                             */
                            $data_payment = array(
                                'BranchCode' => $branch_code,
                                'VendorCode' => $vendor_code,
                                'InvoiceNumber' => $pinv_number,
                                'InvoiceDate' => date("Y-m-d", strtotime($pinv_date)),
                                'InvoiceCurrCode' => $currency_code,
                                'InvoiceCurrRate' => $currency_rate,
                                'InvoiceFiscalRate' => $fiscal_rate,
                                'InvoicePurchase' => (doubleval($taxppn10) * doubleval($fiscal_rate)),
                                'InvoiceAmount' => (doubleval($taxppn10) * doubleval($fiscal_rate)),
                                'InvoiceOwing' => (doubleval($taxppn10) * doubleval($fiscal_rate)),
                                'InvoiceTotalDP' => 0,
                                'ItemCategoryRatio' => 100,
                                'ItemCategoryID' => -3,
                                'ItemCategoryCode' => 'PPn Fiscal',
                                'InvoiceType' => 0,
                                'PPnFiscalStatus' => 1,
                                'LastUser' => $this->session->userdata("username")
                            );

                            $this->m_purchase_invoice->insert_payment($data_payment);
                            //-------------------------------------------------------------------------------------------------------//
                        } else {
                            $trans_status = 2;
                        }
                    }
                }


                //4. Update Purchase Invoice for status only
                $data_pi = array(
                    'TransStatus' => $trans_status,
                    'AppFinished' => $app_finished,
                    'AppLevel1Status' => 1,
                    'AppLevel1Code' => $this->session->userdata("username"),
                    'AppLevel1Date' => date("Y-m-d"),
                    'LastUser' => $this->session->userdata("username")
                );

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

                /* =============================trans roll back dan trans commit============================/ */
                if ($this->db->trans_status() === FALSE) {
                    $this->db->trans_rollback();
                    $result['status'] = FALSE;
                    $result['message'] = get_notification('approval', 0);
                } else {
                    $this->db->trans_commit();
                    $result['status'] = TRUE;
                    $result['message'] = get_notification('approval', 1);
                }
                /* ==================================end====================================================== */
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('approval', 0);
            }

            echo json_encode($result);
            die();
        }
    }
	
	function reverse_data_detail() {
       try{
	  		$pinv_number  		= $this->input->post('txt_pinv_no');
            $detail_post  		= $this->input->post('detail');
            $detail 	  		= json_decode($detail_post);
			$branch_code  		= $this->session->userdata("branch");
			$txt_total_dp 		= $this->input->post('txt_total_dp');
			$txt_prec_no  		= $this->input->post('txt_prec_no');
			$hdn_currency_code  = $this->input->post('hdn_currency_code');
			$vendor_code 		= $this->input->post('cbg_vendor');
			$pord_number 		= $this->input->post('hdn_pord_no');
			$txt_old_pinv 		= $this->input->post('txt_old_pinv');
			
			if($txt_old_pinv != NULL){
				throw new Exception("Transaksi gagal di Reverse, karena data ini adalah import file tidak mempunyai No Receive Item, silahkan Reverse transaki yang lain"); //Sudah dibuat di pp atau belum
			}
			
			/*
				Cek used in pp
			*/
			$date_transaction 	= check_end_periode($pinv_number);
			
			 $get_detail_ppay = $this->m_custom->check_item_reverse($pinv_number, 'at_purchasepayment', 'at_ppaydetail', 'PPayNumber', 'PInvNumber'); //Check pp
			 $get_detail_pret = $this->m_custom->check_item_reverse($pinv_number, 'at_purchasereturn', 'at_pretdetail', 'PRetNumber', 'PInvNumber'); //Check Pret
			 $get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);//Check Periode End
			 
			 if ($get_detail_ppay) {
                throw new Exception(msg_check_po_reverse('Purchase Payment')); //Sudah dibuat di pp atau belum
             } else if ($get_end_periode) {
                throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
             } else if($get_detail_pret) {
			 	throw new Exception(msg_check_po_reverse('Purchase Return')); //Sudah dibuat di pret atau belum
			 }
			/*======================End===================*/
			
			
			
			foreach ($detail as $row_detail) {
				$ItemType = $row_detail->ItemType;
				if($ItemType == 2){
					/*
						This Advanced
					*/
                    $this->transaction['delete_recurdetail']['PInvNumber'][] = $pinv_number;
                    $this->transaction['delete_recurdetail']['ItemCode'][] = $row_detail->ItemCode;
					/*=========================End===============*/
				}
				//else{
//					/*
//                      Check Adjustment
//                     */
//                    $item_lock_status = $this->m_receive_item->check_lock_status($pinv_number, $branch_code, $row_detail->ItemCode);
//                    if ($item_lock_status) {
//                        throw new Exception(('Tidak bisa dilakukan proses Reverse, karena item ' . $row_detail->ItemCode . ' pada listing sedang dilakukan proses Adjustment')); //item adjust
//                    }
//                    /* =================END============================== */
//				}
			}
			
			/*
				Update journal appfinished
			*/
			 $data_pi = array(
				'TransStatus' 		=> 4,
				'AppFinished' 		=> 0,
				'AppLevel1Status' 	=> 0,
				'AppLevel1Code' 	=> NULL,
				'AppLevel1Date' 	=> NULL,
				'LastUser' 			=> $this->session->userdata("username")
			);
			
			$this->transaction['update_group']['PInvNumber'] 	= $pinv_number;
            $this->transaction['update_group']['data'] 			= $data_pi;
			/*================================End====================*/
			
			/*
				Delete invoice payment
			*/
			$this->transaction['delete_invoice_payment']['InvoiceNumber'] = $pinv_number;
			/*=========================End===============*/
			
			/*
				Update Receive Item trans status 1
			*/
			$prec_number = explode(",", $txt_prec_no);

			foreach ($prec_number as $key => $value) {
				$data_ri = array(
					'TransStatus' => 1
				);
				$this->transaction['update_group_ri']['PRecNumber'][] 	= $value;
				$this->transaction['update_group_ri']['data'][] 			= $data_ri;
			}
			
			
			/*========================End=========================*/
				
			$result_approve = $this->m_purchase_invoice->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $pinv_number);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $pinv_number);
            }
            echo json_encode($result);
	   }
	   catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
	}
	
    public function suspend_data() {
        $pinv_number = $this->input->post('id');
        $data = $this->m_purchase_invoice->get_pi_data($pinv_number);

        if ($data->AppLevel1Status != 1 && $data->AppLevel2Status != 1) {
            $this->db->trans_begin();


            if ($data->PInvTotalDP > 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_saldo_detail_dp_suspend($data->VendorCode, $data->POrdNumber, $DPAccount->AccountNumber);
                if ($data->PInvTotalDP > $data->PInvTotalAmount) {
                    $saldo_dp = $data->PInvTotalAmount;
                } else {
                    $saldo_dp = $data->PInvTotalDP;
                }
                $is_edit = "";

                foreach ($sordetail_dp_new as $row_dp_suspend) {
                    $DPUsed = $row_dp_suspend->DPUsed;
                    $POrdDetailDPID = $row_dp_suspend->POrdDetailDPID;

                    $tatal_pordetail = $row_dp_suspend->AmountCurrency - $DPUsed;

                    $update_sordstatus = array('SOrdStatus' => 1, 'DPUsed' => abs($tatal_pordetail));
                    $this->m_purchase_payment->update_po_detail_dp_pay_before($update_sordstatus, $data->VendorCode, $data->POrdNumber, $POrdDetailDPID);
                }
            }
            //1. Update Receive Item for status = 1
            $pi_data = $this->m_purchase_invoice->get_pi_data($pinv_number);
            $prec_number = explode(",", $pi_data->PRecNumber);

            foreach ($prec_number as $key => $value) {
                $data_ri = array(
                    'TransStatus' => 1,
                    'LockedStatus' => 0,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_receive_item->update($data_ri, $value);
            }
            //---------------------------------------------------------------------------------------------------------------//

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

            //2. Update PurchaseInvoice for status = 3 or 9
            $this->m_purchase_invoice->update($data_update, $pinv_number);
            //---------------------------------------------------------------------------------------------------------------//
            //3. Update InvoicePayment for status = 3 or 9
            //$this->m_purchase_invoice->update_payment($data_update, $pinv_number);
            //---------------------------------------------------------------------------------------------------------------------//            

            /* =============================trans roll back dan trans commit============================/ */
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification('suspend', 0);
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification('suspend', 1);
            }
            /* ==================================end====================================================== */
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend1', 0);
        }

        echo json_encode($result);
    }

    function to_preview($obj_string = null) {
//        $data['list'] = $this->m_purchase_invoice->get_all_print($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_invoice->get_all_to_print($data_filter);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_invoice/v_preview_purchase_invoice', $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_invoice->get_all_print($this->ho);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_invoice/v_preview_purchase_invoice', $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_invoice->get_all($this->ho);
        $this->load->view('v_header');
        $this->load->view('purchase/purchase_invoice/v_print_purchase_invoice', $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_invoice->get_pi_data_print($id);
            //echo $this->db->last_query();
            $data['list'] = $this->m_purchase_invoice->get_detail_item_print($id);
            //echo $this->db->last_query();		
            $this->load->view('v_header');
            $this->load->view('purchase/purchase_invoice/v_print_detail_purchase_invoice', $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_invoice->get_pi_data($id);
        $data['list'] = $this->m_purchase_invoice->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_invoice/v_preview_journal_purchase_invoice', $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_invoice->get_pi_data($id);
        $data['list'] = $this->m_purchase_invoice->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_invoice/v_print_journal_purchase_invoice', $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'] : '';
        /* ============================================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('PInvNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('PInvDesc', $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 ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('at_purchaseinvoice.PInvDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_purchaseinvoice.PInvDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ==========================end================================================================= */

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

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

            $hasil[] = array(
                'BranchName' => $result[$i]->BranchName,
                'VendorName' => $result[$i]->VendorName,
                'TransNumber' => $result[$i]->PInvNumber,
                'PInvDate' => $result[$i]->PInvDate,
                'PInvTotalAmount' => $result[$i]->PInvTotalAmount,
                'PInvDesc' => $result[$i]->PInvDesc,
                'TransStatus' => $TransStatus,
                'CreatedBy' => $result[$i]->CreatedByName
            );
        }

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

    public function ajax_for_choose_ri() {
        $item_type = $this->input->post('item_type');
        $vendor_code = $this->input->post('vendor_code');
        //$branch_code    = $this->input->post('branch_code');

        if (!empty($item_type) && !empty($vendor_code)) {
            $result = $this->m_receive_item->get_ri_for_pi($vendor_code, $item_type);
//            echo $this->db->last_query(); die();

            if (!empty($result)) {
                echo json_encode($result);
            } else {
                echo '[]';
            }
        } else {
            echo '[]';
        }
    }

    public function ajax_for_choose_adv() {
        $item_type = $this->input->post('item_type');
        $vendor_code = $this->input->post('vendor_code');
        //$branch_code    = $this->input->post('branch_code');
        if (!empty($item_type) && !empty($vendor_code)) {
            $result = $this->m_receive_item->get_ri_for_pi_adv($vendor_code, $item_type);
//            echo $this->db->last_query(); die();

            if (!empty($result)) {
                echo json_encode($result);
            } else {
                echo '[]';
            }
        } else {
            echo '[]';
        }
    }

    public function ajax_item() {
        $pord_number = $this->input->post('POrdNumber');

        if (!empty($pord_number)) {
            $result = $this->m_receive_item->get_detail_item_for_pi($pord_number);
            echo json_encode($result);
//            echo $this->db->last_query(); die();
        } else {
            echo '[]';
        }
    }

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

        if (!empty($id)) {
            echo json_encode($this->m_purchase_invoice->get_detail_item($id));
        } else {
            echo '[]';
        }
    }

    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();
    }

    public function get_pinv_number() {
        $date = $this->input->post('date') == '' ? date('d-m-Y') : $this->input->post('date');
        $pinv_number = $this->m_purchase_invoice->create_pi_number($date);

        $result['status'] = true;
        $result['number'] = $pinv_number;

        echo json_encode($result);
    }

}
