<?php

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

class Receive_item extends CI_Controller {

    public $menu_id = 169;
    public $name = "Receive Item";
    public $menu_model = array('m_receive_item', 'm_purchase_order', 'm_inventories', 'm_account_journal', 'm_employee', 'm_purchase_requisition');
    public $jobtitle_status = array('0', '1');
    public $branch = "";
    public $ho;
    public $transaction = array();

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

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

        $this->load->model($this->menu_model);
        $this->load->helper('regex');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->helper('convert_date');
        $this->load->helper('custom_string_helper');
		$this->load->model('login/m_login');
	
		$is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
		if($is_login){

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

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

    public function index() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');
                    $data['menu_id'] = $this->menu_id;
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

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

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

                    $this->load->view('v_header');
                    $this->load->view('purchase/receive_item/v_receive_item', $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 {
                    //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);

                    /* =============== Daswan ======================== */
                    $data['POrdNumber'] = $POrdNumber;
                    $data['VendorCode'] = $VendorCode;
                    /* =============== end Daswan ==================== */

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

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

    public function insert() {
        $CategoryIDAmt = array();
        $CategoryIDType = array();

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

        $currency_code = $this->input->post('hdn_currency_code');
        $currency_rate = $this->input->post('hdn_currency_rate');
        $vendor_do_no = $this->input->post('txt_vendor_do_no');
        $prec_date = $this->input->post('txt_prec_date');

        $prec_no = $this->m_receive_item->create_ri_number($prec_date);

        $pord_no = $this->input->post('txt_pord_no');
        $pord_date = $this->input->post('txt_pord_date');
        $shipment_date = $this->input->post('txt_ship_date');
        $txa_description = $this->input->post('txa_description');

        $fob = $this->input->post('cbo_fob') == "" ? null : $this->input->post('cbo_fob');
        $terms = $this->input->post('cbo_terms') == "" ? null : $this->input->post('cbo_terms');
        $shipment = $this->input->post('cbo_ship_via') == "" ? null : $this->input->post('cbo_ship_via');

        $ppn_value = $this->input->post('txt_ppn10');
        $ppn_pcnt = $ppn_value == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');

        $sub_total = $this->input->post('txt_sub_total');
        $total_purchase = $this->input->post('txt_total_purchase');
        $taxes_status = $this->input->post('chk_taxtable');
        $intax_status = $this->input->post('chk_inclusive');

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

        $arr_detail = array();
        $arr_detail_po = array();
        $arr_detail_pr = array();

        $arr_journal_inventory = array();
        $journal_unbilled = array();
        $ItemCategoryID = "";
        $Akun_number = "";

        $result_insert = 0;
        $inventory_value = 0;
        $inventory_value_curr = 0;

        if (count($detail) > 0) {
            $unbilled_amount = 0;
            $unbilled_status = FALSE;

            foreach ($detail as $row_check) {
                $get_data_pord_detail = $this->m_receive_item->get_detail_purchase_order_for_ri($row_check->POrdNumber, $row_check->ItemCode);

                $ItemQtyRI = $get_data_pord_detail->ItemQtyRI; //Qty Suspend sudah ditambahkan di model
                $ItemQtyPO = $get_data_pord_detail->ItemQtyPO;
                $TotalQtyRI = $row_check->ItemQty + $ItemQtyRI;

                if ($TotalQtyRI > $ItemQtyPO) {
                    $result['status'] = FALSE;
                    $result['message'] = "Transaksi gagal, Item Qty Receive Item melebihi Item Qty Purchase Order, Untuk Item " . $row_check->ItemDesc . ", Qty RI : " . $TotalQtyRI . ", Qty PO : " . $ItemQtyPO . "";
                    echo json_encode($result);
                    die();
                }
            }
            /* ======================Insert Group Function================================== */
            $data = array(
                'BranchCode' => $branch_code,
                'VendorCode' => $vendor_code,
                'PRecNumber' => $prec_no,
                'PRecDate' => date("Y-m-d", strtotime($prec_date)),
                'POrdDate' => $pord_date,
                'POrdNumber' => $pord_no,
                'VendorDONumber' => $vendor_do_no,
                'ShipmentDate' => date("Y-m-d", strtotime($shipment_date)),
                'ShipmentID' => $shipment,
                'TermsPaymentID' => $terms,
                'FOBID' => $fob,
                'CurrencyCode' => $currency_code,
                'CurrencyRate' => $currency_rate,
                'PRecDesc' => $txa_description,
                'PRecSubTotal' => $sub_total,
                'PRecPPn10Pcnt' => $ppn_pcnt,
                'PRecPPn10' => $ppn_value,
                'PRecTotalAmount' => $total_purchase,
                'PRecTaxesStatus' => $taxes_status,
                'PRecInTaxStatus' => $intax_status,
                'TransStatus' => 4,
                'AppLevel1Status' => 0,
                'CreatedBy' => $this->session->userdata("username"),
                'CreatedAt' => date('Y-m-d'),
                'LastUser' => $this->session->userdata("username")
            );

            /* ===================Insert Detail============================================== */
            foreach ($detail as $row) {

                //2. insert to table detail receive item
                $detail_data = array(
                    'POrdDetailID' => $row->POrdDetailID,
                    'POrdNumber' => $row->POrdNumber,
                    'PRecNumber' => $prec_no,
                    'ItemCode' => $row->ItemCode,
                    'ItemDesc' => $row->ItemDesc,
                    'itemUnit' => $row->ItemUnit,
                    'ItemQty' => $row->ItemQty,
                    'ItemDisc' => $row->ItemDisc,
                    'ItemPrice' => $row->ItemPrice,
                    'ItemAmount' => $row->ItemAmount,
                    'ItemTaxPPn10' => $row->ItemTaxPPn10,
                    'ItemTotalAmount' => $row->ItemTotalAmount,
                    'ItemCategoryID' => $row->ItemCategoryID,
                    'ItemCategoryCode' => $row->ItemCategoryCode,
                    'ItemType' => $row->ItemType,
                    'ItemStatus' => $row->ItemStatus,
					'ItemCodeVendor' => $row->ItemCodeVendor,
                    'LastUser' => $this->session->userdata("username")
                );

                $arr_detail[] = $detail_data;
                //$this->m_receive_item->insert_detail($detail_data);
                //----------------------------------------------------------------------------------------------//
                //3. Update ItemQTYRI pada Purchase Order Detail
                $newItemQtyRI = $row->ItemQtyRI + $row->ItemQty;

                $detail_data_po = array(
                    'POrdDetailID' => $row->POrdDetailID,
                    'ItemQtyRI' => $newItemQtyRI,
                    'LastUser' => $this->session->userdata("username")
                );

                $arr_detail_po[] = $detail_data_po;
                //$this->m_purchase_order->update_detail($detail_data_po, $row->POrdDetailID);
                //---------------------------------------------------------------------------------------------------------//
                //4. Update Qty RI Di PReq
                $get_purchase_order_on_receive = $this->m_purchase_order->get_detail_item_po($row->POrdDetailID);
                $detail_data_preq = array(
                    'PReqDetailID' => $get_purchase_order_on_receive->PReqDetailID,
                    'ItemQtyRI' => $newItemQtyRI,
                    'LastUser' => $this->session->userdata("username")
                );
                $arr_detail_pr[] = $detail_data_preq;
                //$this->m_purchase_requisition->update_detail($detail_data_preq, $get_purchase_order_on_receive->PReqDetailID);
                /* ====================END====================== */


                @$CategoryIDAmt[$row->ItemCategoryID] += $row->ItemAmount;
                @$CategoryIDCode[$row->ItemCategoryID] = $row->ItemCategoryCode;
                @$CategoryIDType[$row->ItemCategoryID] = $row->ItemType;
            }

            //4. insert journal inventory - Persesian Barang Dagang based on category

            $inventory_value = 0;
            $inventory_value_curr = 0;
            //4. insert journal inventory - Persesian Barang Dagang based on category
            foreach ($CategoryIDAmt as $key => $value) {
                if ($CategoryIDType[$key] == 0) {
                    $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');
                    if ($InventoryAccount == false) {
                        $this->trans_rollback('preference', 'Inventory', '');
                    }

                    $inventory_journal = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
                    $inventory_currency = doubleval($value);
                    $Akun_number = $InventoryAccount->AccountNumber;

                    $get_journal_receipt = $this->m_receive_item->get_journal_receive_empty($InventoryAccount->AccountNumber, $prec_no);
                    if (empty($get_journal_receipt->PRecAccountNumber)) {
                        $journal_inventory = array(
                            'PRecDate' => date("Y-m-d", strtotime($prec_date)),
                            'PRecNumber' => $prec_no,
                            'PRecDesc' => $txa_description,
                            'PRecAccountNumber' => $InventoryAccount->AccountNumber,
                            'PRecSaldoDebet' => $inventory_journal,
                            'PRecSaldoCredit' => 0,
                            'AmountCurrency' => $inventory_currency,
                            'PRecSignStatus' => 0,
                            'ItemCategoryID' => $key,
                            'LastUser' => $this->session->userdata("username")
                        );

                        $arr_journal_inventory[] = $journal_inventory;
                    } else {
                        $inventory_journal = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
                        $inventory_currency = doubleval($value);

                        $inventory_value = $inventory_journal + $get_journal_receipt->PRecSaldoDebet;
                        $inventory_value_curr = $inventory_currency + $get_journal_receipt->AmountCurrency;

                        $journal_inventory = array(
                            'PRecSaldoDebet' => $inventory_value,
                            'PRecSaldoCredit' => 0,
                            'AmountCurrency' => $inventory_value_curr,
                        );
                        $arr_journal_inventory[] = $journal_inventory;
                    }

                    $unbilled_amount += doubleval($value);
                    $unbilled_status = TRUE;
                }
            }
            //--------------------------------------------------------------------------------------------------------------//

            if ($unbilled_status) {
                $UnbilledAccount = $this->m_account_journal->get_sys_item_account('Unbilled');
                if ($UnbilledAccount == false) {
                    $this->trans_rollback('preference', 'Unbilled,Item', '');
                }

                $unbilled_journal = $currency_code == 'IDR' ? $unbilled_amount : $unbilled_amount * $currency_rate;
                $unbilled_currency = $unbilled_amount;

                $journal_unbilled = array(
                    'PRecDate' => date("Y-m-d", strtotime($prec_date)),
                    'PRecNumber' => $prec_no,
                    'PRecDesc' => $txa_description,
                    'PRecAccountNumber' => $UnbilledAccount->AccountNumber,
                    'PRecSaldoDebet' => 0,
                    'PRecSaldoCredit' => $unbilled_journal,
                    'AmountCurrency' => $unbilled_currency,
                    'PRecSignStatus' => 0,
                    'ItemCategoryID' => $key,
                    'LastUser' => $this->session->userdata("username")
                );
            }

            //'1. Input Receive Item >> at_receiveitem ' . '<br/>';

            $result_insert = $this->m_receive_item->insert_all_table_new($data, $arr_detail_pr, $arr_detail_po, $arr_detail, $prec_no, $arr_journal_inventory, $journal_unbilled, $Akun_number);
            /* ===============End=========================================================== */

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

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

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

    //public function insert(){
//        $CategoryIDAmt		= array();
//		$CategoryIDType 	= array();
//		
//        $branch_code		= $this->session->userdata('branch');
//        $vendor_code		= $this->input->post('cbg_vendor');
//        
//        $currency_code      = $this->input->post('hdn_currency_code');
//        $currency_rate     	= $this->input->post('hdn_currency_rate');
//        $vendor_do_no		= $this->input->post('txt_vendor_do_no');
//        $prec_date 			= $this->input->post('txt_prec_date');   
//		
//        $prec_no            = $this->m_receive_item->create_ri_number($prec_date);
//             
//        $pord_no			= $this->input->post('txt_pord_no');
//        $pord_date  		= $this->input->post('txt_pord_date');
//        $shipment_date		= $this->input->post('txt_ship_date');
//        $txa_description        = $this->input->post('txa_description');
//
//        $fob				= $this->input->post('cbo_fob') == "" ? null : $this->input->post('cbo_fob');
//        $terms				= $this->input->post('cbo_terms') == "" ? null : $this->input->post('cbo_terms');
//        $shipment			= $this->input->post('cbo_ship_via') == "" ? null : $this->input->post('cbo_ship_via');
//
//        $ppn_value			= $this->input->post('txt_ppn10');
//        $ppn_pcnt			= $ppn_value == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');
//        
//        $sub_total			= $this->input->post('txt_sub_total');
//        $total_purchase     = $this->input->post('txt_total_purchase');
//        $taxes_status		= $this->input->post('chk_taxtable');
//        $intax_status		= $this->input->post('chk_inclusive');
//
//        $detail_post 		= $this->input->post('detail');
//        $detail             = json_decode($detail_post);
//        
//		/*===================Global Function Array=========================================*/
//		$array_post_group  = array($branch_code,$vendor_code,$currency_code,$currency_rate,$vendor_do_no,$prec_no,$prec_date,$pord_no,$pord_date,$shipment_date,$txa_description,$fob,$terms,$shipment,$ppn_value,$ppn_pcnt,$sub_total,$total_purchase,$taxes_status,$intax_status);
//		/*=======================End=======================================================*/
//		
//        if(count($detail) > 0){
//            $this->db->trans_begin();
//            $unbilled_amount    = 0;
//            $unbilled_status    = FALSE;
//			
//			foreach($detail as $row_check){
//				$get_data_pord_detail = $this->m_receive_item->get_detail_purchase_order_for_ri($row_check->POrdNumber, $row_check->ItemCode);
//				
//				$ItemQtyRI 	= $get_data_pord_detail->ItemQtyRI;//Qty Suspend sudah ditambahkan di model
//				$ItemQtyPO 	= $get_data_pord_detail->ItemQtyPO;
//				$TotalQtyRI = $row_check->ItemQty + $ItemQtyRI;
//				
//				if($TotalQtyRI > $ItemQtyPO){
//					$this->db->trans_rollback();
//					$result['status']       = FALSE;
//                	$result['message']      = "Transaksi gagal, Item Qty Receive Item melebihi Item Qty Purchase Order, Untuk Item ".$row_check->ItemDesc.", Qty RI : ".$TotalQtyRI.", Qty PO : ".$ItemQtyPO."";
//					echo json_encode($result);
//					die();
//				}
//			}
//			/*======================Insert Group Function==================================*/
//			$this->insert_group($array_post_group);
//			/*===============End===========================================================*/
//            
//			/*===================Insert Detail==============================================*/
//            $this->insert_detail($array_post_group, $detail,$CategoryIDAmt,$unbilled_amount, $unbilled_status, $CategoryIDType);
//			/*=================End=========================================================*/
//            
//			/*=============================trans roll back dan trans commit============================/*/
//			if ($this->db->trans_status() === FALSE) {
//				$this->db->trans_rollback();
//				$result['status'] 		= FALSE;
//				$result['message']  	= get_notification_transaksi($this->name, 'insert', 0, $prec_no);
//				
//				$result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
//            	$result['number']       = $prec_no;
//			}
//			else {
//				$this->db->trans_commit();
//				$result['status'] 		= TRUE;
//				$result['message']  	= get_notification_transaksi($this->name, 'insert', 1, $prec_no);
//			}
//			/*==================================end======================================================*/
//        }
//        else {
//            $this->db->trans_rollback();
//            $result['status']       = false;
//            $result['message']      = get_notification_transaksi($this->name, 'insert', 0, $prec_no);
//        }
//
//        echo json_encode($result);
//        die();
//    }

    /*
      Insert group Ri
     */
    function insert_group($array_post_group) {
        $branch_code = $array_post_group[0];
        $vendor_code = $array_post_group[1];
        $currency_code = $array_post_group[2];
        $currency_rate = $array_post_group[3];
        $vendor_do_no = $array_post_group[4];
        $prec_no = $array_post_group[5];
        $prec_date = $array_post_group[6];
        $pord_no = $array_post_group[7];
        $pord_date = $array_post_group[8];
        $shipment_date = $array_post_group[9];
        $txa_description = $array_post_group[10];
        $fob = $array_post_group[11];
        $terms = $array_post_group[12];
        $shipment = $array_post_group[13];
        $ppn_value = $array_post_group[14];
        $ppn_pcnt = $array_post_group[15];
        $sub_total = $array_post_group[16];
        $total_purchase = $array_post_group[17];
        $intax_status = $array_post_group[19];
        $taxes_status = $array_post_group[18];

        $data = array(
            'BranchCode' => $branch_code,
            'VendorCode' => $vendor_code,
            'PRecNumber' => $prec_no,
            'PRecDate' => date("Y-m-d", strtotime($prec_date)),
            'POrdDate' => $pord_date,
            'POrdNumber' => $pord_no,
            'VendorDONumber' => $vendor_do_no,
            'ShipmentDate' => date("Y-m-d", strtotime($shipment_date)),
            'ShipmentID' => $shipment,
            'TermsPaymentID' => $terms,
            'FOBID' => $fob,
            'CurrencyCode' => $currency_code,
            'CurrencyRate' => $currency_rate,
            'PRecDesc' => $txa_description,
            'PRecSubTotal' => $sub_total,
            'PRecPPn10Pcnt' => $ppn_pcnt,
            'PRecPPn10' => $ppn_value,
            'PRecTotalAmount' => $total_purchase,
            'PRecTaxesStatus' => $taxes_status,
            'PRecInTaxStatus' => $intax_status,
            'TransStatus' => 4,
            'AppLevel1Status' => 0,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d'),
            'LastUser' => $this->session->userdata("username")
        );

        //'1. Input Receive Item >> at_receiveitem ' . '<br/>';
        $this->m_receive_item->insert($data);
    }

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

    /* ===================Insert Detail==================== */

    function insert_detail($array_post_group, $detail, $CategoryIDAmt, $unbilled_amount, $unbilled_status, $CategoryIDType) {
        foreach ($detail as $row) {
            $prec_no = $array_post_group[5];
            //2. insert to table detail receive item
            $detail_data = array(
                'POrdDetailID' => $row->POrdDetailID,
                'POrdNumber' => $row->POrdNumber,
                'PRecNumber' => $prec_no,
                'ItemCode' => $row->ItemCode,
                'ItemDesc' => $row->ItemDesc,
                'itemUnit' => $row->ItemUnit,
                'ItemQty' => $row->ItemQty,
                'ItemDisc' => $row->ItemDisc,
                'ItemPrice' => $row->ItemPrice,
                'ItemAmount' => $row->ItemAmount,
                'ItemTaxPPn10' => $row->ItemTaxPPn10,
                'ItemTotalAmount' => $row->ItemTotalAmount,
                'ItemCategoryID' => $row->ItemCategoryID,
                'ItemCategoryCode' => $row->ItemCategoryCode,
                'ItemType' => $row->ItemType,
				'ItemCodeVendor' => $row->ItemCodeVendor,
                'ItemStatus' => $row->ItemStatus,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_receive_item->insert_detail($detail_data);
            //----------------------------------------------------------------------------------------------//
            //3. Update ItemQTYRI pada Purchase Order Detail
            $newItemQtyRI = $row->ItemQtyRI + $row->ItemQty;

            $detail_data_po = array(
                'ItemQtyRI' => $newItemQtyRI,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_order->update_detail($detail_data_po, $row->POrdDetailID);
            //---------------------------------------------------------------------------------------------------------//
            //4. Update Qty RI Di PReq
            $get_purchase_order_on_receive = $this->m_purchase_order->get_detail_item_po($row->POrdDetailID);
            $detail_data_preq = array(
                'ItemQtyRI' => $newItemQtyRI,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_requisition->update_detail($detail_data_preq, $get_purchase_order_on_receive->PReqDetailID);
            /* ====================END====================== */

            @$CategoryIDAmt[$row->ItemCategoryID] += $row->ItemAmount;
            @$CategoryIDCode[$row->ItemCategoryID] = $row->ItemCategoryCode;
            @$CategoryIDType[$row->ItemCategoryID] = $row->ItemType;
        }
        $this->insert_journal_ri($array_post_group, $CategoryIDAmt, $unbilled_amount, $unbilled_status, $CategoryIDCode, 'insert', $CategoryIDType);
    }

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

    /* =================Insert Journal=================================== */

    function insert_journal_ri($array_post_group, $CategoryIDAmt, $unbilled_amount, $unbilled_status, $CategoryIDCode, $status_act, $CategoryIDType) {

        if ($status_act == 'insert') {
            $prec_date = $array_post_group[6];
            $prec_no = $array_post_group[5];
            $txa_description = $array_post_group[10];
            $currency_code = $array_post_group[2];
            $currency_rate = $array_post_group[3];
        } else {
            $prec_no = $array_post_group[1];
            $prec_date = $array_post_group[2];
            $txa_description = $array_post_group[4];
            $currency_code = $array_post_group[5];
            $currency_rate = $array_post_group[6];
        }
        $inventory_value = 0;
        $inventory_value_curr = 0;
        //4. insert journal inventory - Persesian Barang Dagang based on category
        foreach ($CategoryIDAmt as $key => $value) {
            if ($CategoryIDType[$key] == 0) {
                $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');
                if ($InventoryAccount == false) {
                    $this->trans_rollback('preference', 'Inventory', '');
                }

                $inventory_journal = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
                $inventory_currency = doubleval($value);

                $get_journal_receipt = $this->m_receive_item->get_journal_receive_empty($InventoryAccount->AccountNumber, $prec_no);
                if (empty($get_journal_receipt->PRecAccountNumber)) {
                    $journal_inventory = array(
                        'PRecDate' => date("Y-m-d", strtotime($prec_date)),
                        'PRecNumber' => $prec_no,
                        'PRecDesc' => $txa_description,
                        'PRecAccountNumber' => $InventoryAccount->AccountNumber,
                        'PRecSaldoDebet' => $inventory_journal,
                        'PRecSaldoCredit' => 0,
                        'AmountCurrency' => $inventory_currency,
                        'PRecSignStatus' => 0,
                        'ItemCategoryID' => $key,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $this->m_receive_item->insert_journal($journal_inventory);
                } else {
                    $inventory_journal = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
                    $inventory_currency = doubleval($value);

                    $inventory_value = $inventory_journal + $get_journal_receipt->PRecSaldoDebet;
                    $inventory_value_curr = $inventory_currency + $get_journal_receipt->AmountCurrency;

                    $journal_inventory = array(
                        'PRecSaldoDebet' => $inventory_value,
                        'PRecSaldoCredit' => 0,
                        'AmountCurrency' => $inventory_value_curr,
                    );
                    $this->m_receive_item->update_journal($journal_inventory, $InventoryAccount->AccountNumber, $prec_no);
                }

                $unbilled_amount += doubleval($value);
                $unbilled_status = TRUE;
            }
        }
        //--------------------------------------------------------------------------------------------------------------//
        //5. insert journal UnBilled
        if ($unbilled_status) {
            $UnbilledAccount = $this->m_account_journal->get_sys_item_account('Unbilled');
            if ($UnbilledAccount == false) {
                $this->trans_rollback('preference', 'Unbilled,Item', '');
            }

            $unbilled_journal = $currency_code == 'IDR' ? $unbilled_amount : $unbilled_amount * $currency_rate;
            $unbilled_currency = $unbilled_amount;

            $journal_unbilled = array(
                'PRecDate' => date("Y-m-d", strtotime($prec_date)),
                'PRecNumber' => $prec_no,
                'PRecDesc' => $txa_description,
                'PRecAccountNumber' => $UnbilledAccount->AccountNumber,
                'PRecSaldoDebet' => 0,
                'PRecSaldoCredit' => $unbilled_journal,
                'AmountCurrency' => $unbilled_currency,
                'PRecSignStatus' => 0,
                'ItemCategoryID' => $key,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_receive_item->insert_journal($journal_unbilled);
        }
        //--------------------------------------------------------------------------------------------------------------//
    }

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

    public function edit() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

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

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

                    $id = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());
                    $data['detail'] = $this->m_receive_item->get_detail($id);
                    //        $data['app1']           = $this->app1;

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

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

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

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

    public function update() {
        $CategoryIDAmt = array();
        $CategoryIDCode = array();
        $CategoryIDType = array();

        $vendor_do_no = $this->input->post('txt_vendor_do_no');
        $prec_no = $this->input->post('txt_prec_no');
        $prec_date = $this->input->post('txt_prec_date');
        $shipment_date = $this->input->post('txt_ship_date');
        $txa_description = $this->input->post('txa_description');
        $currency_code = $this->input->post('hdn_currency_code');
        $currency_rate = $this->input->post('hdn_currency_rate');

        $ppn_value = $this->input->post('txt_ppn10');
        $ppn_pcnt = $ppn_value == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');
        $terms = $this->input->post('cbo_terms') == "" ? null : $this->input->post('cbo_terms');
        $shipment = $this->input->post('cbo_ship_via') == "" ? null : $this->input->post('cbo_ship_via');
        $fob = $this->input->post('cbo_fob') == "" ? null : $this->input->post('cbo_fob');

        $sub_total = $this->input->post('txt_sub_total');
        $total_purchase = $this->input->post('txt_total_purchase');

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

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

        $detail_qty = $this->input->post('detail_qty');
        $detail_qty = json_decode($detail_qty, true);

        $arr_update_detail = array();
        $arr_update_po = array();
        $arr_update_pr = array();

        $arr_journal_inventory = array();
        $journal_unbilled = array();
        $Akun_number = "";
        $ItemCategoryID = "";

        $calculate_qty_ri = array();
        $arr_delete_item_ri = array();

        $result_update = 0;
        $inventory_value = 0;
        $inventory_value_curr = 0;

        if (count($detail) > 0) {
            $unbilled_amount = 0;
            $unbilled_status = FALSE;

            foreach ($detail as $row_check) {
                $get_data_pord_detail = $this->m_receive_item->get_detail_purchase_order_for_ri($row_check->POrdNumber, $row_check->ItemCode);

                $ItemQtyRI = $get_data_pord_detail->ItemQtyRI; //Qty Suspend sudah ditambahkan di model
                $ItemQtyPO = $get_data_pord_detail->ItemQtyPO;
                $TotalQtyRI = ($row_check->ItemQty - $ItemQtyRI) + ($ItemQtyRI + $get_data_pord_detail->ItemQtySpd);

                if ($TotalQtyRI > $ItemQtyPO) {
                    $result['status'] = FALSE;
                    $result['message'] = "Transaksi gagal, Item Qty Receive Item melebihi Item Qty Purchase Order, Untuk Item " . $row_check->ItemDesc . ", Qty RI : " . $TotalQtyRI . ", Qty PO : " . $ItemQtyPO . "";
                    echo json_encode($result);
                    die();
                }
            }

            /* ====================Update group=========================== */
            $data = array(
                'VendorDONumber' => $vendor_do_no,
                'ShipmentID' => $shipment,
                'TermsPaymentID' => $terms,
                'ShipmentDate' => date("Y-m-d", strtotime($shipment_date)),
                'FOBID' => $fob,
                'PRecDesc' => $txa_description,
                'PRecPPn10Pcnt' => $ppn_pcnt,
                'PRecPPn10' => $ppn_value,
                'PRecSubTotal' => $sub_total,
                'PRecTotalAmount' => $total_purchase,
                'TransStatus' => 4,
				'AppFinished' => 2,
                'LastUser' => $this->session->userdata("username")
            );

            //4. Delete Journal
            $result_update = $this->m_receive_item->delete_journal($prec_no);
            //--------------------------------------------------------------------------------------------------------------//

            foreach ($detail as $row) {
                //2. Insert Into Receive Detail
                $detail_data = array(
                    'PRecDetailID' => $row->PRecDetailID,
                    'ItemQty' => $row->ItemQty,
                    'ItemAmount' => $row->ItemAmount,
                    'ItemTaxPPn10' => $row->ItemTaxPPn10,
                    'ItemTotalAmount' => $row->ItemTotalAmount,
					'ItemCodeVendor' => $row->ItemCodeVendor,
                    'LastUser' => $this->session->userdata("username")
                );

                $arr_update_detail[] = $detail_data;
                //-----------------------------------------------------------------------------------------------//
                //3. Update item quantity ri pada po
                $porddetail = $this->m_purchase_order->get_detail_item_po($row->POrdDetailID);
                if ($row->ItemQty > $row->ItemQty_Old) {
                    $TotalNewQty_RI = doubleval($porddetail->ItemQtyRI - $row->ItemQty_Old) + doubleval($row->ItemQty);
                    $detail_data_po = array(
                        'POrdDetailID' => $row->POrdDetailID,
                        'ItemQtyRI' => $TotalNewQty_RI,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $arr_update_po[] = $detail_data_po;

                    $detail_data_preq = array(
                        'PReqDetailID' => $porddetail->PReqDetailID,
                        'ItemQtyRI' => $TotalNewQty_RI,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $arr_update_pr[] = $detail_data_preq;
                } else if ($row->ItemQty < $row->ItemQty_Old) {
                    $TotalNewQty_RI = doubleval($porddetail->ItemQtyRI - $row->ItemQty_Old) + doubleval($row->ItemQty);
                    $detail_data_po = array(
                        'POrdDetailID' => $row->POrdDetailID,
                        'ItemQtyRI' => $TotalNewQty_RI,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $arr_update_po[] = $detail_data_po;

                    $detail_data_preq = array(
                        'PReqDetailID' => $porddetail->PReqDetailID,
                        'ItemQtyRI' => $TotalNewQty_RI,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $arr_update_pr[] = $detail_data_preq;
                }
                //----------------------------------------------------------------------------------------------------------//

                @$CategoryIDAmt[$row->ItemCategoryID] += $row->ItemAmount;
                @$CategoryIDCode[$row->ItemCategoryID] = $row->ItemCategoryCode;
                @$CategoryIDType[$row->ItemCategoryID] = $row->ItemType;
            }

            $inventory_value = 0;
            $inventory_value_curr = 0;
            //4. insert journal inventory - Persesian Barang Dagang based on category
            foreach ($CategoryIDAmt as $key => $value) {
                if ($CategoryIDType[$key] == 0) {
                    $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');
                    if ($InventoryAccount == false) {
                        $this->trans_rollback('preference', 'Inventory', '');
                    }

                    $inventory_journal = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
                    $inventory_currency = doubleval($value);
                    $Akun_number = $InventoryAccount->AccountNumber;

                    $get_journal_receipt = $this->m_receive_item->get_journal_receive_empty($InventoryAccount->AccountNumber, $prec_no);
                    if (empty($get_journal_receipt->PRecAccountNumber)) {
                        $journal_inventory = array(
                            'PRecDate' => date("Y-m-d", strtotime($prec_date)),
                            'PRecNumber' => $prec_no,
                            'PRecDesc' => $txa_description,
                            'PRecAccountNumber' => $InventoryAccount->AccountNumber,
                            'PRecSaldoDebet' => $inventory_journal,
                            'PRecSaldoCredit' => 0,
                            'AmountCurrency' => $inventory_currency,
                            'PRecSignStatus' => 0,
                            'ItemCategoryID' => $key,
                            'LastUser' => $this->session->userdata("username"),
                            'Status' => 0
                        );
                        $arr_journal_inventory[] = $journal_inventory;
                    } else {
                        $inventory_journal = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
                        $inventory_currency = doubleval($value);

                        $inventory_value = $inventory_journal + $get_journal_receipt->PRecSaldoDebet;
                        $inventory_value_curr = $inventory_currency + $get_journal_receipt->AmountCurrency;

                        $journal_inventory = array(
                            'PRecSaldoDebet' => $inventory_value,
                            'PRecSaldoCredit' => 0,
                            'AmountCurrency' => $inventory_value_curr,
                            'Status' => 1
                        );
                        $arr_journal_inventory[] = $journal_inventory;
                    }

                    $unbilled_amount += doubleval($value);
                    $unbilled_status = TRUE;
                }
            }
            //--------------------------------------------------------------------------------------------------------------//
            //5. insert journal UnBilled
            if ($unbilled_status) {
                $UnbilledAccount = $this->m_account_journal->get_sys_item_account('Unbilled');
                if ($UnbilledAccount == false) {
                    $this->trans_rollback('preference', 'Unbilled,Item', '');
                }

                $unbilled_journal = $currency_code == 'IDR' ? $unbilled_amount : $unbilled_amount * $currency_rate;
                $unbilled_currency = $unbilled_amount;

                $journal_unbilled = array(
                    'PRecDate' => date("Y-m-d", strtotime($prec_date)),
                    'PRecNumber' => $prec_no,
                    'PRecDesc' => $txa_description,
                    'PRecAccountNumber' => $UnbilledAccount->AccountNumber,
                    'PRecSaldoDebet' => 0,
                    'PRecSaldoCredit' => $unbilled_journal,
                    'AmountCurrency' => $unbilled_currency,
                    'PRecSignStatus' => 0,
                    'ItemCategoryID' => $ItemCategoryID,
                    'LastUser' => $this->session->userdata("username")
                );
            }
            //--------------------------------------------------------------------------------------------------------------//

            /* ===============Delete per grid jika tombol delete di klik ===================== */
            if (count($detail_id) > 0) {
                foreach ($detail_id as $PRecDetailID) {
                    $data_delete_item = array(
                        'PRecDetailID' => $PRecDetailID
                    );
                    $arr_delete_item_ri[] = $data_delete_item;
                }

                for ($x = 0; $x < count($detail_qty['a']); $x++) {
                    //1. Update ItemQtyRI pada POrdDetail
                    $porddetail_delete = $this->m_purchase_order->get_detail_item_po($detail_qty['a'][$x]);
                    $data_pord_detail = array(
                        'POrdDetailID' => $detail_qty['a'][$x],
                        'PReqDetailID' => $porddetail_delete->PReqDetailID,
                        'ItemQtyRI' => $detail_qty['b'][$x] - $detail_qty['c'][$x],
                        'LastUser' => $this->session->userdata("username")
                    );
                    $calculate_qty_ri[] = $data_pord_detail;
                    //------------------------------------------------------------------------------------------------------------//
                }
            }
            /* ====================End============================================================================ */

            $result_update = $this->m_receive_item->update_all_new_table($data, $prec_no, $arr_update_detail, $arr_update_po, $arr_update_pr, $arr_journal_inventory, $journal_unbilled, $Akun_number, $calculate_qty_ri, $arr_delete_item_ri);

            if ($result_update == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 0, $prec_no);

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

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

    //public function update(){
//        $CategoryIDAmt      = array();
//        $CategoryIDCode     = array();
//		$CategoryIDType 	= array();
//        
//        $vendor_do_no		= $this->input->post('txt_vendor_do_no');
//        $prec_no			= $this->input->post('txt_prec_no');
//        $prec_date 			= $this->input->post('txt_prec_date');
//        $shipment_date		= $this->input->post('txt_ship_date');
//        $txa_description    = $this->input->post('txa_description');
//        $currency_code      = $this->input->post('hdn_currency_code');
//        $currency_rate      = $this->input->post('hdn_currency_rate');
//
//        $ppn_value			= $this->input->post('txt_ppn10');                
//        $ppn_pcnt			= $ppn_value == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');        
//        $terms				= $this->input->post('cbo_terms') == "" ? null : $this->input->post('cbo_terms');
//        $shipment			= $this->input->post('cbo_ship_via') == "" ? null : $this->input->post('cbo_ship_via');
//        $fob				= $this->input->post('cbo_fob') == "" ? null : $this->input->post('cbo_fob');
//        
//        $sub_total			= $this->input->post('txt_sub_total');
//        $total_purchase     = $this->input->post('txt_total_purchase');
//                
//        $detail_post        = $this->input->post('detail');
//        $detail             = json_decode($detail_post);            
//		
//		$detail_id			= $this->input->post('detail_id');
//        $detail_id			= json_decode($detail_id);
//		
//		$detail_qty			= $this->input->post('detail_qty');
//        $detail_qty			= json_decode($detail_qty,true);
////        print_r($detail); die();
//		
//        if(count($detail) > 0){
//            $this->db->trans_begin();
//            $unbilled_amount    = 0;
//            $unbilled_status    = FALSE;
//			
//			foreach($detail as $row_check){
//				$get_data_pord_detail = $this->m_receive_item->get_detail_purchase_order_for_ri($row_check->POrdNumber, $row_check->ItemCode);
//				
//				$ItemQtyRI 	= $get_data_pord_detail->ItemQtyRI;//Qty Suspend sudah ditambahkan di model
//				$ItemQtyPO 	= $get_data_pord_detail->ItemQtyPO;
//				$TotalQtyRI = ($row_check->ItemQty - $ItemQtyRI) + ($ItemQtyRI + $get_data_pord_detail->ItemQtySpd);
//				
//				if($TotalQtyRI > $ItemQtyPO){
//					$this->db->trans_rollback();
//					$result['status']       = FALSE;
//                	$result['message']      = "Transaksi gagal, Item Qty Receive Item melebihi Item Qty Purchase Order, Untuk Item ".$row_check->ItemDesc.", Qty RI : ".$TotalQtyRI.", Qty PO : ".$ItemQtyPO."";
//					echo json_encode($result);
//					die();
//				}
//			}
//			
//			/*=============Array global function =============================*/
//			$array_post_update = array($vendor_do_no,$prec_no, $prec_date, $shipment_date, $txa_description, $currency_code, $currency_rate, $ppn_value, $ppn_pcnt, $terms, $shipment, $fob, $sub_total, $total_purchase);
//			/*==============End===============================================*/
//			
//			/*====================Update group===========================*/
//			$this->update_group($array_post_update);
//			/*=================End======================================*/
//			
//			//4. Delete Journal
//            $this->m_receive_item->delete_journal($prec_no);
//            //--------------------------------------------------------------------------------------------------------------//
//			
//			/*=====Update detail=======================================*/
//			$this->update_detail($detail, $array_post_update, $CategoryIDAmt, $CategoryIDCode, $unbilled_amount, $unbilled_status, $detail_id, $detail_qty, $CategoryIDType);
//			/*===============End=======================================*/
//            
//            $this->db->trans_commit();
//            $result['status']       = true;
//            $result['message']      = get_notification_transaksi($this->name, 'update', 1, $prec_no);
//
//            $result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
//            $result['number']       = $prec_no;
//        }
//        else {
//            $this->db->trans_rollback();
//            $result['status']       = false;
//            $result['message']      = get_notification_transaksi($this->name, 'update', 0, $prec_no);
//        }
//        
//        echo json_encode($result);
//        die();
//    }

    /* =====================Update Froup======================== */
    function update_group($array_post_update) {
        $vendor_do_no = $array_post_update[0];
        $prec_no = $array_post_update[1];
        $shipment_date = $array_post_update[3];
        $txa_description = $array_post_update[4];
        $ppn_value = $array_post_update[7];
        $ppn_pcnt = $array_post_update[8];
        $terms = $array_post_update[9];
        $shipment = $array_post_update[10];
        $fob = $array_post_update[11];
        $sub_total = $array_post_update[12];
        $total_purchase = $array_post_update[13];

        $data = array(
            'VendorDONumber' => $vendor_do_no,
            'ShipmentID' => $shipment,
            'TermsPaymentID' => $terms,
            'ShipmentDate' => date("Y-m-d", strtotime($shipment_date)),
            'FOBID' => $fob,
            'PRecDesc' => $txa_description,
            'PRecPPn10Pcnt' => $ppn_pcnt,
            'PRecPPn10' => $ppn_value,
            'PRecSubTotal' => $sub_total,
            'PRecTotalAmount' => $total_purchase,
            'TransStatus' => 4,
            'LastUser' => $this->session->userdata("username")
        );

        //1. Update Receive Item
        $this->m_receive_item->update($data, $prec_no);
    }

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

    /* ==========Update Detail==================================== */

    function update_detail($detail, $array_post_update, $CategoryIDAmt, $CategoryIDCode, $unbilled_amount, $unbilled_status, $detail_id, $detail_qty, $CategoryIDType) {

        foreach ($detail as $row) {
            //2. Insert Into Receive Detail
            $detail_data = array(
                'ItemQty' => $row->ItemQty,
                'ItemAmount' => $row->ItemAmount,
                'ItemTaxPPn10' => $row->ItemTaxPPn10,
                'ItemTotalAmount' => $row->ItemTotalAmount,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_receive_item->update_detail($detail_data, $row->PRecDetailID);
            //-----------------------------------------------------------------------------------------------//
            //3. Update item quantity ri pada po
            $porddetail = $this->m_purchase_order->get_detail_item_po($row->POrdDetailID);
            if ($row->ItemQty > $row->ItemQty_Old) {
                $TotalNewQty_RI = doubleval($porddetail->ItemQtyRI - $row->ItemQty_Old) + doubleval($row->ItemQty);
                $detail_data_po = array(
                    'ItemQtyRI' => $TotalNewQty_RI,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_order->update_detail($detail_data_po, $row->POrdDetailID);

                $detail_data_preq = array(
                    'ItemQtyRI' => $TotalNewQty_RI,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_requisition->update_detail($detail_data_preq, $porddetail->PReqDetailID);
            } else if ($row->ItemQty < $row->ItemQty_Old) {
                $TotalNewQty_RI = doubleval($porddetail->ItemQtyRI - $row->ItemQty_Old) + doubleval($row->ItemQty);
                $detail_data_po = array(
                    'ItemQtyRI' => $TotalNewQty_RI,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_order->update_detail($detail_data_po, $row->POrdDetailID);

                $detail_data_preq = array(
                    'ItemQtyRI' => $TotalNewQty_RI,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_requisition->update_detail($detail_data_preq, $porddetail->PReqDetailID);
            }
            //----------------------------------------------------------------------------------------------------------//

            @$CategoryIDAmt[$row->ItemCategoryID] += $row->ItemAmount;
            @$CategoryIDCode[$row->ItemCategoryID] = $row->ItemCategoryCode;
            @$CategoryIDType[$row->ItemCategoryID] = $row->ItemType;
        }

        $this->delete_row($detail_id, $detail_qty);

        $this->insert_journal_ri($array_post_update, $CategoryIDAmt, $unbilled_amount, $unbilled_status, $CategoryIDCode, 'update', $CategoryIDType);
    }

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

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

        $rep_1 = str_replace(".", "/", $id);
        $rep_2 = str_replace(".", "/", $rep_1);
        $rep_3 = str_replace(".", "/", $rep_2);
        $prec_no = $rep_3;

        $arr_group_ri = array();
        $arr_qty_ri = array();
        $this->transaction = [];

        $result_suspend = 0;
        $data = $this->m_receive_item->get_detail($prec_no);

        if ($data->AppLevel1Status != 1) {
            /* ==============Set status di purchase order============================= */
            /*
              $data->TotalQty == $data->TotalQtyRI maka status 2, jika tidak sama maka status berubah jadi 1
             */
            $po_number = explode(",", $data->POrdNumber);
            $data_ri = array(
                'TransStatus' => 3,
                'LastUser' => $this->session->userdata("username")
            );

            $this->transaction['update_group']['data'] = $data_ri;
            $this->transaction['update_group']['PrecNo'] = $prec_no;
            //$this->m_receive_item->update($data_ri, $prec_no);

            /*
              Kembalikan item qty PO
             */
            $data_detail = $this->m_receive_item->get_detail_item($prec_no);

            foreach ($data_detail as $row) {
                $detail_po = $this->m_purchase_order->get_detail_item_by_id($row->POrdDetailID);
                $newItemQtyRI = intval($detail_po->ItemQtyRI) - intval($row->ItemQty);

                $new_detail_po = array(
                    'ItemQtyRI' => $newItemQtyRI
                );

                $this->transaction['update_qty_ri']['data'][] = $new_detail_po;
                $this->transaction['update_qty_ri']['POrdDetailID'][] = $row->POrdDetailID;
                $this->transaction['update_qty_ri']['PReqDetailID'][] = $detail_po->PReqDetailID;
            }

            $result_suspend = $this->m_receive_item->suspend_data($this->transaction);
            /* =====================End============================================================ */

            /* =============================trans roll back dan trans commit============================/ */
            if ($result_suspend == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification('suspend', 0);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification('suspend', 1);
            }
            /* ==================================end====================================================== */
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend', 0);
        }
        echo json_encode($result);
    }

    function delete_row($detail_id, $detail_qty) {
        /* ===============Delete per grid jika tombol delete di klik ===================== */
        if (count($detail_id) > 0) {
            foreach ($detail_id as $PRecDetailID) {
                $this->m_receive_item->delete_detail($PRecDetailID);
            }

            for ($x = 0; $x < count($detail_qty['a']); $x++) {
                //1. Update ItemQtyRI pada POrdDetail
                $data_pord_detail = array(
                    'ItemQtyRI' => $detail_qty['b'][$x] - $detail_qty['c'][$x],
                    'LastUser' => $this->session->userdata("username")
                );

                $this->m_purchase_order->update_detail($data_pord_detail, $detail_qty['a'][$x]);
                //------------------------------------------------------------------------------------------------------------//
            }
        }
        /* ====================End============================================================================ */
    }

    public function approved_mgr() {
        if (in_array($this->session->userdata("jobtitle_status"), $this->jobtitle_status)) {
            $branch_code = $this->session->userdata("branch");
            $hdn_currency_rate = $this->input->post('hdn_currency_rate');
            $prec_no = $this->input->post('txt_prec_no');
            $detail_post = $this->input->post('detail');
            $prec_date = date("Y-m-d", strtotime($this->input->post('txt_prec_date')));
            $currency_rate = $this->input->post('hdn_currency_rate');
            $pord_no = $this->input->post('txt_pord_no');
            $po_number = explode(",", $pord_no);
            $detail = json_decode($detail_post);
			
			$this->db->trans_begin();
            if (count($detail) > 0) {
                /*
                  Cek Concuren For Approval Mgr
                 */
                $get_receipt_item = $this->m_receive_item->get_detail_print($prec_no);

                $get_employee = $this->m_employee->get_detail($get_receipt_item->AppLevel1Code);
                if (($get_receipt_item->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($get_receipt_item->AppLevel1Date)) . '';
					
                    echo json_encode($result);
                    $this->db->trans_rollback();
					die();
                }
                /* =========================End======================================== */

                //1. Update Purhcase Order Status
                $TotalQtyRI_On_RI 	= 0;
                $TotalQtySpd_On_PO 	= 0;
                $get_po_set_finish 	= 0;
				$TempItemCode 		= " ";
				$data_inventory 	= array();
				$ItemQty_Loop 			= 0; 
				
                foreach ($po_number as $key => $value) {
                    $TotalQtyRI_On_RI = $this->m_purchase_order->set_finish($value);

                    $TotalQtySpd_On_PO = $this->m_purchase_order->get_total_qty_po_spd($value);
                    $get_po_set_finish = $this->m_purchase_order->set_finish_po($value);
                    $get_qty_ri = $this->m_purchase_order->get_qty_receive_item($value, $prec_no);

                    $QtyRI = empty($TotalQtyRI_On_RI->TotalQtyRI) ? 0 : $TotalQtyRI_On_RI->TotalQtyRI;
                    $QtySpd = empty($TotalQtySpd_On_PO->TotalQtySpd) ? 0 : $TotalQtySpd_On_PO->TotalQtySpd;
                    $QtyRI_FromNumber = empty($get_qty_ri->TotalQtyRI_All) ? 0 : $get_qty_ri->TotalQtyRI_All;

                    $total_qty_po = ($QtyRI + $QtySpd) + $QtyRI_FromNumber;

                    if ($total_qty_po == $get_po_set_finish->TotalQtyPO) {
                        $trans_stataus = 2;
                    } else {
                        $trans_stataus = 1;
                    }

                    $data_prec = array(
                        'TransStatus' => $trans_stataus,
                        'LastUser' => $this->session->userdata("username")
                    );
					$this->m_purchase_order->update($data_prec, $value);
					
                   /* $this->transaction['update_po']['data'][] = $data_prec;
                    $this->transaction['update_po']['POrdNumber'][] = $value;*/
                }
                //------------------------------------------------------------------------------------------------------//

                foreach ($detail as $row) {
                    /* ===================Check Lock Status Adjust============================================= */
                    $item_lock_status = $this->m_receive_item->check_lock_status($prec_no, $branch_code, $row->ItemCode);
                    if ($item_lock_status) {
                        $result['status'] = false;
                        $result['message'] = 'Tidak bisa dilakukan proses approval, karena item ' . $row->ItemCode . ' pada listing sedang dilakukan proses Adjustment';

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

                    /* =====================inventori or fixed asset======================================================== */
                    if ($row->ItemType == 0) {
                        //Upate Item Quantity at Inventories
						$get_inventory = $this->m_inventories->get_inventories($row->ItemCode);
						if ($get_inventory == false) {
                            //1. Insert Item pada Inventory >> at_inventories
                            $data_inventory = array(
                                'BranchCode' => $branch_code,
                                'ItemCode' => $row->ItemCode,
                                'ItemQty' => $row->ItemQty,
                                'ItemAverage' => $row->ItemPrice * $hdn_currency_rate,
                                'ItemValue' => $row->ItemAmount * $hdn_currency_rate,
                                'LastUser' => $this->session->userdata("username")
                            );
							$this->m_inventories->insert($data_inventory);
                            //$this->transaction['insert_inventory'][] = $data_inventory;
                        } else {
                            //2. Update Item QTY pada Inventory >> at_inventories
                            $item_qty = ($get_inventory->ItemQty) + ($row->ItemQty);
                            $item_value = doubleval($get_inventory->ItemValue) + doubleval($row->ItemAmount * $hdn_currency_rate);
                            $item_average = doubleval($item_value) / $item_qty;

                            $data_inventory = array(
                                'ItemQty' => $item_qty,
                                'ItemAverage' => $item_average,
                                'ItemValue' => $item_value,
                                'LastUser' => $this->session->userdata("username")
                            );
							
							$this->m_inventories->update($data_inventory, $row->ItemCode);
							
                            /*$this->transaction['update_inventory']['data'][] = $data_inventory;
                            $this->transaction['update_inventory']['ItemCode'][] = $row->ItemCode;*/
                        }

                        //3. Insert Inventories Detail for Item Fixed Asset only
                        if ($row->ItemStatus == 1) {
                            $item_average = ($row->ItemPrice - ($row->ItemPrice * ($row->ItemDisc / 100))) * $currency_rate;
                            $asset_code = $this->m_inventories->create_asset_code($row->ItemCode);

                            $asset_string = substr($asset_code, 0, strlen($asset_code) - 4);
                            $asset_number = intval(substr($asset_code, -4));
                            $intloop = 4 - strlen($asset_number);

                            for ($ii = 0; $ii < $row->ItemQty; $ii++) {
                                for ($jj = 1; $jj <= $intloop; $jj++) {
                                    $asset_number = '0' . $asset_number;
                                }

                                $asset_code = $asset_string . $asset_number;
                                $asset_number = intval($asset_number) + 1;
                                $intloop = 4 - strlen($asset_number);

                                $data_inventdetail = array(
                                    'BranchCode' => $branch_code,
                                    'ReceiptNumber' => $prec_no,
                                    'ReceiptDate' => $prec_date,
                                    'UsageDate' => $prec_date,
                                    'ItemCode' => $row->ItemCode,
                                    'ItemDesc' => $row->ItemDesc,
                                    'ItemQty' => 1,
                                    'ItemAverage' => $item_average,
                                    'ItemCategoryID' => $row->ItemCategoryID,
                                    'AssetCode' => $asset_code,
                                    'SoldStatus' => 0,
                                    'LastUser' => $this->session->userdata("username")
                                );
								$this->m_inventories->insert_detail($data_inventdetail);
								
                                //$this->transaction['insert_asset'][] = $data_inventdetail;
                            }
                        }
                    }
                    /* =========================End Fixed Asset========================================= */
                }

                $data = array(
                    'TransStatus' => 1,
                    'AppFinished' => 1,
                    'AppLevel1Status' => 1,
                    'AppLevel1Code' => $this->session->userdata("username"),
                    'AppLevel1Date' => date("Y-m-d"),
                    'LastUser' => $this->session->userdata("username")
                );
				
				$this->m_receive_item->update($data, $prec_no);
				/*
                $this->transaction['update_group']['data'] = $data;
                $this->transaction['update_group']['PrecNo'] = $prec_no;*/

                //$result_approve = $this->m_receive_item->approved_all($this->transaction, $detail);
               // $this->transaction = [];
            }


            /* =============================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======================================================*/
			echo json_encode($result);
            die();
        }
    }

    function reverse_data_detail() {
        try {

            $receive_item = $this->input->post('txt_prec_no');
            $txt_pord_no = $this->input->post('txt_pord_no');
            $hdn_currency_rate = $this->input->post('hdn_currency_rate');

            $detail_post = $this->input->post('detail');
            $detail = json_decode($detail_post);
            $branch_code = $this->session->userdata("branch");
			
			$get_purchase_order = $this->m_receive_item->get_purchase_order($txt_pord_no);
			if($get_purchase_order){
				$trans_status = 0;
			}
			else{
				$trans_status = 1;
			}
			
            /*
              Check apakah transaksi sudah di buat di purchase invoice
             */
            $date_transaction 	= check_end_periode($receive_item);

            $get_detail_pinv = $this->m_custom->check_item_reverse($receive_item, 'at_purchaseinvoice', 'at_pinvdetail', 'PInvNumber', 'PRecNumber');
            $get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);
			$get_no_transaction = $this->m_purchase_order->get_old_no_transaaction($txt_pord_no);
			
            if ($get_detail_pinv) {
                throw new Exception(msg_check_po_reverse('Purchase Invoice')); //Sudah dibuat di pi 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_no_transaction->OldPOrdNumber != ""){
				throw new Exception("Transaksi gagal di reverse, karena item ini adalah transaksi dari import file");
			}
            /* ====================END================================== */
			
			/*$get_purchase_order = $this->m_receive_item->get_purchase_order($txt_pord_no);
			if($get_purchase_order){
				throw new Exception("Transaksi gagal di Reverse, PO dengan No ".$get_purchase_order." mempunyai Down Payment, selesaikan pembayaran DP atau By Pass PO");
			}*/
			
            foreach ($detail as $row_detail) {
                /*
                  0 = Inventory
                  1 = Asset
                 */

                if ($row_detail->ItemStatus == 0) {
                    /*
                      Check Adjustment
                     */
                    $item_lock_status = $this->m_receive_item->check_lock_status($receive_item, $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============================== */
                } else if ($row_detail->ItemStatus == 1) {
                    /*
                      Check fixed asset lock
                     */
                    $item_lock_status_invendetail = $this->m_inventories->get_inventori_detail($row_detail->ItemCode, $branch_code, $receive_item);
                    if ($item_lock_status_invendetail->SoldStatus == 5) {
                        throw new Exception('Tidak bisa dilakukan proses Reverse, karena Item ' . $row_detail->ItemCode . ' sedang proses Dispose/Selling'); //item adjust
                    }
                    /* ==============End================= */

                    /*
                      Delete Inven Detail
                     */
                    $this->transaction['delete_invendetail']['PRecNumber'][] = $receive_item;
                    $this->transaction['delete_invendetail']['ItemCode'][] = $row_detail->ItemCode;
                    $this->transaction['delete_invendetail']['BranchCode'][] = $branch_code;
                    /* =====================END======================================= */
                }
				
				if($row_detail->ItemType == 0){
					$get_inventory = $this->m_inventories->get_inventories($row_detail->ItemCode);
					$item_qty = ($get_inventory->ItemQty) - ($row_detail->ItemQty);
					$item_value = doubleval($get_inventory->ItemValue) - doubleval($row_detail->ItemAmount * $hdn_currency_rate);
	
					if (($item_qty == 0)) {
						$item_average = 0;
					} else {
						$item_average = doubleval($item_value) / $item_qty;
					}
	
					$data_inventory = array(
						'ItemQty' => $item_qty,
						'ItemAverage' => $item_average,
						'ItemValue' => $item_value,
						'LastUser' => $this->session->userdata("username")
					);
	
					$this->transaction['update_inventory']['data'][] = $data_inventory;
					$this->transaction['update_inventory']['ItemCode'][] = $row_detail->ItemCode;
				}
            }

            $data_po = array(
                'TransStatus' => $trans_status,
                'LastUser' => $this->session->userdata("username")
            );
            $this->transaction['update_po']['data'] = $data_po;
            $this->transaction['update_po']['POrdNumber'] = $txt_pord_no;

            $data_ri = array(
                'TransStatus' => 4,
                'AppLevel1Status' => 0,
                'AppLevel1Code' => NULL,
                'AppLevel1Date' => NULL,
                'AppFinished' => 0,
                'LastUser' => $this->session->userdata("username")
            );
            $this->transaction['update_ri']['data'] = $data_ri;
            $this->transaction['update_ri']['PRecNumber'] = $receive_item;

            $result_approve = $this->m_receive_item->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $receive_item);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $receive_item);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

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

        $this->load->view('v_header');
        $this->load->view('purchase/receive_item/v_preview_receive_item', $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_receive_item->get_all_print($this->ho);

        $this->load->view('v_header');
        $this->load->view('purchase/receive_item/v_preview_receive_item', $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_receive_item->get_all($this->ho);

        $this->load->view('v_header');
        $this->load->view('PURCHASE/RECEIVE_ITEM/V_PRINT_RECEIVE_ITEM', $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_receive_item->get_detail_print($id);
            $data['list'] = $this->m_receive_item->get_detail_item_print($data['detail']->PRecNumber);

            $this->load->view('v_header');
            $this->load->view('purchase/receive_item/v_print_detail_receive_item', $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_receive_item->get_detail($id);
        $data['list'] = $this->m_receive_item->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/receive_item/v_preview_journal_receive_item', $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_receive_item->get_detail($id);
        $data['list'] = $this->m_receive_item->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('purchase/receive_item/v_print_journal_receive_item', $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('PRecNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('PRecDesc', $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_receiveitem.PRecDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_receiveitem.PRecDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_receiveitem');
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_receive_item->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]->PRecNumber,
                'PRecDate' => $result[$i]->PRecDate,
                'POrdNumber' => $result[$i]->POrdNumber,
                'PRecDesc' => $result[$i]->PRecDesc,
                'TransStatus' => $TransStatus,
                'CreatedBy' => $result[$i]->CreatedBy
            );
        }

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

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

        if (!empty($VendorCode)) {
            echo json_encode($this->m_purchase_order->get_for_ri2($VendorCode));
//            echo $this->db->last_query();
        } else {
            echo '[]';
        }
    }

    public function ajax_item() {
        $id = $this->input->post('Number');

        if (!empty($id)) {
            echo json_encode($this->m_purchase_order->get_detail_item_for_ri($id));
//            echo $this->db->last_query();
        } 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_receive_item->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_prec_number() {
        $date = $this->input->post('date') == '' ? date('d-m-Y') : $this->input->post('date');
        $prec_number = $this->m_receive_item->create_ri_number($date);

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

        echo json_encode($result);
    }

}
