<?php

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

class Purchases_return extends CI_Controller {

    public $menu_id = 171;
    public $code = "Purchase Return Number";
    public $name = "Purchase Return";
    public $menu_model = array('m_purchase_return', 'm_purchase_invoice', 'm_purchase_order',
        'm_taxes', 'm_vendors', 'm_account_journal', 'm_inventories', 'm_purchase_payment');
    public $app1 = array("MGR", "SPV");
    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('message');
        $this->load->helper('status');
        $this->load->helper('convert_date');
        $this->load->helper('custom_string_helper');
        $this->load->helper('approval');
		$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_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $data['list_vendor'] = $this->m_purchase_order->get_all_vendor();

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

    public function add() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');
                    $data['menu_id'] = $this->menu_id;
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['pret_number'] = $this->m_purchase_return->create_pret_number();

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

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

    public function insert() {
        @$AssetAmount = array();
        @$AssetCategory = array();
        $CategoryCodeAmount = array();
        $CategoryCodeType = array();
        $CategoryIDPPn10 = array();
        $CategoryIDPPh22 = array();
        $CategoryCodeTypePajak = array();

        $branch_code = $this->session->userdata('branch');
        $vendor_code = $this->input->post('cbg_vendor');
        $vendor_address = $this->input->post('txa_address');
        $description = $this->input->post('txa_description');

        $pret_date = $this->input->post('txt_pret_date');
        $pret_number = $this->m_purchase_return->create_pret_number($pret_date);
        $pinv_number = $this->input->post('txt_pinv_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');
        $taxes_status = $this->input->post('hdn_taxes_status');
        $intax_status = $this->input->post('hdn_intax_status');

        $pret_ppn10_val = $this->input->post('txt_ppn10_hide');
        $pret_pph22_val = $this->input->post('txt_pph22_hide');
		
		$pret_ppn10_val_real = $this->input->post('txt_ppn10');
        $pret_pph22_val_real = $this->input->post('txt_pph22');
		
        $pret_ppn10_pcnt = $pret_ppn10_val == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');
        $pret_pph22_pcnt = $pret_pph22_val == 0 ? 0 : $this->input->post('hdn_pph22_pcnt');
        $pret_total_dp = $this->input->post('txt_total_dp') == 0 ? 0 : $this->input->post('txt_total_dp');

        $pret_sub_total = $this->input->post('txt_sub_total_hide');
        $pret_total_return = $this->input->post('txt_total_return_hide');
		
		$pret_sub_total_real = $this->input->post('txt_sub_total');
        $pret_total_return_real = $this->input->post('txt_total_return');

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

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

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

            foreach ($detail as $row_check) {
                $get_invoice_detail = $this->m_purchase_return->get_invoice_detail($row_check->PInvDetailID);
                if ($get_invoice_detail->ReturnQty > $get_invoice_detail->ItemQty) {
                    $result['status'] = false;
                    $result['message'] = "Transaksi gagal, Item Code dengan " . $get_invoice_detail->ItemCode . ", Qty Return sudah melebihi Qty Invoice, Qty Return = " . $get_invoice_detail->ReturnQty . ", Qty Invoice = " . $get_invoice_detail->ItemQty . "";
                    echo json_encode($result);
                    $this->db->trans_rollback();
                    die();
                }

                if ($row_check->ItemStatus == 0) {
                    $get_inventories = $this->m_inventories->get_inventories($row_check->ItemCode);

                    if ($get_inventories->LockStatus == 1) {
                        $result['status'] = false;
                        $result['message'] = "Maaf transaksi gagal di approve, item " . $get_inventories->ItemCode . " sedang proses adjustment, silahkan approve kembali setelah proses adjustment selesai";
                        echo json_encode($result);
                        $this->db->trans_rollback();
                        die();
                    } else if ($get_inventories->ItemQty < $row_check->Item_Qty) {
                        $result['status'] = false;
                        $result['message'] = "Maaf transaksi gagal, item " . $get_inventories->ItemCode . " jumlah qty di inventory tidak cukup, Qty Inventory = " . $get_inventories->ItemQty . " Qty Return = " . $row_check->Item_Qty . "";
                        echo json_encode($result);
                        $this->db->trans_rollback();
                        die();
                    }
                } else if ($row_check->ItemStatus == 3) {
                    $get_recur_detail = $this->m_purchase_return->get_recur_detail($pinv_number, $row_check->ItemDesc);
                    if ($get_recur_detail->PaymentAmount > 0) {
                        $result['status'] = false;
                        $result['message'] = "Maaf transaksi gagal di buat, item " . $row_check->ItemCode . " Sudah digunakan untuk Adv.Payment";
                        echo json_encode($result);
                        $this->db->trans_rollback();
                        die();
                    }
                }
            }

            $data = array(
                'BranchCode' => $branch_code,
                'VendorCode' => $vendor_code,
                'PRetDate' => date("Y-m-d", strtotime($pret_date)),
                'PRetNumber' => $pret_number,
                'PInvDate' => date("Y-m-d", strtotime($pinv_date)),
                'PInvNumber' => $pinv_number,
                'VendorAddress' => $vendor_address,
                'CurrencyCode' => $currency_code,
                'CurrencyRate' => $currency_rate,
                'FiscalRate' => $fiscal_rate,
                'PRetDesc' => $description,
                'PRetSubTotal' => $pret_sub_total,
                'PRetPPn10Pcnt' => $pret_ppn10_pcnt,
                'PRetPPh22Pcnt' => $pret_pph22_pcnt,
                'PRetPPn10' => $pret_ppn10_val,
                'PRetPPh22' => $pret_pph22_val,
                'PRetTotalAmount' => $pret_total_return,
                'PRetTotalDP' => $pret_total_dp,
                'PRetTaxesStatus' => $taxes_status,
                'PRetInTaxStatus' => $intax_status,
                'TransStatus' => 4,
                'CreatedBy' => $this->session->userdata("username"),
                'CreatedAt' => date('Y-m-d'),
                'LastUser' => $this->session->userdata("username")
            );

            //1. insert into table Purhcase Return
            $this->m_purchase_return->insert($data);
            //---------------------------------------------------------------------------------------------------------//

            foreach ($detail as $row) {
                $detail_data = array(
                    'PInvDetailID' => $row->PInvDetailID,
                    'PInvNumber' => $pinv_number,
                    'PRecNumber' => $row->PRecNumber,
                    'PRetNumber' => $pret_number,
                    'ItemCode' => $row->ItemCode,
                    'ItemDesc' => $row->ItemDesc,
                    'ItemDiscPcnt' => $row->ItemDisc,
                    'InvoiceQty' => $row->InvoiceQty,
                    'ItemQty' => $row->Item_Qty,
                    'ItemUnit' => $row->ItemUnit,
                    'ItemPrice' => $row->ItemPrice_Hide,
                    'ItemAmount' => $row->Item_Amount,
                    'ItemTaxPPn10' => $row->Item_TaxPPn10,
                    'ItemTaxPPh22' => $row->Item_TaxPPh22,
                    'ItemTotalAmount' => $row->Item_TotalAmount,
                    'ItemCategoryID' => $row->ItemCategoryID,
                    'ItemCategoryCode' => $row->ItemCategoryCode,
                    'ItemAssetStatus' => $row->ItemAssetStatus,
                    'ItemAssetCode' => $row->ItemAssetCode,
                    'ItemPPh22Status' => $row->ItemPPh22Status,
                    'LastUser' => $this->session->userdata("username")
                );

                //2. insert detail into table PRetDetail
                $this->m_purchase_return->insert_detail($detail_data);
                //---------------------------------------------------------------------------------------------------------//


                @$AssetAmount[$row->ItemCategoryCode] += $row->Item_TotalAmount;
                @$AssetCategory[$row->ItemAssetStatus] = $row->ItemCategoryID;
                @$CategoryCodeAmount[$row->ItemCategoryID] += $row->Item_Amount;
                @$CategoryCodeType[$row->ItemCategoryID] = $row->ItemType;
                @$CategoryIDPPn10[$row->ItemCategoryID] += $row->Item_TaxPPn10;
                @$CategoryIDPPh22[$row->ItemCategoryID] += $row->Item_TaxPPh22;
                @$CategoryCodeTypePajak[$row->ItemCategoryID] = $row->ItemType;
            }

            //3. Update PurchaseInvoice for LockedStatus is 1
            $data_pinv_header = array(
                'LockedStatus' => 1,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_invoice->update($data_pinv_header, $pinv_number);
            //-------------------------------------------------------------------------------------------------------------//
            $this->insert_journal($pret_total_return, $pret_total_return_real, $pret_sub_total_real, $pret_ppn10_val_real, $pret_pph22_val_real, $detail, $CategoryCodeTypePajak, $CategoryIDPPh22, $CategoryIDPPn10, $fiscal_rate, $currency_code, $pret_sub_total, $AssetAmount, $AssetCategory, $CategoryCodeAmount, $CategoryCodeType, $currency_code, $pret_ppn10_val, $currency_rate, $pret_number, $pret_date, $description, $pret_pph22_val);

            /* =============================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, $pret_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, $pret_number);
            }
            /* ==================================end====================================================== */
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'insert', 0, "$pret_number");
        }

        echo json_encode($result);
    }

    function insert_journal($pret_total_return,$pret_total_return_real, $pret_sub_total_real, $pret_ppn10_val_real, $pret_pph22_val_real, $detail, $CategoryCodeTypePajak, $CategoryIDPPh22, $CategoryIDPPn10, $fiscal_rate, $currency_code, $pret_sub_total, $AssetAmount, $AssetCategory, $CategoryCodeAmount, $CategoryCodeType, $currency_code, $pret_ppn10_val, $currency_rate, $pret_number, $pret_date, $description, $pret_pph22_val) {
        /*
          Journal Adv Payment dan Jasa
         */
        $payable_value_journal = 0;
        $payable_currency_curr = 0;
        $return_amount = 0;
        $return_currency = 0;
		
		$AdvanceAccount = $this->m_account_journal->get_sys_purchase_account('AdvancePurchase', $currency_code); // Uang Muka Category -> 1-4-03-001-00                            
		if ($AdvanceAccount == false) {
			$this->trans_rollback('journal', 'Advance Purchase', '');
		}

		$advance_amount = $currency_code == 'IDR' ? doubleval($pret_total_return_real) : ((doubleval($pret_sub_total_real) * $currency_rate) + (doubleval($pret_ppn10_val_real) * $fiscal_rate) + (doubleval($pret_pph22_val_real) * $fiscal_rate));
		$advance_currency = $currency_code == 'IDR' ? doubleval($pret_total_return_real) : (doubleval($pret_sub_total_real) + doubleval($pret_ppn10_val_real) + doubleval($pret_pph22_val_real));

		$journal_advance = array(
			'PRetDate' => date("Y-m-d", strtotime($pret_date)),
			'PRetNumber' => $pret_number,
			'PRetDesc' => $description,
			'PRetAccountNumber' => $AdvanceAccount->AccountNumber,
			'PRetSaldoDebet' => $advance_amount,
			'PRetSaldoCredit' => 0,
			'AmountCurrency' => $advance_currency,
			'PRetSignStatus' => 0,
			'ItemCategoryID' => 'Hutang Dagang',
			'LastUser' => $this->session->userdata("username")
		);

		$this->m_purchase_return->insert_journal($journal_advance);
		
			
        foreach ($detail as $row_detail) {

            if ($row_detail->ItemType == 0) {
                $ReturnAccount = $this->m_account_journal->get_cat_item_account('Inventory', $row_detail->ItemCategoryID, 'IDR');
                if ($ReturnAccount == false) {
                    $this->trans_rollback('journal', 'Inventory Account', '');
                }
                $Sign_status = 1;
            } else {
                if ($row_detail->ItemType == 1) {
                    $ReturnAccount = $this->m_account_journal->get_sys_service_account('Expense', 'IDR', $row_detail->ItemCategoryID); // PPh Jasa / Service                
                    if ($ReturnAccount == false) {
                        $this->trans_rollback('preference', 'Purchase Expense', '');
                    }
                    $category_name = 'Hutang Expense';
                    $Sign_status = 1;
                } else {
                    $ReturnAccount = $this->m_account_journal->get_sys_advance_account('Advance', 'IDR', $row_detail->ItemCategoryID); // Adv. Payment
                    if ($ReturnAccount == false) {
                        $this->trans_rollback('preference', 'UnBilled,Adv. Payment', '');
                    }
                    $category_name = 'Hutang Advance';
                    $Sign_status = 1;
                }
            }

            $get_journal_retur = $this->m_purchase_return->get_journal_hutang_dagang($ReturnAccount->AccountNumber, $pret_number);
			
			$return_amount = $currency_code == 'IDR' ? doubleval($row_detail->Item_Amount) : doubleval($row_detail->Item_Amount) * $currency_rate;
            $return_currency = doubleval($row_detail->Item_Amount);
				
            if (empty($get_journal_retur->PRetAccountNumber)) {
                $journal_return = array(
                    'PRetDate' => date("Y-m-d", strtotime($pret_date)),
                    'PRetNumber' => $pret_number,
                    'PRetDesc' => $description,
                    'PRetAccountNumber' => $ReturnAccount->AccountNumber,
                    'PRetSaldoDebet' => 0,
                    'PRetSaldoCredit' => $return_amount,
                    'AmountCurrency' => $return_currency,
                    'PRetSignStatus' => $Sign_status,
                    'ItemCategoryID' => 'Retur Pembelian',
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_return->insert_journal($journal_return);
            } else {
                $return_amount = $return_amount + $get_journal_retur->PRetSaldoCredit;
                $return_currency = $return_currency + $get_journal_retur->AmountCurrency;

                $journal_return = array(
                    'PRetSaldoDebet' => 0,
                    'PRetSaldoCredit' => $return_amount,
                    'AmountCurrency' => $return_currency
                );
                $this->m_purchase_return->update_journal($journal_return, $pret_number, $ReturnAccount->AccountNumber);
            }
        }

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

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

        if ($pret_ppn10_val > 0) {
            if ($currency_code == 'IDR') {
                foreach ($CategoryIDPPn10 as $key => $value) {
                    if ($CategoryCodeTypePajak[$key] == 0) {
                        $PPnAccount = $this->m_account_journal->get_sys_purchase_account('PurchaseTaxable', 'IDR'); // PPn Masukan
                        if ($PPnAccount == false) {
                            $this->trans_rollback('preference', 'PPn,Purchase', '');
                        }
                    } else {
                        if ($CategoryCodeTypePajak[$key] == 1) {
                            $PPnAccount = $this->m_account_journal->get_sys_service_account('PurchaseTaxable', 'IDR'); // Jasa / Service
                            if ($PPnAccount == false) {
                                $this->trans_rollback('preference', 'Purchase Taxable,PPn 10', '');
                            }
                        } else {
                            $PPnAccount = $this->m_account_journal->get_sys_advance_account('PurchaseTaxable', 'IDR'); // Adv
                            if ($PPnAccount == false) {
                                $this->trans_rollback('preference', 'Purchase 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(
                        'PRetDate' => date("Y-m-d", strtotime($pret_date)),
                        'PRetNumber' => $pret_number,
                        'PRetDesc' => $description,
                        'PRetAccountNumber' => $PPnAccount->AccountNumber,
                        'PRetSaldoDebet' => 0,
                        'PRetSaldoCredit' => $taxppn_value,
                        'AmountCurrency' => $tax_currency,
                        'PRetSignStatus' => 1,
                        'ItemCategoryID' => $key,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $get_journal_retur = $this->m_purchase_return->get_journal_hutang_dagang($PPnAccount->AccountNumber, $pret_number);

                    if (empty($get_journal_retur->PRetAccountNumber)) {
                        $this->m_purchase_return->insert_journal($journal_taxppn10);
                    } else {
                        $taxppn_value = $taxppn_value + $get_journal_retur->PRetSaldoCredit;
                        $tax_currency = $tax_currency + $get_journal_retur->AmountCurrency;

                        $journal_update_ppn = array(
                            'PRetSaldoDebet' => 0,
                            'PRetSaldoCredit' => $taxppn_value,
                            'AmountCurrency' => $tax_currency
                        );
                        $this->m_purchase_return->update_journal($journal_update_ppn, $pret_number, $PPnAccount->AccountNumber);
                    }
					
					@$SumPpn += $taxppn_value;
                }
            }
        }
        /* =======================End============================================================================ */

        //8. Insert Journal PPh22 Import pada Debet                    
        if (($pret_pph22_val > 0)) {
            $taxpph22_value = 0;
            $taxpph22_currency = 0;
			
			$PPh22Account = $this->m_account_journal->get_sys_item_account('TaxablePPH22'); // PPn Import
			if ($PPh22Account == false) {
				$this->trans_rollback('preference', 'PPh22,Item', '');
			}
					
			
			$get_journal_retur = $this->m_purchase_return->get_journal_hutang_dagang($PPh22Account->AccountNumber, $pret_number);

			$taxpph22_value = $currency_code == 'IDR' ? $pret_pph22_val : doubleval($pret_pph22_val) * $fiscal_rate;
			$taxpph22_currency = $pret_pph22_val;

			if (empty($get_journal_retur->PRetAccountNumber)) {
				$journal_taxpph22 = array(
					'PRetDate' => date("Y-m-d", strtotime($pret_date)),
					'PRetNumber' => $pret_number,
					'PRetDesc' => $description,
					'PRetAccountNumber' => $PPh22Account->AccountNumber,
					'PRetSaldoDebet' => 0,
					'PRetSaldoCredit' => $taxpph22_value,
					'AmountCurrency' => $taxpph22_currency,
					'PRetSignStatus' => 1,
					'LastUser' => $this->session->userdata("username")
				);

				$this->m_purchase_return->insert_journal($journal_taxpph22);
			} else {
				$taxpph22_value = $taxpph22_value + $get_journal_retur->PRetSaldoCredit;
				$taxpph22_currency = $taxpph22_currency + $get_journal_retur->AmountCurrency;

				$journal_taxpph22 = array(
					'PRetSaldoDebet' => 0,
					'PRetSaldoCredit' => $taxpph22_value,
					'AmountCurrency' => $taxpph22_currency
				);

				$this->m_purchase_return->update_journal($journal_taxpph22, $pret_number, $PPh22Account->AccountNumber);
			}
			
			@$SumPph = $taxpph22_value;
        }
        //---------------------------------------------------------------------------------------------------------//

        /* ================7. Insert Journal PPn Masukan pada Fiscal ==================================================== */
        if ($pret_ppn10_val > 0) {
            $taxppn_value = 0;
            $tax_currency = 0;
            $sum_tax_total = 0;
            if ($currency_code != 'IDR') {
                foreach ($CategoryIDPPn10 as $key => $value) {
                    $PPnAccount = $this->m_account_journal->get_account_name('PPN Masukan'); // 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(
                        'PRetDate' => date("Y-m-d", strtotime($pret_date)),
                        'PRetNumber' => $pret_number,
                        'PRetDesc' => $description,
                        'PRetAccountNumber' => $PPnAccount->AccountNumber,
                        'PRetSaldoDebet' => 0,
                        'PRetSaldoCredit' => $taxppn_value,
                        'AmountCurrency' => $tax_currency,
                        'PRetSignStatus' => 1,
                        'ItemCategoryID' => $key,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $get_journal_retur = $this->m_purchase_return->get_journal_hutang_dagang($PPnAccount->AccountNumber, $pret_number);
                    if (empty($get_journal_retur->PRetAccountNumber)) {
                        $this->m_purchase_return->insert_journal($journal_taxppn10);
                    } else {
                        $taxppn_value = $taxppn_value + $get_journal_retur->PRetSaldoCredit;
                        $tax_currency = $tax_currency + $get_journal_retur->AmountCurrency;

                        $journal_update_ppn = array(
                            'PRetSaldoDebet' => 0,
                            'PRetSaldoCredit' => $taxppn_value,
                            'AmountCurrency' => $tax_currency
                        );
                        $this->m_purchase_return->update_journal($journal_update_ppn, $pret_number, $PPnAccount->AccountNumber);
                    }

                    $sum_tax_total += $value * $fiscal_rate;
					@$SumPpn += $taxppn_value;
                }
            }
        }
        /* =======================End============================================================================ */
		
		/*
			Beban Pembulatan Auto
		*/
		$SumPersediaan = $pret_sub_total * $currency_rate;
		$SumPersediaan_Beban 			= empty($SumPersediaan) ? 0 : $SumPersediaan;
		$SumPpn_Beban 	= empty($SumPpn) ? 0 : $SumPpn;
		$SumPph_Beban 	= empty($SumPph) ? 0 : $SumPph;
		
		$Total_all_amount 	= (($advance_amount) - ($SumPersediaan_Beban + $SumPpn_Beban + $SumPph_Beban));
		
		if(($pret_total_return - $pret_total_return_real) != 0){
			if($pret_total_return < $pret_total_return_real){
				$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
				if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $txt_currency_code);}
				
				$journal_beban    = array(
					'PRetDate' => date("Y-m-d", strtotime($pret_date)),
					'PRetNumber' => $pret_number,
					'PRetDesc' => $description,
					'PRetAccountNumber' => $BebanAccountAuto->AccountNumber,
					'PRetSaldoDebet' => 0,
					'PRetSaldoCredit' => abs($Total_all_amount),
					'AmountCurrency' => 0,
					'PRetSignStatus' => 1,
					'LastUser' => $this->session->userdata("username")
				);
				
				$this->m_purchase_return->insert_journal($journal_beban);
			}
			else{
				$BebanAccountAuto   = $this->m_account_journal->get_account_name('Beban Pembulatan'); 
				if($BebanAccountAuto == false) {$this->trans_rollback('journal','Beban Pembulatan', $txt_currency_code);}
				
				$journal_beban    = array(
					'PRetDate' => date("Y-m-d", strtotime($pret_date)),
					'PRetNumber' => $pret_number,
					'PRetDesc' => $description,
					'PRetAccountNumber' => $BebanAccountAuto->AccountNumber,
					'PRetSaldoDebet' => abs($Total_all_amount),
					'PRetSaldoCredit' => 0,
					'AmountCurrency' => 0,
					'PRetSignStatus' => 0,
					'LastUser' => $this->session->userdata("username")
				);
				
				$this->m_purchase_return->insert_journal($journal_beban);
			}
		}
		
        //7. Journal Advance Purchase Account - Uang Muka Pembelian
        //---------------------------------------------------------------------------------------------------------//
    }

    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_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

                    $id = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());
                    $data['detail'] = $this->m_purchase_return->get_detail($id);
                    //        echo $this->db->last_query();
                    //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');

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

    public function update() {
//        $branch_code        = $this->session->userdata("branch");
//        $vendor_code        = $this->input->post("cmb_vendor");

        @$AssetAmount = array();
        @$AssetCategory = array();
        $CategoryCodeAmount = array();
        $CategoryCodeType = array();
        $CategoryIDPPn10 = array();
        $CategoryIDPPh22 = array();
        $CategoryCodeTypePajak = array();

        $pinv_number = $this->input->post('txt_pinv_no');
        $pret_number = $this->input->post("txt_pret_no");
        $pret_date = date("Y-m-d", strtotime($this->input->post("txt_pret_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');

        $pret_sub_total = $this->input->post("txt_sub_total_hide");
		$pret_sub_total_real = $this->input->post("txt_sub_total");
		
        $pret_ppn10_val = $this->input->post("txt_ppn10_hide");
        $pret_pph22_val = $this->input->post("txt_pph22_hide");
		
		$pret_ppn10_val_real = $this->input->post("txt_ppn10");
        $pret_pph22_val_real = $this->input->post("txt_pph22");
		
        $pret_total_return = $this->input->post("txt_total_return_hide");
		$pret_total_return_real = $this->input->post("txt_total_return");
		
        $taxes_status = $this->input->post('hdn_taxes_status');
        $intax_status = $this->input->post('hdn_intax_status');

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

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

//        print_r($detail);

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

            foreach ($detail as $row_check) {
                $get_invoice_detail = $this->m_purchase_return->get_invoice_detail($row_check->PInvDetailID);
                if ($get_invoice_detail->ReturnQty > $get_invoice_detail->ItemQty) {
                    $result['status'] = false;
                    $result['message'] = "Transaksi gagal, Item Code dengan " . $get_invoice_detail->ItemCode . ", Qty Return sudah melebihi Qty Invoice, Qty Return = " . $get_invoice_detail->ReturnQty . ", Qty Invoice = " . $get_invoice_detail->ItemQty . "";
                    echo json_encode($result);
                    $this->db->trans_rollback();
                    die();
                }

                if ($row_check->ItemStatus == 0) {
                    $get_inventories = $this->m_inventories->get_inventories($row_check->ItemCode);
                    if ($get_inventories->LockStatus == 1) {
                        $result['status'] = false;
                        $result['message'] = "Maaf transaksi gagal, item " . $get_inventories->ItemCode . " sedang proses adjustment, silahkan approve lagi setelah proses adjustment selesai";
                        echo json_encode($result);
                        $this->db->trans_rollback();
                        die();
                    } else if ($get_inventories->ItemQty < $row_check->Item_Qty) {
                        $result['status'] = false;
                        $result['message'] = "Maaf transaksi gagal, item " . $get_inventories->ItemCode . " jumlah qty di inventory tidak cukup, Qty Inventory = " . $get_inventories->ItemQty . " Qty Return = " . $row_check->Item_Qty . "";
                        echo json_encode($result);
                        $this->db->trans_rollback();
                        die();
                    }
                }
            }

            $data = array(
                'PRetDesc' => $description,
                'PRetSubTotal' => $pret_sub_total,
                'PRetPPn10' => $pret_ppn10_val,
                'PRetPPh22' => $pret_pph22_val,
                'PRetTotalAmount' => $pret_total_return,
                'PRetTaxesStatus' => $taxes_status,
                'PRetInTaxStatus' => $intax_status,
                'TransStatus' => 4,
				'CurrencyRate' => $currency_rate,
				'AppFinished' => 2,
                'LastUser' => $this->session->userdata("username")
            );

            //1. insert into table Purhcase Return
            $this->m_purchase_return->update($data, $pret_number);
            //-------------------------------------------------------------------------------------------------------------//

            foreach ($detail as $row) {

                //$result_exist   = $this->m_purchase_return->check_detail_code_exist($pret_number, $row->ItemCode);
                $detail_update = array(
                    'ItemQty' => $row->Item_Qty,
                    'ItemAmount' => $row->Item_Amount,
                    'ItemTaxPPn10' => $row->Item_TaxPPn10,
                    'ItemTaxPPh22' => $row->Item_TaxPPh22,
                    'ItemTotalAmount' => $row->Item_TotalAmount,
                    'ItemDiscPcnt' => $row->ItemDisc,
                    'ItemAssetCode' => $row->ItemAssetCode,
                    'LastUser' => $this->session->userdata("username")
                );

                //2. update detail into table PRetDetail
                $this->m_purchase_return->update_detail($detail_update, $row->PRetDetailID);
                //--------------------------------------------------------------------------------------------------//

                if ($currency_code == 'IDR') {
                    @$AssetAmount[$row->ItemCategoryCode] += $row->Item_TotalAmount;
                } else {
                    @$AssetAmount[$row->ItemCategoryCode] += $row->Item_Amount;
                }

                @$AssetCategory[$row->ItemAssetStatus] = $row->ItemCategoryID;
                @$CategoryCodeAmount[$row->ItemCategoryID] += $row->Item_Amount;
                @$CategoryCodeType[$row->ItemCategoryID] = $row->ItemType;
                @$CategoryIDPPn10[$row->ItemCategoryID] += $row->Item_TaxPPn10;
                @$CategoryIDPPh22[$row->ItemCategoryID] += $row->Item_TaxPPh22;
                @$CategoryCodeTypePajak[$row->ItemCategoryID] += $row->ItemType;
            }

            if (count($detail_id) > 0) {
                foreach ($detail_id as $PRetDetailID) {
                    $this->m_purchase_return->delete_detail_by_id($PRetDetailID);
                }
            }
            //4. Update PurchaseInvoice for LockedStatus is 1
            $data_pinv_header = array(
                'LockedStatus' => 1,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_invoice->update($data_pinv_header, $pinv_number);
            //-------------------------------------------------------------------------------------------------------------//
            //5. Delete Journal untuk purchase return
            $this->m_purchase_return->delete_journal($pret_number);
            //-------------------------------------------------------------------------------------------------------------//
            $this->insert_journal($pret_total_return,$pret_total_return_real, $pret_sub_total_real, $pret_ppn10_val_real, $pret_pph22_val_real, $detail, $CategoryCodeTypePajak, $CategoryIDPPh22, $CategoryIDPPn10, $fiscal_rate, $currency_code, $pret_sub_total, $AssetAmount, $AssetCategory, $CategoryCodeAmount, $CategoryCodeType, $currency_code, $pret_ppn10_val, $currency_rate, $pret_number, $pret_date, $description, $pret_pph22_val);


            /* =============================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, $pret_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, $pret_number);
            }
            /* ==================================end====================================================== */
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'update', 0);
        }

        echo json_encode($result);
    }
	
	function reverse_data_detail() {
        try {
            $txt_pret_no = $this->input->post('txt_pret_no');
			$txt_pinv_no = $this->input->post('txt_pinv_no');
			$txt_currency_rate = $this->input->post('txt_currency_rate');
			
			$detail_post = $this->input->post('detail');
            $detail 	 = json_decode($detail_post);
			$branch_code = $this->session->userdata("branch");
			/*
				Check End Periode
			*/
			$date_transaction 	= check_end_periode($txt_pret_no);
			
			$get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);
			if ($get_end_periode) {
                throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
            }
			
			foreach($detail as $row_detail){
				$ItemCode 		 = $row_detail->ItemCode;
				$item_asset_code = $row_detail->ItemAssetCode;
				$ItemDesc 		 = $row_detail->ItemDesc;
				$item_amount_value = $row_detail->Item_Amount;
				/*
					Check Item Type
					
				*/
				if ($row_detail->ItemType == 0) {
					/*
                      Check Adjustment
                     */
                    $item_lock_status = $this->m_inventories->get_inventori_by_item($ItemCode, $branch_code);
                    if ($item_lock_status->LockStatus == 1) {
                        throw new Exception(('Tidak bisa dilakukan proses Reverse, karena item ' . $row_detail->ItemCode . ' pada listing sedang dilakukan proses Adjustment')); //item adjust
                    }
                    /* =================END============================== */
					
					//3. Update Return Qty at Inventories
					$get_inventories = $this->m_inventories->get_inventories($ItemCode);
					$item_qty = $get_inventories->ItemQty;
					$item_average = $get_inventories->ItemAverage;
					$old_item_value = $get_inventories->ItemValue;

					$new_itemqty = $item_qty + $row_detail->Item_Qty;
					$new_item_average = doubleval(($old_item_value + ($item_amount_value * $txt_currency_rate)) / $new_itemqty);

					$new_itemvalue = $new_itemqty * $new_item_average;

					$data_inventories = array(
						'ItemQty' => $new_itemqty,
						'ItemValue' => $new_itemvalue,
						'ItemAverage' => $new_item_average,
						'LastUser' => $this->session->userdata("username")
					);
					
					$this->transaction['update_inventory']['data'][] = $data_inventories;
                    $this->transaction['update_inventory']['ItemCode'][] = $ItemCode;
						
					if($row_detail->ItemStatus == 1){
						if ($item_asset_code != "") {
                            $asset_code = explode(',', $item_asset_code);

                            foreach ($asset_code as $row_asset) {
                                $data_inventdetail = array(
                                    'ItemQty' => 1,
                                    'SoldStatus' => 0,
                                    'LastUser' => $this->session->userdata("username")
                                );
								$this->transaction['update_assset_code']['data'][] = $data_inventdetail;
                    			$this->transaction['update_assset_code']['AssetCode'][] = $row_asset;
                            }
                        }
					}
				}
				else if($row_detail->ItemType == 2){
					/*
					  Delete recur detai for adv.payment
					 */
					$data_recur = array(
						'SoldStatus' => 1
					);
					$this->transaction['update_data_recur']['data'][] = $data_recur;
                    $this->transaction['update_data_recur']['PInvNumber'][] = $txt_pinv_no;
					$this->transaction['update_data_recur']['ItemDesc'][] = $ItemDesc;
				}
				
				//2. Update Return QTY and Return Status at PInvDetail
				$data_pinvdetail = array(
					'ReturnQty' => $row_detail->PInvReturnQty - $row_detail->Item_Qty,
					'ReturnStatus' => 0,
					'LastUser' => $this->session->userdata("username")
				);
				
				$this->transaction['update_qty_invoice']['data'][] = $data_pinvdetail;
                $this->transaction['update_qty_invoice']['PInvDetailID'][] = $row_detail->PInvDetailID;
			}
			
			$get_sordetail_dp = $this->m_purchase_return->get_detail_invoice($txt_pret_no);
			if(!empty($get_sordetail_dp->Invoice_Number)){
				$NoSalesReceipt = $get_sordetail_dp->PPayNumber;
				throw new Exception(('Tidak bisa dilakukan proses Reverse, karena Down Payment dari no transaksi ' . $txt_pret_no . ' sudah dipakai di Sales Receipts'. $NoSalesReceipt .', silahkan Reverse terlebih dahulu Purchase Payment')); //item adjust
			}
			
			$this->transaction['delete_pordetaildp']['PPayNumber'] = $txt_pret_no;
			
			//5. Update Purchase Return for status only
			$data_purch_return = array(
				'TransStatus' => 4,
				'AppFinished' => 0,
				'AppLevel1Status' => 0,
				'AppLevel1Code' => NULL,
				'AppLevel1Date' => NULL,
				'LastUser' => NULL
			);
			
			$this->transaction['update_group_return']['data'] = $data_purch_return;
            $this->transaction['update_group_return']['PRetNumber'] = $txt_pret_no;
			
			 //6. Update Purchase invoice for locked status is 0
			$data_pinv_header = array(
				'LockedStatus' => 1,
				'LastUser' => $this->session->userdata("username")
			);
			
			$this->transaction['update_group_invoice']['data'] = $data_pinv_header;
            $this->transaction['update_group_invoice']['PInvNumber'] = $txt_pinv_no;
			//-----------------------------------------------------------------------------------------------------------//
			
			$result_approve = $this->m_purchase_return->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_pret_no);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_pret_no);
            }
            /* ==================================end====================================================== */
			echo json_encode($result);
            
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }
	
    public function approval() {
        if (in_array($this->session->userdata("jobtitle_status"), $this->jobtitle_status)) {
            $detail_post = $this->input->post('Detail');
            $detail = json_decode($detail_post);

            if (count($detail) > 0) {
                $this->db->trans_begin();
                $branch_code = $this->session->userdata('branch');
                $vendor_code = $this->input->post('VendorCode');

                $pret_number = $this->input->post('PRetNumber');
                $pinv_number = $this->input->post('PInvNumber');
                $total_return = $this->input->post('TotalReturn');
                $CurrencyRate = $this->input->post('CurrencyRate');
                $CurrencyCode = $this->input->post('CurrencyCode');
                $FiscalRate = $this->input->post('FiscalRate');
                $SubTotal = $this->input->post('SubTotal');
                $Ppn10 = $this->input->post('Ppn10');
                $Pph22 = $this->input->post('Pph22');
				
				$SubTotal_real = $this->input->post('SubTotal_real');
				$TotalReturn_real = $this->input->post('TotalReturn_real');

                foreach ($detail as $row_check) {
                    $get_invoice_detail = $this->m_purchase_return->get_invoice_detail($row_check->PInvDetailID);
                    $TotalQtyReturn = $get_invoice_detail->ReturnQty + $row_check->Item_Qty;
                    //Qty lama ditambah Qty baru
                    if ($TotalQtyReturn > $get_invoice_detail->ItemQty) {
                        $result['status'] = false;
                        $result['message'] = "Transaksi gagal, Item Code dengan " . $get_invoice_detail->ItemCode . ", Qty Return sudah melebihi Qty Invoice, Qty Return = " . $TotalQtyReturn . ", Qty Invoice = " . $get_invoice_detail->ItemQty . "";
                        echo json_encode($result);
                        die();
                    }

                    if ($row_check->ItemType == 0) {
                        $get_inventories = $this->m_inventories->get_inventories($row_check->ItemCode);

                        if ($get_inventories->LockStatus == 1) {
                            $result['status'] = false;
                            $result['message'] = "Maaf transaksi gagal di approve, item " . $get_inventories->ItemCode . " sedang proses adjustment, silahkan approve lagi setelah proses adjustment selesai";
                            echo json_encode($result);
                            $this->db->trans_rollback();
                            die();
                        } else if ($get_inventories->ItemQty < $row_check->Item_Qty) {
                            $result['status'] = false;
                            $result['message'] = "Maaf transaksi gagal di approve, item " . $get_inventories->ItemCode . " jumlah qty di inventory tidak cukup, Qty Inventory = " . $get_inventories->ItemQty . " Qty Return = " . $row_check->Item_Qty . "";
                            echo json_encode($result);
                            $this->db->trans_rollback();
                            die();
                        }
                    } else if ($row_check->ItemType == 2) {
                        $get_recur_detail = $this->m_purchase_return->get_recur_detail($pinv_number, $row_check->ItemDesc);
                        if ($get_recur_detail->PaymentAmount > 0) {
                            $result['status'] = false;
                            $result['message'] = "Maaf transaksi gagal di approve, item " . $row_check->ItemCode . " Sudah digunakan untuk Adv.Payment";
                            echo json_encode($result);
                            $this->db->trans_rollback();
                            die();
                        }
                    }
                }


                //1. Update Vendor For New DP by Return Purchase
                $vendor_saldo = $this->m_vendors->get_saldo_by_id($vendor_code);
                $saldo_dp_balance = doubleval($vendor_saldo[0]->SaldoDPBalance) + doubleval($total_return);

                $data_vendor_saldo = array(
                    'SaldoDPBalance' => $saldo_dp_balance,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_vendors->update($data_vendor_saldo, $vendor_code, $branch_code);
                //-------------------------------------------------------------------------------------------------------//
                $CategoryIDAmt = array();
                $CategoryIDCode = array();
                $CategoryIDAsset = array();

                foreach ($detail as $row) {

                    $item_asset_status = $row->ItemAssetStatus;
                    $item_asset_code = $row->ItemAssetCode;
                    $item_amount_value = $row->Item_Amount;

                    //2. Update Return QTY and Return Status at PInvDetail
                    $data_pinvdetail = array(
                        'ReturnQty' => $row->PInvReturnQty + $row->Item_Qty,
                        'ReturnStatus' => 1,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $this->m_purchase_invoice->update_detail($data_pinvdetail, $row->PInvDetailID);
                    //------------------------------------------------------------------------------------------------//                  

                    if ($row->ItemType == 0) {
                        //3. Update Return Qty at Inventories
                        $get_inventories = $this->m_inventories->get_inventories($row->ItemCode);
                        $item_qty = $get_inventories->ItemQty;
                        $item_average = $get_inventories->ItemAverage;
                        $old_item_value = $get_inventories->ItemValue;

                        $new_itemqty = $item_qty - $row->Item_Qty;
                        $new_item_average = doubleval(($old_item_value - ($item_amount_value * $CurrencyRate)) / $new_itemqty);

                        $new_itemvalue = $new_itemqty * $new_item_average;

                        $data_inventories = array(
                            'ItemQty' => $new_itemqty,
                            'ItemValue' => $new_itemvalue,
                            'ItemAverage' => $new_item_average,
                            'LastUser' => $this->session->userdata("username")
                        );

                        $this->m_inventories->update($data_inventories, $row->ItemCode);
                        //------------------------------------------------------------------------------------------------//                  
                        //4. Update ItemQty = 0 and SoldStatus = 3 at InventDetail

                        if ($item_asset_code != "") {
                            $asset_code = explode(',', $item_asset_code);

                            foreach ($asset_code as $row_asset) {
                                $data_inventdetail = array(
                                    'ItemQty' => 0,
                                    'SoldStatus' => 3,
                                    'LastUser' => $this->session->userdata("username")
                                );

                                $this->m_inventories->update_detail($data_inventdetail, $row_asset);
                            }
                        }
                    } else if ($row->ItemType == 2) {
                        /*
                          Delete recur detai for adv.payment
                         */
                        $data_recur = array(
                            'SoldStatus' => 2
                        );
                        $this->m_purchase_return->update_recur($data_recur, $row->ItemDesc, $pinv_number);
                    }

                    @$CategoryIDAmt[$row->ItemCategoryID] += $row->Item_Amount;
                    @$CategoryIDCode[$row->ItemCategoryID] = $row->ItemCategoryCode;
                    @$CategoryIDAsset[$row->ItemCategoryID] = $row->ItemStatus;
                }
                //-------------------------------------------------------------------------------------------------------//

                /*
                  Insert Pordeatail DP
                 */
                $item_ppn = ($CurrencyCode == 'IDR' && $Ppn10 > 0) ? ($Ppn10) : 0;
                $item_pph22 = ($CurrencyCode == 'IDR' && $Pph22 > 0) ? ($Pph22) : 0;

                $Total_amount_return = doubleval($SubTotal_real + $item_ppn + $item_pph22);
                $get_purchase_invoice = $this->m_purchase_invoice->get_purchase_invoice($pinv_number);

                $data_detail_dp = array(
                    'POrdNumber' => $get_purchase_invoice->POrdNumber,
                    'VendorCode' => $get_purchase_invoice->VendorCode,
                    'PPayNumber' => $pret_number,
                    'POrdTotalDP' => $Total_amount_return,
                    'Owing' => $Total_amount_return,
                    'CurrencyRate' => $CurrencyRate,
                    'PaymentAmount' => $Total_amount_return,
                    'SaldoDPBalance' => $Total_amount_return,
                    'PaymentDate' => date("Y-m-d"),
                    'SOrdStatus' => 1,
                    'StatusDPFor' => 1,
                    'LastUser' => $this->session->userdata("username")
                );
                $this->m_purchase_payment->insert_po_detail_dp($data_detail_dp);

                if ($CurrencyCode != 'IDR' && ($Ppn10 > 0)) {
                    $data_detail_dp_ppn = array(
                        'POrdNumber' => $get_purchase_invoice->POrdNumber,
                        'VendorCode' => $get_purchase_invoice->VendorCode,
                        'PPayNumber' => $pret_number,
                        'POrdTotalDP' => doubleval($Ppn10 + $Pph22),
                        'Owing' => doubleval($Ppn10 + $Pph22),
                        'CurrencyRate' => $FiscalRate,
                        'PaymentAmount' => doubleval($Ppn10 + $Pph22),
                        'SaldoDPBalance' => doubleval($Ppn10 + $Pph22),
                        'PaymentDate' => date("Y-m-d"),
                        'SOrdStatus' => 1,
                        'StatusDPFor' => 1,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $this->m_purchase_payment->insert_po_detail_dp($data_detail_dp_ppn);
                }
                /* ============================End============================================================================ */


                //5. Update Purchase Return for status only
                $data_purch_return = array(
                    'TransStatus' => 2,
                    'AppFinished' => 1,
                    'AppLevel1Status' => 1,
                    'AppLevel1Code' => $this->session->userdata("username"),
                    'AppLevel1Date' => date("Y-m-d"),
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_return->update($data_purch_return, $pret_number);
                //-----------------------------------------------------------------------------------------------------------//
                //6. Update Purchase invoice for locked status is 0
                $data_pinv_header = array(
                    'LockedStatus' => 0,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_invoice->update($data_pinv_header, $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);

                    $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('approval', 1);
                }
                /* ==================================end====================================================== */
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('approval', 0);
            }

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

    public function suspend_data() {
        $pret_number = $this->input->post('id');
        $data = $this->m_purchase_return->get_detail($pret_number);

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

            //1. Update Purchase Item for status = 3 or 9
            $data_pret = array(
                'TransStatus' => 3,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_return->update($data_pret, $pret_number);
            //---------------------------------------------------------------------------------------------------------------//
            //2. Update Purchase invoice for locked status is 0
            $invoice_number = $this->m_purchase_return->get_detail($pret_number);

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

            $this->m_purchase_invoice->update($data_pinv_header, $invoice_number->PInvNumber);
            //-----------------------------------------------------------------------------------------------------------//

            /* =============================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);

                $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('suspend', 1);
            }
            /* ==================================end====================================================== */
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend', 0);
        }

        echo json_encode($result);
    }

    public function to_preview($obj_string = null) {
//        $data['list'] = $this->m_purchase_return->get_all($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['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $data['list']           = $this->m_purchase_return->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('purchase/purchase_return/v_preview_purchasereturn', $data);
        $this->load->view('v_footer');
    }
    public function to_preview_LAMA() {
        $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['list'] = $this->m_purchase_return->get_all($this->ho);

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

    public function to_print() {
        $data['menu_id'] = $this->menu_id;
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $data['list'] = $this->m_purchase_return->get_all($this->ho);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_return/v_print_purchasereturn', $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_return->get_detail_print($id);
            //echo $this->db->last_query();
            $data['list'] = $this->m_purchase_return->get_detail_item_print($data['detail']->PRetNumber, $data['detail']->PInvNumber);
            //echo $this->db->last_query();     
            $this->load->view('v_header');
            $this->load->view('purchase/purchase_return/v_print_detail_purchasereturn', $data);
            $this->load->view('v_footer');
        }
    }

    function print_preview() {
        $data['number'] = '0';
        $data['filename'] = "Purchase_return";
        //$this->load->helper('to_pdf');

        $this->load->view('purchase/purchase_return/v_print_detail_return', $data);
        //pdf_create($html, $data['filename']);
    }

    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_return->get_detail($id);
        $data['list'] = $this->m_purchase_return->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_return/v_print_journal_purchasereturn', $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_return->get_detail($id);
        $data['list'] = $this->m_purchase_return->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_return/v_preview_journal_purchasereturn', $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('PRetNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('PRetDesc', $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_purchasereturn.PRetDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_purchasereturn.PRetDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ==========================end================================================================= */

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

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

            $hasil[] = array(
                'BranchName' => $result[$i]->BranchName,
                'VendorName' => $result[$i]->VendorName,
                'TransNumber' => $result[$i]->PRetNumber,
                'PRetDate' => $result[$i]->PRetDate,
                'PInvNumber' => $result[$i]->PInvNumber,
                'PInvDate' => $result[$i]->PInvDate,
                'PRetDesc' => $result[$i]->PRetDesc,
                'TransStatus' => $TransStatus,
                'CreatedBy' => $result[$i]->CreatedBy,
            );
        }

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

    public function ajax_for_choose_pret() {
        $vendor_code = $this->input->post('VendorCode');

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

    public function ajax_for_choose_pret_adv() {
        $vendor_code = $this->input->post('VendorCode');

        if (!empty($vendor_code)) {
            echo json_encode($this->m_purchase_invoice->get_for_purchase_return_adv($vendor_code));
            //echo $this->db->last_query();
        } else {
            echo '[]';
        }
    }

    /* public function check_adv_from_detail_recur(){
      $no_transaksi = $this->input->post('no_transaksi');
      if(!empty($no_transaksi)){

      $get_recur_detail = $this->m_purchase_invoice->get_detail_recur_from_return($no_transaksi);
      if($get_recur_detail->ItemTotalAmount == $get_recur_detail->PaymentAmount){
      $result['status'] = false;
      }
      else{
      $result['status'] = true;
      }

      echo json_encode($result);
      //echo $this->db->last_query();
      }
      else{
      echo '[]';
      }
      } */

    public function ajax_for_choose_asset() {
        $item_code = $this->input->post('ItemCode');
        $RINumber = $this->input->post('RINumber');

        if (!empty($item_code)) {
            echo json_encode($this->m_inventories->get_invent_detail_for_asset($item_code, $RINumber));
//            echo $this->db->last_query(); die();
        } else {
            echo '[]';
        }
    }

    public function ajax_for_choose_item_pi() {
        $pinv_number = $this->input->post('PInvNumber');
        $item = $this->input->post('ItemType');

        if (!empty($pinv_number)) {
            if ($item == 'Item') {
                echo json_encode($this->m_purchase_invoice->get_detail_item_return($pinv_number));
            } else {
                echo json_encode($this->m_purchase_invoice->get_detail_item_adv($pinv_number));
            }
        } else {
            echo '[]';
        }
    }

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

        if (!empty($pret_number)) {
            $result = $this->m_purchase_return->get_detail_item($pret_number[0], $pret_number[1]);
            echo json_encode($result);
//            echo $this->db->last_query();
        } else {
            echo '[]';
        }
    }

    public function get_pret_number() {
        $date = $this->input->post('date') == '' ? date('d-m-Y') : $this->input->post('date');
        $pret_number = $this->m_purchase_return->create_pu_number($date);

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

        echo json_encode($result);
    }

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

}
