<?php

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

class Purchases_order extends CI_Controller {

    public $menu_id = 168;
    public $menu_model = array('m_purchase_requisition', 'm_purchase_order', 'm_receive_item', 'm_purchase_invoice', 'm_taxes', 'm_employee', 'm_purchase_payment');
    public $name = "Purchase Order";
    public $branch = "";
    public $ho;
    public $jobtitle_status = array('0', '1');
    public $transaction = [];

    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->model('m_purchase_requisition');

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

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

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

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

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

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

    public function view_list_price($ItemCode) {
        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);
                    $data['ItemCode'] = $ItemCode;

                    //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/purchase_order/v_list_price_item', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

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

                    //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/purchase_order/v_list_receipt_item', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    function get_list_price($ItemCode,$limit='') {
        $ItemCode   = str_replace('__', '/', $ItemCode);
        $ItemCode   = str_replace('_', '-', $ItemCode);
        $limit      = $limit == '' ? 10:$limit;
        $list_price = $this->m_purchase_order->get_list_price_by_itemcode($ItemCode,$limit);
        echo json_encode($list_price);
    }

    function get_list_receipt($ItemCode, $POrdNumber) {
        $ItemCode   = str_replace('__', '/', $ItemCode);
        $ItemCode   = str_replace('_', '-', $ItemCode);
        $POrdNumber = str_replace('__', '/', $POrdNumber);
        $POrdNumber = str_replace('_', '-', $POrdNumber);
        $list_receipt = $this->m_purchase_order->get_list_receipt_by_itemcode($ItemCode, $POrdNumber);
        echo json_encode($list_receipt);
    }

    public function add($PReqNumber = '', $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);

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

                    date_default_timezone_set("Asia/Bangkok");
                    $data['po_date'] = date('d-m-Y');
                    $data['branch'] = $this->m_purchase_order->get_branch_address($this->session->userdata('branch'));

                    $data['taxes_ppn10'] = $this->m_taxes->get_by_code('PPN');
                    $data['taxes_pph22'] = $this->m_taxes->get_by_code('PPH22');
                    $data['taxes_pph23'] = $this->m_taxes->get_by_code('PPH23');

                    /* ===========daswan=================== */
                    $data['PReqNumber'] = $PReqNumber;
                    $data['VendorCode'] = $VendorCode;

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

    public function insert() {
        /* ==================Deklar Variabel=============================================================== */
        $branch_code = $this->session->userdata('branch');
        $vendor_code = $this->input->post('cbg_vendor');

        $pord_date = $this->input->post('txt_pord_date');
        $pord_number = $this->input->post('txt_pord_no');

        /* =====================================po number========================================== */
        $pord_number = $this->m_purchase_order->create_po_number($pord_date);
        /* ========================================================================================== */

        $preq_date = $this->input->post('txt_preq_date');
        $preq_number = $this->input->post('txt_preq_no');
        $expected_date = $this->input->post('txt_expected_date');

        $shipment_id = $this->input->post('cbo_ship_via') == "" ? null : $this->input->post('cbo_ship_via');
        $termspayment_id = $this->input->post('cbo_terms') == "" ? null : $this->input->post('cbo_terms');
        $fob_id = $this->input->post('cbo_fob') == "" ? null : $this->input->post('cbo_fob');

        $billing_address = $this->input->post('txa_address');
        $shipping_address = $this->input->post('txa_ship_to');
        $currency_code = $this->input->post('hdn_currency_code');
        $currency_rate = $this->input->post('txt_currency_rate');
        $pord_desc = $this->input->post('txa_description');

        $taxes_status = $this->input->post('chk_taxtable') == '' ? 0 : $this->input->post('chk_taxtable');
        $intax_status = $this->input->post('chk_inclusive') == '' ? 0 : $this->input->post('chk_inclusive');

        $pord_ppn10 = $this->input->post('txt_ppn10_hide');
        $pord_pph22 = $this->input->post('txt_pph22_hide');
        $pord_pph23 = $this->input->post('txt_pph23_hide');

        $pord_ppn10_pcnt = $pord_ppn10 == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');
        $pord_pph22_pcnt = $pord_pph22 == 0 ? 0 : $this->input->post('hdn_pph22_pcnt');
        $pord_pph23_pcnt = $pord_pph23 == 0 ? 0 : $this->input->post('hdn_pph23_pcnt');

        $pord_subtotal = $this->input->post('txt_sub_total_hide');
        $pord_discount = $this->input->post('txt_discount_hide');
        $pord_estfreight = $this->input->post('txt_freight');
        $pord_totalamount = $this->input->post('txt_total_purchase_hide');

        $pord_totaldp = $this->input->post('txt_downpayment');
        $pord_dpstatus = $this->input->post('chk_vendorneeds') == '' ? 0 : $this->input->post('chk_vendorneeds');

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

        if (count($detail) > 0) {
            foreach ($detail as $row_check) {

                $ItemQtyPO = 0;
                $ItemQtyPR = 0;
                $TotalQtyPO = 0;

                $check_qty_from_pod_detail = $this->m_purchase_requisition->get_detail_sum_preq($row_check->PReqNumber, $row_check->ItemCode);

                $ItemQtyPO = $check_qty_from_pod_detail->TotalItemQtyPO; //Qty Suspend sudah ditambahkan di model
                $ItemQtyPR = $check_qty_from_pod_detail->TotalItemQtyPR;
                $TotalQtyPO = $row_check->ItemQty + $ItemQtyPO;

                if ($TotalQtyPO > $ItemQtyPR) {
                    $result['status'] = FALSE;
                    $result['message'] = "Transaksi gagal, Item Qty Purchase Order melebihi Item Qty Purchase Requisition, Untuk Item " . $row_check->ItemDesc . ", Qty PO : " . $TotalQtyPO . ", Qty PR : " . $ItemQtyPR . "";
                    echo json_encode($result);
                    die();
                }
            }
            /*
              Insert Group Po
             */
            $data_po = array(
                'BranchCode' => $branch_code,
                'VendorCode' => $vendor_code,
                'POrdDate' => date("Y-m-d", strtotime($pord_date)),
                'POrdNumber' => $pord_number,
                'PReqDate' => $preq_date,
                'PReqNumber' => $preq_number,
                'ExpectedDate' => date("Y-m-d", strtotime($expected_date)),
                'ShipmentID' => $shipment_id,
                'TermsPaymentID' => $termspayment_id,
                'FOBID' => $fob_id,
                'BillingAddress' => $billing_address,
                'ShippingAddress' => $shipping_address,
                'CurrencyCode' => $currency_code,
                'CurrencyRate' => $currency_rate,
                'POrdDesc' => $pord_desc,
                'POrdSubTotal' => $pord_subtotal,
                'POrdDiscount' => $pord_discount,
                'POrdPPn10Pcnt' => $pord_ppn10_pcnt,
                'POrdPPh22Pcnt' => $pord_pph22_pcnt,
                'POrdPPh23Pcnt' => $pord_pph23_pcnt,
                'POrdPPn10' => $pord_ppn10,
                'POrdPPh22' => $pord_pph22,
                'POrdPPh23' => $pord_pph23,
                'POrdEstFreight' => $pord_estfreight,
                'POrdTotalAmount' => $pord_totalamount,
                'POrdDPStatus' => $pord_dpstatus,
                'POrdTotalDP' => $pord_dpstatus == 0 ? 0 : $pord_totaldp,
                'POrdTaxesStatus' => $taxes_status,
                'POrdInTaxStatus' => $intax_status,
                'TransStatus' => 6,
                'CreatedBy' => $this->session->userdata("username"),
                'CreatedAt' => date('Y-m-d'),
                'LastUser' => $this->session->userdata("username")
            );

            //1. insert PO data
            $result_insert = $this->m_purchase_order->insert_all_table_new($data_po, $detail, $pord_number);
            //-------------------------------------------------------------------------------------------------------//

            if ($result_insert == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $pord_number);

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

        echo json_encode($result);
    }

    //public function insert() {
//		/*==================Deklar Variabel===============================================================*/
//        $branch_code		= $this->session->userdata('branch');
//        $vendor_code       	= $this->input->post('cbg_vendor');
//        
//        $pord_date         	= $this->input->post('txt_pord_date');
//        $pord_number        = $this->input->post('txt_pord_no');
//		
//		/*=====================================po number==========================================*/
//		$pord_number  		= $this->m_purchase_order->create_po_number($pord_date);
//		/*==========================================================================================*/
//		
//        $preq_date			= $this->input->post('txt_preq_date');        
//        $preq_number		= $this->input->post('txt_preq_no');
//        $expected_date		= $this->input->post('txt_expected_date');
//
//        $shipment_id   		= $this->input->post('cbo_ship_via')=="" ? null : $this->input->post('cbo_ship_via');		
//        $termspayment_id    = $this->input->post('cbo_terms')=="" ? null : $this->input->post('cbo_terms');
//        $fob_id				= $this->input->post('cbo_fob')=="" ? null : $this->input->post('cbo_fob');
//        
//        $billing_address	= $this->input->post('txa_address');
//        $shipping_address	= $this->input->post('txa_ship_to');
//        $currency_code      = $this->input->post('hdn_currency_code');
//        $currency_rate      = $this->input->post('txt_currency_rate');
//        $pord_desc          = $this->input->post('txa_description');
//        
//        $taxes_status		= $this->input->post('chk_taxtable') == '' ? 0 : $this->input->post('chk_taxtable');
//        $intax_status       = $this->input->post('chk_inclusive') == '' ? 0 : $this->input->post('chk_inclusive') ;
//
//        $pord_ppn10			= $this->input->post('txt_ppn10_hide');
//        $pord_pph22			= $this->input->post('txt_pph22_hide');
//        $pord_pph23			= $this->input->post('txt_pph23_hide');
//        
//        $pord_ppn10_pcnt    = $pord_ppn10 == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');        
//        $pord_pph22_pcnt    = $pord_pph22 == 0 ? 0 : $this->input->post('hdn_pph22_pcnt') ;
//        $pord_pph23_pcnt    = $pord_pph23 == 0 ? 0 : $this->input->post('hdn_pph23_pcnt');
//        
//        $pord_subtotal		= $this->input->post('txt_sub_total_hide');
//        $pord_discount		= $this->input->post('txt_discount_hide');
//        $pord_estfreight   	= $this->input->post('txt_freight');
//        $pord_totalamount   = $this->input->post('txt_total_purchase_hide');
//        
//        $pord_totaldp       = $this->input->post('txt_downpayment');        
//        $pord_dpstatus      = $this->input->post('chk_vendorneeds') == '' ? 0 : $this->input->post('chk_vendorneeds');
//
//        $detail_post        = $this->input->post('detail');
//        $detail             = json_decode($detail_post);
//		/*==========================End===================================================================================*/
//       
//        if(count($detail) > 0){  
//            $this->db->trans_begin();
//            
//			foreach($detail as $row_check){
//				
//				$ItemQtyPO 	= 0;
//				$ItemQtyPR 	= 0;
//				$TotalQtyPO = 0;
//				
//				$check_qty_from_pod_detail = $this->m_purchase_requisition->get_detail_sum_preq($row_check->PReqNumber, $row_check->ItemCode);
//				
//				$ItemQtyPO 	= $check_qty_from_pod_detail->TotalItemQtyPO;//Qty Suspend sudah ditambahkan di model
//				$ItemQtyPR 	= $check_qty_from_pod_detail->TotalItemQtyPR;
//				$TotalQtyPO = $row_check->ItemQty + $ItemQtyPO;
//				
//				if($TotalQtyPO > $ItemQtyPR){
//					$this->db->trans_rollback();
//					$result['status']       = FALSE;
//                	$result['message']      = "Transaksi gagal, Item Qty Purchase Order melebihi Item Qty Purchase Requisition, Untuk Item ".$row_check->ItemDesc.", Qty PO : ".$TotalQtyPO.", Qty PR : ".$ItemQtyPR."";
//					echo json_encode($result);
//					die();
//				}
//			}
//			/*
//				Insert Group Po
//			*/
//            $data_po = array (
//                            'BranchCode'            => $branch_code,
//                            'VendorCode'            => $vendor_code,
//                            'POrdDate'              => date("Y-m-d", strtotime($pord_date)),
//                            'POrdNumber'            => $pord_number,
//                            'PReqDate'              => $preq_date,
//                            'PReqNumber'            => $preq_number,
//                            'ExpectedDate'          => date("Y-m-d", strtotime($expected_date)),
//                            'ShipmentID'            => $shipment_id,
//                            'TermsPaymentID'        => $termspayment_id,
//                            'FOBID'                 => $fob_id,
//                            'BillingAddress'        => $billing_address,
//                            'ShippingAddress'       => $shipping_address,
//                            'CurrencyCode'          => $currency_code,
//                            'CurrencyRate'          => $currency_rate,
//                            'POrdDesc'              => $pord_desc,
//                            'POrdSubTotal'          => $pord_subtotal,
//                            'POrdDiscount'          => $pord_discount,
//                            'POrdPPn10Pcnt'         => $pord_ppn10_pcnt,
//                            'POrdPPh22Pcnt'         => $pord_pph22_pcnt,
//                            'POrdPPh23Pcnt'         => $pord_pph23_pcnt,
//                            'POrdPPn10'             => $pord_ppn10,
//                            'POrdPPh22'             => $pord_pph22,
//                            'POrdPPh23'             => $pord_pph23,
//                            'POrdEstFreight'        => $pord_estfreight,
//                            'POrdTotalAmount'       => $pord_totalamount,
//                            'POrdDPStatus'          => $pord_dpstatus,
//                            'POrdTotalDP'           => $pord_dpstatus == 0 ? 0 : $pord_totaldp,
//                            'POrdTaxesStatus'       => $taxes_status,
//                            'POrdInTaxStatus'       => $intax_status,
//                            'TransStatus'           => 6,
//							'CreatedBy' 			=> $this->session->userdata("username"),
//							'CreatedAt' 			=> date('Y-m-d'),
//                            'LastUser'              => $this->session->userdata("username")
//                        );
//
//            //1. insert PO data
//			$this->m_purchase_order->insert($data_po);
//            //-------------------------------------------------------------------------------------------------------//
//            
//			/*
//				Insert Detail PO
//			*/
//            foreach($detail as $row){
//				$detail_data_po = array(
//                                    'PReqDetailID'          => $row->PReqDetailID,
//                                    'PReqNumber'            => $row->PReqNumber,
//                                    'POrdNumber'            => $pord_number,
//                                    'ItemCode'              => $row->ItemCode,
//                                    'ItemDesc'              => $row->ItemDesc,
//                                    'itemUnit'              => $row->ItemUnit,
//                                    'itemQty'               => $row->ItemQty,
//                                    'ItemPrice'             => $row->ItemPrice,
//									'ItemDisc' 				=> $row->ItemDisc,
//                                    'ItemAmount'            => $row->ItemAmount_Hide,
//                                    'ItemTaxPPn10'          => $row->Item_PPn10,
//                                    'ItemTaxPPh22'          => $row->Item_PPh22,
//                                    'ItemTaxPPh23'          => $row->Item_PPh23,
//                                    'ItemTotalAmount'       => $row->ItemTotalAmount,
//                                    'ItemCategoryID'        => $row->ItemCategoryID,
//                                    'ItemCategoryCode'      => $row->ItemCategoryCode,
//                                    'ItemType'              => $row->ItemType,
//                                    'ItemStatus'            => $row->ItemStatus,
//                                    'ItemPPh22Status'       => $row->ItemPPh22Status,
//                                    'ItemPPh23Status'       => $row->ItemPPh23Status,                    
//                                    'ItemAdvNetDueIn'       => $row->ItemAdvNetDueIn,
//                                    'ItemPriceNTax'         => $row->ItemPriceNTax,
//                                    'LastUser'              => $this->session->userdata("username")				
//                                );
//
//                //2. insert PO Detail item data
//               $this->m_purchase_order->insert_detail($detail_data_po);
//                //-------------------------------------------------------------------------------------------------//
//                
//                $preqdetail     = $this->m_purchase_requisition->get_detail_item_by_id($row->PReqDetailID);
//                $newItemQtyPO   = $preqdetail->ItemQtyPO + $row->ItemQty;
//                
//                $detail_data_pr = array(					
//                                    'ItemQtyPO'         => $newItemQtyPO,
//                                    'LastUser'          => $this->session->userdata("username")					
//                                  );				
//
//                //3. update PReqDetail => item quantity PO
//                $this->m_purchase_requisition->update_detail($detail_data_pr, $row->PReqDetailID);
//            }			
//
//            /*=============================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, $pord_number);
//			}
//			else {
//				$this->db->trans_commit();
//				$result['status'] 		= TRUE;
//				$result['message']  	= get_notification_transaksi($this->name, 'insert', 1, $pord_number);
//			}
//			/*==================================end======================================================*/	
//        }
//        else{
//            $result['status']   = false;
//            $result['message']  = get_notification('no_count', 0);            
//        }
//
//        echo json_encode($result);
//    }

    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 {
                    $group_menu = $this->session->userdata('group_menu');

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

                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['jobtitle_status'] = $this->session->userdata('jobtitle_status');

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

                    $id = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());
                    $data['detail'] = $this->m_purchase_order->get_detail($id);
                    $data['taxes_ppn10'] = $this->m_taxes->get_by_code('PPN');
                    $data['taxes_pph22'] = $this->m_taxes->get_by_code('PPH22');

                    $preqdatetemp = explode(",", $data["detail"]->PReqDate);

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

                    $data["detail"]->PReqDate = implode(",", $preqdatetemp);

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

    public function update() {
        /* =====================================Deklar Variabel============================================================= */
        $pord_number = $this->input->post('txt_pord_no');
        $preq_number = $this->input->post('txt_preq_no');

        $shipping_address = $this->input->post('txa_ship_to');
        $currenccy_rate = $this->input->post('txt_currency_rate');

        $fob_id = $this->input->post('cbo_fob') == '' ? null : $this->input->post('cbo_fob');
        $termspayment_id = $this->input->post('cbo_terms') == '' ? null : $this->input->post('cbo_terms');
        $shipment_id = $this->input->post('cbo_ship_via') == '' ? null : $this->input->post('cbo_ship_via');
        $pord_desc = $this->input->post('txa_description');

        $taxes_status = $this->input->post('chk_taxtable');
        $intax_status = $this->input->post('chk_inclusive');

        $pord_ppn10 = $this->input->post('txt_ppn10_hide');
        $pord_pph22 = $this->input->post('txt_pph22_hide');
        $pord_pph23 = $this->input->post('txt_pph23_hide');

        $pord_ppn10_pcnt = $pord_ppn10 == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');
        $pord_pph22_pcnt = $pord_pph22 == 0 ? 0 : $this->input->post('hdn_pph22_pcnt');
        $pord_pph23_pcnt = $pord_pph23 == 0 ? 0 : $this->input->post('hdn_pph23_pcnt');

        $pord_subtotal = $this->input->post('txt_sub_total_hide');
        $pord_discount = $this->input->post('txt_discount_hide');
        $pord_estfreight = $this->input->post('txt_freight');
        $pord_totalamount = $this->input->post('txt_total_purchase_hide');

        $pord_dpstatus = $this->input->post('chk_vendorneeds');
        $pord_totaldp = $this->input->post('txt_downpayment');

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

        $detail_data_arr = array();
        $detail_data_preq = array();
        $result_update = array();

        $calculate_po_arr = array();
        $calculate_pr_arr = array();
        /* =========================End============================================================= */

        if (count($detail) > 0) {
            foreach ($detail as $row_check) {

                $ItemQtyPO = 0;
                $ItemQtyPR = 0;
                $TotalQtyPO = 0;

                $check_qty_from_pod_detail = $this->m_purchase_requisition->get_detail_sum_preq($row_check->PReqNumber, $row_check->ItemCode);

                $ItemQtyPO = $check_qty_from_pod_detail->TotalItemQtyPO;
                $ItemQtyPR = $check_qty_from_pod_detail->TotalItemQtyPR;
                $TotalQtyPO = ($row_check->ItemQty - $ItemQtyPO) + ($ItemQtyPO + $check_qty_from_pod_detail->ItemQtySpd);


                if ($TotalQtyPO > $ItemQtyPR) {
                    $this->db->trans_rollback();
                    $result['status'] = FALSE;
                    $result['message'] = "Transaksi gagal, Item Qty Purchase Order melebihi Item Qty Purchase Requisition, Untuk Item " . $row_check->ItemDesc . ", Qty PO : " . $TotalQtyPO . ", Qty PR : " . $ItemQtyPR . "";
                    echo json_encode($result);
                    die();
                }
            }
            /* ====================Update Group========================================================== */
            $data = array(
                'ShipmentID' => $shipment_id,
                'TermsPaymentID' => $termspayment_id,
                'FOBID' => $fob_id,
                'ShippingAddress' => $shipping_address,
                'CurrencyRate' => $currenccy_rate,
                'POrdDesc' => $pord_desc,
                'POrdSubTotal' => $pord_subtotal,
                'POrdDiscount' => $pord_discount,
                'POrdPPn10Pcnt' => $pord_ppn10_pcnt,
                'POrdPPh22Pcnt' => $pord_pph22_pcnt,
                'POrdPPh23Pcnt' => $pord_pph23_pcnt,
                'POrdPPn10' => $pord_ppn10,
                'POrdPPh22' => $pord_pph22,
                'POrdPPh23' => $pord_pph23,
                'POrdEstFreight' => $pord_estfreight,
                'POrdTotalAmount' => $pord_totalamount,
                'POrdDPStatus' => $pord_dpstatus,
                'POrdTotalDP' => $pord_dpstatus == 0 ? 0 : $pord_totaldp,
                'POrdTaxesStatus' => $taxes_status,
                'POrdInTaxStatus' => $intax_status,
                'TransStatus' => 6,
                'LastUser' => $this->session->userdata("username")
            );

            /* ========================Update Detail======================================================= */
            foreach ($detail as $row) {
                //2. Update PO Detail
                $detail_data = array(
                    'POrdDetailID' => $row->POrdDetailID,
                    'ItemQty' => $row->ItemQty,
                    'ItemPrice' => $row->ItemPrice,
                    'ItemDisc' => $row->ItemDisc,
                    'ItemAmount' => $row->ItemAmount_Hide,
                    'ItemTaxPPn10' => $row->ItemTaxPPn10,
                    'ItemTaxPPh22' => $row->ItemTaxPPh22,
                    'ItemTaxPPh23' => $row->ItemTaxPPh23,
                    'ItemTotalAmount' => $row->ItemTotalAmount,
                    'ItemPriceNTax' => $row->ItemPriceNTax,
					'ItemCodeVendor'=> $row->ItemCodeVendor,
                    'LastUser' => $this->session->userdata("username")
                );

                $detail_data_arr[] = $detail_data;
                //-------------------------------------------------------------------------------------------------------//
                //3. Update PReq Detail -> Item Qauntity PO
                $preqdetail = $this->m_purchase_requisition->get_detail_item_by_id($row->PReqDetailID);
                if ($row->ItemQty > $row->ItemQty_Old) {
                    $TotalNewQty_PO = doubleval($preqdetail->ItemQtyPO - $row->ItemQty_Old) + doubleval($row->ItemQty);
                    $detail_data_pr = array(
                        'PReqDetailID' => $row->PReqDetailID,
                        'ItemQtyPO' => $TotalNewQty_PO,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $detail_data_preq[] = $detail_data_pr;
                } else if ($row->ItemQty < $row->ItemQty_Old) {
                    $TotalNewQty_PO = doubleval($preqdetail->ItemQtyPO - $row->ItemQty_Old) + doubleval($row->ItemQty);
                    $detail_data_pr = array(
                        'PReqDetailID' => $row->PReqDetailID,
                        'ItemQtyPO' => $TotalNewQty_PO,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $detail_data_preq[] = $detail_data_pr;
                }
                //-------------------------------------------------------------------------------------------------------//
            }
            /* =====================End================================================================================= */

            /* ===============Delete per grid jika tombol delete di klik ===================== */
            if (count($detail_id) > 0) {
                foreach ($detail_id as $POrdDetailID) {
                    $this->m_purchase_order->delete_detail($POrdDetailID);
                    //------------------------------------------------------------------------------------------------------------//
                    //2. Update PreqNumber pada PO
                    $get_preqdetail = $this->m_purchase_order->get_detail_distinct($pord_number);
                    $new_preq_no = '';
                    $new_preq_date = '';

                    foreach ($get_preqdetail as $row) {
                        $new_preq_no = $new_preq_no . $row->PReqNumber . ', ';
                        $new_preq_date = $new_preq_date . $row->PReqDate . ', ';
                    }

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

                    $data_po = array(
                        'PReqNumber' => $new_preq_no,
                        'PReqDate' => $new_preq_date,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $calculate_po_arr[] = $data_po;
                    //------------------------------------------------------------------------------------------------------------//  
                }

                for ($x = 0; $x < count($detail_qty['a']); $x++) {
                    $preq_detail = $this->m_purchase_requisition->get_detail_item_by_id($detail_qty['a'][$x]);
                    $new_qty_po = $preq_detail->ItemQtyPO - $detail_qty['b'][$x];

                    //1. Update ItemQtyPO pada PReqDetail
                    $data_preq_detail = array(
                        'PreqDetailID' => $detail_qty['a'][$x],
                        'ItemQtyPO' => $new_qty_po,
                        'LastUser' => $this->session->userdata("username")
                    );
                    $calculate_pr_arr[] = $data_preq_detail;
                }
            }
            /* ====================End============================================================================ */

            //1. Update Purchase Order
            $result_update = $this->m_purchase_order->update_all_new_table($data, $detail_data_arr, $detail_data_preq, $pord_number, $calculate_po_arr, $calculate_pr_arr, $detail_id);
            /* =================================End==================================================== */

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

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

        echo json_encode($result);
    }

    //public function update() {
//        
//
////        $preq_number		= $this->input->post('txt_preq_no');
////        $pord_date              = $this->input->post('txt_pord_date');
////        $preq_date		= $this->input->post('txt_preq_date');
////        $vendor_code            = $this->input->post('cbg_vendor');
////        $billing_address	= $this->input->post('txa_address');
////        $expected_date		= $this->input->post('txt_expected_date');
//		/*=====================================Deklar Variabel=============================================================*/
//		$pord_number        = $this->input->post('txt_pord_no');
//		$preq_number        = $this->input->post('txt_preq_no');
//		
//        $shipping_address	= $this->input->post('txa_ship_to');
//        $currenccy_rate     = $this->input->post('txt_currency_rate');
//        
//        $fob_id				= $this->input->post('cbo_fob') == '' ? null : $this->input->post('cbo_fob');
//        $termspayment_id    = $this->input->post('cbo_terms') == '' ? null : $this->input->post('cbo_terms');
//        $shipment_id   		= $this->input->post('cbo_ship_via') == '' ? null : $this->input->post('cbo_ship_via');
//        $pord_desc 			= $this->input->post('txa_description');
//        
//        $taxes_status		= $this->input->post('chk_taxtable');
//        $intax_status       = $this->input->post('chk_inclusive');
//         
//        $pord_ppn10         = $this->input->post('txt_ppn10_hide');
//        $pord_pph22         = $this->input->post('txt_pph22_hide');
//        $pord_pph23         = $this->input->post('txt_pph23_hide');
//        
//        $pord_ppn10_pcnt    = $pord_ppn10 == 0 ? 0 : $this->input->post('hdn_ppn10_pcnt');        
//        $pord_pph22_pcnt    = $pord_pph22 == 0 ? 0 : $this->input->post('hdn_pph22_pcnt') ;
//        $pord_pph23_pcnt    = $pord_pph23 == 0 ? 0 : $this->input->post('hdn_pph23_pcnt');
//        
//        $pord_subtotal		= $this->input->post('txt_sub_total_hide');
//        $pord_discount		= $this->input->post('txt_discount_hide');
//        $pord_estfreight    = $this->input->post('txt_freight');
//        $pord_totalamount   = $this->input->post('txt_total_purchase_hide');
//
//        $pord_dpstatus      = $this->input->post('chk_vendorneeds');
//        $pord_totaldp       = $this->input->post('txt_downpayment');
//        
//        $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);
//		/*=========================End=============================================================*/
//
//        if(count($detail) > 0){
//            $this->db->trans_begin();
//				
//			foreach($detail as $row_check){
//				
//				$ItemQtyPO 	= 0;
//				$ItemQtyPR 	= 0;
//				$TotalQtyPO = 0;
//				
//				$check_qty_from_pod_detail = $this->m_purchase_requisition->get_detail_sum_preq($row_check->PReqNumber, $row_check->ItemCode);
//				
//				$ItemQtyPO 	= $check_qty_from_pod_detail->TotalItemQtyPO;
//				$ItemQtyPR 	= $check_qty_from_pod_detail->TotalItemQtyPR;
//				$TotalQtyPO = ($row_check->ItemQty - $ItemQtyPO) + ($ItemQtyPO + $check_qty_from_pod_detail->ItemQtySpd);
//				
//				
//				if($TotalQtyPO > $ItemQtyPR){
//					$this->db->trans_rollback();
//					$result['status']       = FALSE;
//                	$result['message']      = "Transaksi gagal, Item Qty Purchase Order melebihi Item Qty Purchase Requisition, Untuk Item ".$row_check->ItemDesc.", Qty PO : ".$TotalQtyPO.", Qty PR : ".$ItemQtyPR."";
//					echo json_encode($result);
//					die();
//				}
//			}
//			/*====================Update Group==========================================================*/
//            $data = array (
//                        'ShipmentID'		=> $shipment_id,
//                        'TermsPaymentID'    => $termspayment_id,
//                        'FOBID' 			=> $fob_id,
//                        'ShippingAddress' 	=> $shipping_address,
//                        'CurrencyRate'      => $currenccy_rate,
//                        'POrdDesc'			=> $pord_desc,
//                        'POrdSubTotal'		=> $pord_subtotal,
//                        'POrdDiscount'		=> $pord_discount,
//                        'POrdPPn10Pcnt'     => $pord_ppn10_pcnt,
//                        'POrdPPh22Pcnt'     => $pord_pph22_pcnt,
//                        'POrdPPh23Pcnt'    	=> $pord_pph23_pcnt,
//                        'POrdPPn10'			=> $pord_ppn10,
//                        'POrdPPh22'			=> $pord_pph22,
//                        'POrdPPh23'			=> $pord_pph23,
//                        'POrdEstFreight'	=> $pord_estfreight,
//                        'POrdTotalAmount'	=> $pord_totalamount,
//                        'POrdDPStatus'      => $pord_dpstatus,
//                        'POrdTotalDP'       => $pord_dpstatus == 0 ? 0 : $pord_totaldp,
//                        'POrdTaxesStatus'  	=> $taxes_status,
//                        'POrdInTaxStatus'   => $intax_status,
//                        'TransStatus'       => 6,
//                        'LastUser' 			=> $this->session->userdata("username")
//                    );
//
//            //1. Update Purchase Order
//          $this->m_purchase_order->update($data, $pord_number);
//            /*=================================End====================================================*/
//			
//			/*========================Update Detail=======================================================*/
//            foreach($detail as $row){
//				//2. Update PO Detail
//                $detail_data = array(
//                                'ItemQty'           => $row->ItemQty,
//                                'ItemPrice'         => $row->ItemPrice,
//								'ItemDisc' 			=> $row->ItemDisc,
//                                'ItemAmount'        => $row->ItemAmount_Hide,
//                                'ItemTaxPPn10'      => $row->ItemTaxPPn10,
//                                'ItemTaxPPh22'      => $row->ItemTaxPPh22,
//                                'ItemTaxPPh23'      => $row->ItemTaxPPh23,
//                                'ItemTotalAmount'   => $row->ItemTotalAmount,
//                                'ItemPriceNTax'     => $row->ItemPriceNTax,
//                                'LastUser'          => $this->session->userdata("username")				
//                                );  
//
//                $this->m_purchase_order->update_detail($detail_data, $row->POrdDetailID);
//                //-------------------------------------------------------------------------------------------------------//
//                
//                //3. Update PReq Detail -> Item Qauntity PO
//                $preqdetail     = $this->m_purchase_requisition->get_detail_item_by_id($row->PReqDetailID);
//				if($row->ItemQty > $row->ItemQty_Old){
//					$TotalNewQty_PO = intval($preqdetail->ItemQtyPO - $row->ItemQty_Old) + intval($row->ItemQty);
//					$detail_data_pr = array(
//                                    'ItemQtyPO' => $TotalNewQty_PO,				
//                                    'LastUser' 	=> $this->session->userdata("username")					
//                                  );				
//
//                	$this->m_purchase_requisition->update_detail($detail_data_pr, $row->PReqDetailID);
//				
//				}
//				else if($row->ItemQty < $row->ItemQty_Old){
//					$TotalNewQty_PO = intval($preqdetail->ItemQtyPO - $row->ItemQty_Old) + intval($row->ItemQty);
//					$detail_data_pr = array(
//                                    'ItemQtyPO' => $TotalNewQty_PO,				
//                                    'LastUser' 	=> $this->session->userdata("username")					
//                                  );				
//
//                	$this->m_purchase_requisition->update_detail($detail_data_pr, $row->PReqDetailID);
//				}
//                //-------------------------------------------------------------------------------------------------------//
//            }
//			
//			/*=====================End=================================================================================*/
//			
//			/*===============Delete per grid jika tombol delete di klik =====================*/
//			
//			//print_r($detail_qty);
//			
//
//			if(count($detail_id)>0){
//				foreach ($detail_id as $POrdDetailID) {
//					
//					
//					$this->m_purchase_order->delete_detail($POrdDetailID);
//					//------------------------------------------------------------------------------------------------------------//
//					
//					//2. Update PreqNumber pada PO
//					$get_preqdetail = $this->m_purchase_order->get_detail_distinct($pord_number);
//					$new_preq_no    = '';
//					$new_preq_date  = '';
//					
//					foreach($get_preqdetail as $row) {
//						$new_preq_no    = $new_preq_no . $row->PReqNumber . ', ';
//						$new_preq_date  = $new_preq_date . $row->PReqDate . ', ';
//					}
//		
//					if($new_preq_no != ''){$new_preq_no = substr($new_preq_no, 0, (intval(strlen($new_preq_no)) - 2));}
//					if($new_preq_date != ''){$new_preq_date = substr($new_preq_date, 0, (intval(strlen($new_preq_date)) - 2));}
//								
//					$data_po = array(
//								'PReqNumber'    => $new_preq_no,
//								'PReqDate'      => $new_preq_date,
//								'LastUser'      => $this->session->userdata("username")					
//							);
//					
//					$this->m_purchase_order->update($data_po, $pord_number);
//					//------------------------------------------------------------------------------------------------------------//  
//				}
//				
//				for($x = 0; $x < count($detail_qty['a']); $x++) {
//					$preq_detail    = $this->m_purchase_requisition->get_detail_item_by_id($detail_qty['a'][$x]);
//					$new_qty_po     = $preq_detail->ItemQtyPO - $detail_qty['b'][$x];
//					
//					//1. Update ItemQtyPO pada PReqDetail
//					$data_preq_detail = array(
//											'ItemQtyPO'     => $new_qty_po,				
//											'LastUser'      => $this->session->userdata("username")					
//										);
//		
//					$this->m_purchase_requisition->update_detail($data_preq_detail, $detail_qty['a'][$x]);
//				}
//			}
//			/*====================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, 'update', 0, $pord_number);
//			}
//			else {
//				$this->db->trans_commit();
//				$result['status'] 		= TRUE;
//				$result['message']  	= get_notification_transaksi($this->name, 'update', 1, $pord_number);
//			}
//			/*==================================end======================================================*/	
//        }
//        else {
//            $result['status'] = false;
//            $result['message'] = get_notification_transaksi($this->name, 'update', 0);
//        }
//        
//        echo json_encode($result);
//    }

    function delete_row() {
        $preq_detail_id = $this->input->post('preq_detail_id');
        $pord_detail_id = $this->input->post('pord_detail_id');
        $pord_item_qty = $this->input->post('pord_item_qty');

        $pord_number = $this->input->post('pord_number');
        $pord_subtotal = $this->input->post('pord_subtotal');
        $pord_discount = $this->input->post('pord_discount');
        $pord_ppn10 = $this->input->post('pord_ppn10');
        $pord_pph22 = $this->input->post('pord_pph22');
        $pord_pph23 = $this->input->post('pord_pph23');
        $pord_estfreight = $this->input->post('pord_freight');
        $pord_totalamount = $this->input->post('pord_total');

        if (!empty($pord_detail_id)) {
            $this->db->trans_begin();

            $preq_detail = $this->m_purchase_requisition->get_detail_item_by_id($preq_detail_id);
            $new_qty_po = $preq_detail->ItemQtyPO - $pord_item_qty;

            //1. Update ItemQtyPO pada PReqDetail
            $data_preq_detail = array(
                'ItemQtyPO' => $new_qty_po,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_requisition->update_detail($data_preq_detail, $preq_detail_id);
            //------------------------------------------------------------------------------------------------------------//
            //2. Update PurchaseOrder for data amount             
            $data_pord = array(
                'POrdSubTotal' => $pord_subtotal,
                'POrdDiscount' => $pord_discount,
                'POrdPPn10' => $pord_ppn10,
                'POrdPPh22' => $pord_pph22,
                'POrdPPh23' => $pord_pph23,
                'POrdEstFreight' => $pord_estfreight,
                'POrdTotalAmount' => $pord_totalamount);

            $this->m_purchase_order->update($data_pord, $pord_number);
            //------------------------------------------------------------------------------------------------------------//            
            //3. Delete POrdDetail
            $this->m_purchase_order->delete_detail($pord_detail_id);
            //------------------------------------------------------------------------------------------------------------//            
            //4. Update PreqNumber pada PO
            $get_preqdetail = $this->m_purchase_order->get_detail_distinct($pord_number);
            $new_preq_no = '';
            $new_preq_date = '';

            foreach ($get_preqdetail as $row) {
                $new_preq_no = $new_preq_no . $row->PReqNumber . ', ';
                $new_preq_date = $new_preq_date . $row->PReqDate . ', ';
            }

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

            $data_po = array(
                'PReqNumber' => $new_preq_no,
                'PReqDate' => $new_preq_date,
                'LastUser' => $this->session->userdata("username")
            );

            $this->m_purchase_order->update($data_po, $pord_number);
            //------------------------------------------------------------------------------------------------------------//            

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

    public function approval() {
        try {
            if (in_array($this->session->userdata("jobtitle_status"), $this->jobtitle_status)) {
                /* =======================Deklar variabel========================================= */
                $trans_status = 1;
                $branch_code = $this->session->userdata('branch');
                $vendor_code = $this->input->post('VendorCode');
                $status = $this->input->post('Status');

                $pord_number = $this->input->post('POrdNumber');
                $pord_date = $this->input->post('POrdDate');
                $preq_number = $this->input->post('PReqNumber');
                $number_preq = explode(",", $preq_number);

                $currency_code = $this->input->post('CurrencyCode');
                $currency_rate = $this->input->post('CurrencyRate');
                $down_payment = $this->input->post('DownPayment');
                $sub_total = $this->input->post('SubTotal');

                $detail_post = $this->input->post('Detail');
                $detail = json_decode($detail_post);
                $arr_data_preq = array();
                $arr_data_payment = array();
                $arr_data_po = array();
                $result_approve = 0;
                /* =================================End============================================== */
				
				$this->db->trans_begin();
				
                $data = $this->m_purchase_order->get_detail($pord_number);
                if ($status == 1) {
                    /*
                      Cek Concuren For Approval Mgr
                     */
                    $get_employee = $this->m_employee->get_detail($data->AppLevel1Code);
                    if (($data->AppLevel1Code != NULL)) {
                        throw new Exception('Maaf Transaksi gagal di Approve, karena transaksi sudah di approve terlebih dahulu oleh, ' . $get_employee->EmployeeName . ' pada tanggal ' . date("d-m-Y", strtotime($data->AppLevel1Date)) . '');
                    	$this->db->trans_rollback();
					}
                    /* =========================End======================================== */
                } else {
                    /*
                      Cek Concuren For Approval Dir
                     */
                    $get_employee = $this->m_employee->get_detail($data->AppLevel2Code);
                    if (($data->AppLevel2Code != NULL)) {
                        throw new Exception('Maaf Transaksi gagal di Approve, karena transaksi sudah di approve terlebih dahulu oleh, ' . $get_employee->EmployeeName . ' pada tanggal ' . date("d-m-Y", strtotime($data->AppLevel2Date)) . '');
                    	$this->db->trans_rollback();
					}
                    /* =========================End======================================== */
                }
                /*
                  status = 1 jika po pertama dibust maka hide text status 1
                 */
                if ($status == 1) {
                    if ($data->AppLevel2Status != 1) {
                        $trans_status = 5;
                    }
                } else {
                    if ($data->AppLevel1Status != 1) {
                        $trans_status = 4;
                    }
                }
                /* ===================End===================================== */

                if ($trans_status == 1) {
                    if (($data->POrdDPStatus == 1) & ($data->POrdTotalDP - $data->PPayTotalDP > 0)) {
                        $trans_status = 0;
                    }

                    //1. Update Purhcase Requisition Status
                    $TotalQtyPO_On_PO = 0;
                    $TotalQtySpd_On_PR = 0;
                    $get_pr_set_finish = 0;

                    foreach ($number_preq as $key => $value) {
                        $TotalQtyPO_On_PO = $this->m_purchase_requisition->set_finish($value);
                        $TotalQtySpd_On_PR = $this->m_purchase_requisition->get_total_qty_pr_spd($value);
                        $get_pr_set_finish = $this->m_purchase_requisition->set_finish_pr($value);
                        $get_qty_po = $this->m_purchase_requisition->get_qty_purchase_order($value, $pord_number);
                        $total_qty_po = ($TotalQtyPO_On_PO + $TotalQtySpd_On_PR) + $get_qty_po;

                        if ($total_qty_po == $get_pr_set_finish->TotalQtyPR) {
                            if ($get_pr_set_finish->TransStatus != 8) {
                                $data_prq = array(
                                   // 'PReqNumber' => $value,
                                    'TransStatus' => 2,
                                    'LastUser' => $this->session->userdata("username")
                                );
                                //$arr_data_preq[] = $data_prq;
                                $this->m_purchase_requisition->update($data_prq, $value);
                            }
                        } else {
                            $data_prq = array(
                                //'PReqNumber' => $value,
                                'TransStatus' => 1,
                                'LastUser' => $this->session->userdata("username")
                            );
                            //$arr_data_preq[] = $data_prq;
                           $this->m_purchase_requisition->update($data_prq, $value);
                        }
                    }
                    //------------------------------------------------------------------------------------------------------//
                    //2. Insert Payment DP into InvoicePayment
                    if ($down_payment > 0) {
                        /* ===========Deklar variabel for DP================== */
                        $AssetAmount = array();
                        $AssetCategoryID = array();
                        $AssetCategoryCode = array();
                        $total_loop = 0;
                        $total_ratio = 0;
                        /* ===============End================================= */

                        //$this->m_purchase_invoice->delete_payment($pord_number);

                        foreach ($detail as $row) {
                            @$AssetType[$row->ItemStatus] = $row->ItemType;
                            @$AssetAmount[$row->ItemStatus] += $row->ItemAmount;
                            @$AssetCategoryID[$row->ItemStatus] = $row->ItemCategoryID;
                            @$AssetCategoryCode[$row->ItemStatus] = $row->ItemCategoryCode;
                        }
                        //------------------------------------------------------------------------------------------------//

                        $total_records = count(@$AssetAmount);

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

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

                            $advance_ratio = $down_payment * ($item_ratio / 100);
                            $total_ratio = $total_ratio + $item_ratio;

                            $data_payment = array(
                                'BranchCode' => $branch_code,
                                'VendorCode' => $vendor_code,
                                'InvoiceNumber' => $pord_number,
                                'InvoiceDate' => date("Y-m-d", strtotime($pord_date)),
                                'InvoiceCurrCode' => $currency_code,
                                'InvoiceCurrRate' => $currency_rate,
                                'InvoiceFiscalRate' => 1,
                                'InvoicePurchase' => doubleval($advance_ratio),
                                'InvoiceTotalDP' => 0,
                                'InvoiceAmount' => doubleval($advance_ratio),
                                'InvoiceOwing' => doubleval($advance_ratio),
                                'ItemCategoryRatio' => $item_ratio,
                                'ItemCategoryID' => @$AssetCategoryID[$key],
                                'ItemCategoryCode' => @$AssetCategoryCode[$key],
                                'ItemType' => @$AssetType[$key],
                                'ItemStatus' => $key,
                                'InvoiceType' => 1,
                                'PPnFiscalStatus' => 0,
                                'LastUser' => $this->session->userdata("username")
                            );
                            //$arr_data_payment[] = $data_payment;
                            $this->m_purchase_order->insert_payment($data_payment);
                        }
                    }
                    //------------------------------------------------------------------------------------------------------//
                }

                /* =======================Update Status Trans status========================================= */
                if ($status == 1) {
                    $data_po = array(
                        'TransStatus' => $trans_status,
                        'AppLevel1Status' => 1,
                        'AppLevel1Code' => $this->session->userdata("username"),
                        'AppLevel1Date' => date("Y-m-d"),
                        'LastUser' => $this->session->userdata("username")
                    );
                    //$arr_data_po[] = $data_po;
                } else {
                    $data_po = array(
                        'TransStatus' => $trans_status,
                        'AppLevel2Status' => 1,
                        'AppLevel2Code' => $this->session->userdata("username"),
                        'AppLevel2Date' => date("Y-m-d"),
                        'LastUser' => $this->session->userdata("username")
                    );
                    //$arr_data_po[] = $data_po;
                }

                //3.Update Purchase Order for Status only
                $this->m_purchase_order->update($data_po, $pord_number);
                /* =========================End============================================================== */

                /*
                  Update approval
                 */
                //$result_approve = $this->m_purchase_order->approval_update_table($arr_data_preq, $arr_data_po, $arr_data_payment, $status, $pord_number);
                /* ================End================================ */

                /* =============================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);
				}
                echo json_encode($result);
                /* ==================================end====================================================== */
            }
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    function reverse_data_detail() {
        try {
            $pord_number = $this->input->post('txt_pord_no');
			$detail_post		= $this->input->post('detail');
			$detail				= json_decode($detail_post);
			
            $result_approve = 0;
            /*
              Check Kondisi apakah transaksi ini sudah di buat di RI
             */
            $get_detail_preq = $this->m_custom->check_item_reverse($pord_number, 'at_receiveitem', 'at_precdetail', 'PRecNumber', 'POrdNumber');
            $get_dp_for_reverse = $this->m_custom->check_dp_for_reverse($pord_number, 'at_ppaydetail','PInvNumber','at_purchasepayment','PPayNumber');
			$get_no_transaction = $this->m_purchase_order->get_old_no_transaaction($pord_number);
			
            if ($get_detail_preq) {
                throw new Exception(msg_check_po_reverse('Receive Item'));
            } else if ($get_dp_for_reverse) {
                throw new Exception(msg_check_dp_reverse($pord_number, 'Purchase Payment'));
            }
			else if($get_no_transaction->OldPOrdNumber != ""){
				throw new Exception("Transaksi gagal di reverse, karena item ini adalah transaksi dari import file");
			}

            /*
              Rubah status
             */
            $data = array(
                'TransStatus' => 6,
                'AppLevel1Status' => 0,
                'AppLevel1Code' => NULL,
                'AppLevel1Date' => NULL,
                'AppLevel2Status' => 0,
                'AppLevel2Code' => NULL,
                'AppLevel2Date' => NULL,
                'LastUser' => $this->session->userdata("username")
            );
            $this->transaction['reverse_po']['data'] = $data;
            $this->transaction['reverse_po']['POrdNumber'] = $pord_number;
            /* =========================END========================= */
			
			foreach($detail as $row_detail){
				$data_group = array(
					'TransStatus' => 1,
					'LastUser' => $this->session->userdata("username")
				);
				
				$this->transaction['update_group']['data'][] = $data_group;
            	$this->transaction['update_group']['PReqNumber'][] = $row_detail->PReqNumber;
			}
			
            /* =============================trans roll back dan trans commit============================/ */
            $result_approve = $this->m_purchase_order->approved_reverse($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $pord_number);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $pord_number);
            }
            /* ==================================end====================================================== */

            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    function approval_by_pass() {
        try {
            $trans_status = 1;
            $branch_code = $this->session->userdata('branch');
            $vendor_code = $this->input->post('VendorCode');
            $status = $this->input->post('Status');

            $pord_number = $this->input->post('POrdNumber');
            $pord_date = $this->input->post('POrdDate');
            $preq_number = $this->input->post('PReqNumber');
            $number_preq = explode(",", $preq_number);

            $currency_code = $this->input->post('CurrencyCode');
            $currency_rate = $this->input->post('CurrencyRate');
            $down_payment = $this->input->post('DownPayment');
            $sub_total = $this->input->post('SubTotal');

            $detail_post = $this->input->post('Detail');
            $detail = json_decode($detail_post);
            $arr_data_preq = array();
            $arr_data_payment = array();
            $arr_data_po = array();
            $result_approve = 0;
            $Sum_Downpayment = 0;
			
			$get_receive_item = $this->m_receive_item->get_receive_item($pord_number);
			
			if($get_receive_item){
				throw new Exception("Transaksi gagal di By Pass, PO dengan No ".$pord_number." mempunyai RI Silahkan Reverse dan Suspen RI");
			}
			
            $get_purchase_payment = $this->m_purchase_payment->get_purchase_payment_for_dp($pord_number, $vendor_code);
            if ($get_purchase_payment == 1) {
                throw new Exception(msg_check_bypass_dp('Purchase Payment'));
            }

            $get_invoice_payment = $this->m_purchase_order->get_invoice_payment($pord_number);
            foreach ($get_invoice_payment as $row_payment) {
                $TotalPayment = $row_payment->PaymentAmount + $row_payment->PaymentRounded;
                $TotalOwing_New = ($row_payment->PaymentAmount + $row_payment->PaymentRounded + $row_payment->InvoiceOwing) - $row_payment->InvoiceAmount;

                $data_payment = array(
                    'InvoiceAmount' => doubleval($TotalPayment),
                    'InvoicePurchase' => doubleval($TotalPayment),
                    'InvoiceOwing' => doubleval($TotalOwing_New),
                    'LastUser' => $this->session->userdata('username')
                );

                $this->transaction['update_payment']['data'][] = $data_payment;
                $this->transaction['update_payment']['POrdNumber'][] = $pord_number;

                $Sum_Downpayment += $TotalPayment;
            }

            $data_po = array(
                'POrdTotalDP' => $Sum_Downpayment,
                'TransStatus' => $trans_status,
                'LastUser' => $this->session->userdata("username")
            );

            $this->transaction['update_group']['data'] = $data_po;
            $this->transaction['update_group']['POrdNumber'] = $pord_number;

            $result_byepass = $this->m_purchase_order->approved_by_pass($this->transaction);

            $this->transaction = [];

            /* =============================trans roll back dan trans commit============================/ */
            if ($result_byepass == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification('by_pass_dp ', 0);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification('by_pass_dp', 1);
            }
            /* ==================================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)){                        
//            /*=======================Deklar variabel=========================================*/
//			$this->db->trans_begin();
//
//            $trans_status       = 1;
//            $branch_code        = $this->session->userdata('branch');            
//            $vendor_code        = $this->input->post('VendorCode');
//            $status             = $this->input->post('Status');
//            
//            $pord_number        = $this->input->post('POrdNumber');	
//            $pord_date          = $this->input->post('POrdDate');            
//            $preq_number        = $this->input->post('PReqNumber');
//            $number_preq        = explode(",", $preq_number);
//
//            $currency_code      = $this->input->post('CurrencyCode');	
//            $currency_rate      = $this->input->post('CurrencyRate');	
//            $down_payment       = $this->input->post('DownPayment');	
//            $sub_total          = $this->input->post('SubTotal');
//
//            $detail_post        = $this->input->post('Detail');
//            $detail             = json_decode($detail_post);    
//			/*=================================End==============================================*/ 
//			           
//            $data               = $this->m_purchase_order->get_detail($pord_number);
//			if($status == 1){
//				/*
//					Cek Concuren For Approval Mgr
//				*/
//				$get_employee = $this->m_employee->get_detail($data->AppLevel1Code);
//				if(($data->AppLevel1Code != NULL)){
//					$result['status']   = false;
//					$result['message']  = 'Maaf Transaksi gagal di Approve, karena transaksi sudah di approve terlebih dahulu oleh, '.$get_employee->EmployeeName.' pada tanggal '.date("d-m-Y", strtotime($data->AppLevel1Date)).'';
//					
//					echo json_encode($result);
//					die();
//				}
//				/*=========================End========================================*/
//			}
//			else{
//				/*
//					Cek Concuren For Approval Dir
//				*/
//				$get_employee = $this->m_employee->get_detail($data->AppLevel2Code);
//				if(($data->AppLevel2Code != NULL)){
//					$result['status']   = false;
//					$result['message']  = 'Maaf Transaksi gagal di Approve, karena transaksi sudah di approve terlebih dahulu oleh, '.$get_employee->EmployeeName.' pada tanggal '.date("d-m-Y", strtotime($data->AppLevel2Date)).'';
//					
//					echo json_encode($result);
//					die();
//				}
//				/*=========================End========================================*/
//			}
//			/*
//				status = 1 jika po pertama dibust maka hide text status 1
//			*/
//            if($status == 1) {
//                if($data->AppLevel2Status != 1) {$trans_status = 5;}
//            }
//            else {
//                if($data->AppLevel1Status != 1) {$trans_status = 4;}
//            }
//			/*===================End=====================================*/
//
//            if($trans_status == 1){
//                if (($data->POrdDPStatus == 1) & ($data->POrdTotalDP - $data->PPayTotalDP > 0)){
//                    $trans_status = 0;                    
//                }
//
//                //1. Update Purhcase Requisition Status
//				$TotalQtyPO_On_PO 	= 0;
//				$TotalQtySpd_On_PR 	= 0;
//				$get_pr_set_finish 	= 0;
//				
//                foreach($number_preq as $key => $value){
//					$TotalQtyPO_On_PO 	= $this->m_purchase_requisition->set_finish($value);
//					$TotalQtySpd_On_PR 	= $this->m_purchase_requisition->get_total_qty_pr_spd($value);
//					$get_pr_set_finish 	= $this->m_purchase_requisition->set_finish_pr($value);
//					$get_qty_po 		= $this->m_purchase_requisition->get_qty_purchase_order($value, $pord_number);
//					$total_qty_po 		= ($TotalQtyPO_On_PO + $TotalQtySpd_On_PR) + $get_qty_po;
//					
//					if($total_qty_po == $get_pr_set_finish->TotalQtyPR){
//						if ($get_pr_set_finish->TransStatus != 8) {
//							$data_prq = array (
//                            	'TransStatus'   => 2,
//                            	'LastUser'      => $this->session->userdata("username")
//                            );
//                    		$this->m_purchase_requisition->update($data_prq, $value);
//						}
//					}
//					else{
//						$data_prq = array (
//							'TransStatus'   => 1,
//							'LastUser'      => $this->session->userdata("username")
//						);
//                    	$this->m_purchase_requisition->update($data_prq, $value);
//					}
//                } 
//                //------------------------------------------------------------------------------------------------------//
//                                
//                //2. Insert Payment DP into InvoicePayment
//                if($down_payment > 0) {
//                    /*===========Deklar variabel for DP==================*/
//					$AssetAmount        = array();
//                    $AssetCategoryID    = array();
//                    $AssetCategoryCode  = array();
//                    $total_loop         = 0;
//                    $total_ratio        = 0;
//					/*===============End=================================*/
//					
//                    $this->m_purchase_invoice->delete_payment($pord_number);
//                    
//                    foreach($detail as $row){
//                        @$AssetType[$row->ItemStatus]          += $row->ItemType;                    
//                        @$AssetAmount[$row->ItemStatus]        += $row->ItemAmount;                    
//                        @$AssetCategoryID[$row->ItemStatus]     = $row->ItemCategoryID;                    
//                        @$AssetCategoryCode[$row->ItemStatus]   = $row->ItemCategoryCode;                    
//                    }
//                    //------------------------------------------------------------------------------------------------//
//
//                    $total_records      = count(@$AssetAmount);
//                    
//                    foreach(@$AssetAmount as $key => $value){
//                        $total_loop++;
//
//                        if($total_loop == $total_records){
//                            $item_ratio = 100 - $total_ratio;
//                        } 
//                        else {
//                            $item_ratio = floor(abs((doubleval($value) / $sub_total) * 100));
//                        }
//
//                        $advance_ratio  = $down_payment * ($item_ratio / 100);
//                        $total_ratio    = $total_ratio + $item_ratio;
//                        
//                        $data_payment   = array(
//                                            'BranchCode'            => $branch_code,
//                                            'VendorCode'            => $vendor_code,
//                                            'InvoiceNumber'         => $pord_number,
//                                            'InvoiceDate'           => date("Y-m-d", strtotime($pord_date)),
//
//                                            'InvoiceCurrCode'       => $currency_code,
//                                            'InvoiceCurrRate'       => $currency_rate,
//                                            'InvoiceFiscalRate'     => 1,
//                                            'InvoicePurchase'       => $advance_ratio,
//                                            'InvoiceTotalDP'        => 0,
//                                            'InvoiceAmount'         => $advance_ratio,
//                                            'InvoiceOwing'          => $advance_ratio,
//                                            'ItemCategoryRatio'     => $item_ratio,
//                                            'ItemCategoryID'        => @$AssetCategoryID[$key],
//                                            'ItemCategoryCode'      => @$AssetCategoryCode[$key],
//                                            'ItemType'              => @$AssetType[$key],
//                                            'ItemStatus'            => $key,
//                                            'InvoiceType'           => 1,
//                                            'PPnFiscalStatus'       => 0,
//                                            'LastUser'              => $this->session->userdata("username")	
//                                        );
//										
//                       $this->m_purchase_order->insert_payment($data_payment);
//                    }
//                }
//                //------------------------------------------------------------------------------------------------------//
//            }
//			
//			/*=======================Update Status Trans status=========================================*/
//            if($status == 1) {
//                $data_po = array (
//                            'TransStatus'       => $trans_status,						
//                            'AppLevel1Status'   => 1,
//                            'AppLevel1Code'     => $this->session->userdata("username"),
//                            'AppLevel1Date'     => date("Y-m-d"),	
//                            'LastUser'          => $this->session->userdata("username")
//                        );
//            }
//            else{
//                $data_po = array (
//                            'TransStatus'       => $trans_status,						
//                            'AppLevel2Status'   => 1,
//                            'AppLevel2Code'     => $this->session->userdata("username"),
//                            'AppLevel2Date'     => date("Y-m-d"),	
//                            'LastUser'          => $this->session->userdata("username")
//                        );
//                
//            }
//
//            //3.Update Purchase Order for Status only
//           	$this->m_purchase_order->update($data_po, $pord_number);
//            /*=========================End==============================================================*/
//
//            /*=============================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);
//			}
//			echo json_encode($result);
//			/*==================================end======================================================*/	
//        }
//    }

    public function suspend_data() {
        $result_suspend = 0;
        $pord_number = str_replace(".", "/", $this->input->post('id'));
        $data = $this->m_purchase_order->get_table_group($pord_number);

        $pr_number = explode(",", $data->PReqNumber);
        $arr_update_data_group = array();
        $arr_detail_pr = array();

        $data_update = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata("username")
        );
        $arr_update_data_group[] = $data_update;

        //1. Update PurcahseOrder TransStatus
        //$this->m_purchase_order->update($data_update, $pord_number);
        //---------------------------------------------------------------------------------------------------------------------//
        //2. Update InvoicePayment TransStatus
        //$this->m_purchase_invoice->update_payment($data_update, $pord_number);
        //---------------------------------------------------------------------------------------------------------------------//            
        //3. Update Item Qty Purchase Requsition
        $data_detail = $this->m_purchase_order->get_detail_item($pord_number);

        foreach ($data_detail as $row) {
            $detail_pr = $this->m_purchase_requisition->get_detail_item_by_id($row->PReqDetailID);
            $newItemQtyPO = doubleval($detail_pr->ItemQtyPO) - doubleval($row->ItemQty);

            $new_detail_pr = array(
                'PReqDetailID' => $row->PReqDetailID,
                'ItemQtyPO' => $newItemQtyPO,
				'PReqNumber' => $row->PReqNumber,
                'LastUser' => $this->session->userdata("username")
            );
            $arr_detail_pr[] = $new_detail_pr;
            //$this->m_purchase_requisition->update_detail($new_detail_pr, $row->PReqDetailID);
        }
		
		$result_suspend = $this->m_purchase_order->suspend_data($data_update, $arr_detail_pr, $pord_number);
        //---------------------------------------------------------------------------------------------------------------------//

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


        echo json_encode($result);
    }

    public function suspend_item() {

        $suspend_all = 1;
        $trans_status = 1;

        $pord_number = $this->input->post('POrdNumber');
        $detail_post = $this->input->post('Detail');
        $detail = json_decode($detail_post);
        $result_suspend_item = 0;
        $arr_update_qty_suspend = array();
        $arr_update_trans_status = array();

        $check_approved = $this->m_receive_item->check_item_ri_approved_by_pordnumber($pord_number);
        if ($check_approved == false) {
            foreach ($detail as $row) {
                $POrdDetailID = $row->POrdDetailID;
                $item_qty = $row->ItemQty_Old;

                $get_item_qty_on_pr = $this->m_purchase_order->get_detail_sum_pord($POrdDetailID, $row->ItemCode);
				if($row->ItemSpdStatus == 'Yes'){
					$item_qty_ri = $get_item_qty_on_pr->ItemQtyPO - $get_item_qty_on_pr->ItemQtyRI;
				}
				else{
					$item_qty_ri        = 0;
				}	
                $item_qty_suspend = $item_qty_ri;

                if ($row->ItemModusType == 2) {
                    if ($item_qty_suspend == 0) {
                        if ($get_item_qty_on_pr->ItemQty_RI == $get_item_qty_on_pr->ItemQtyPO) {
                            $result['status'] = false;
                            $result['message'] = 'Item tidak berhasil di Suspend, Qty SO sudah di proses keseluruhan di DO';
                            echo json_encode($result);

                            die();
                        }
                    } else {
                        if (($get_item_qty_on_pr->ItemQtyRI > $get_item_qty_on_pr->ItemQtyPO)) {
                            $result['status'] = false;
                            $result['message'] = 'Item tidak berhasil di Suspend, Qty RI melebihi Qty PO atau semua Qty di PO sudah di proses di RI';
                            echo json_encode($result);

                            die();
                        }
                    }

                    $data = array(
                        'ItemQtySpd' => $item_qty_suspend,
                        'ItemSpdStatus' => $row->ItemSpdStatus == 'Yes' ? 1 : 0,
                        'LastUser' => $this->session->userdata("username"),
                        'POrdDetailID' => $POrdDetailID
                    );

                    //Edit POrdDetail for Suspend Item Status
                    $arr_update_qty_suspend[] = $data;
                    //-----------------------------------------------------------------------------------------------------//
                }

                if (($row->ItemSpdStatus == 'No') or ( $row->ItemQtyRI > 0)) {
                    $suspend_all = 0;
                }

                if (($row->ItemQty - $row->ItemQtyRI - $row->ItemQtySpd) != 0) {
                    $trans_status = 0;
                }
            }

            //suspen status 8 jika dia item suspend semua
            if (($suspend_all == 1) or ( $trans_status == 1)) {
                if ($suspend_all == 1) {
                    $TransStatus = 8;
                } elseif ($trans_status == 1) {
                    $ReceiveAppStatus = $this->m_receive_item->check_ri_app_status($pord_number);

                    if ($ReceiveAppStatus == 1) {
                        $TransStatus = 2;
                    } else {
                        $TransStatus = 1;
                    }
                }

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

                $arr_update_trans_status[] = $data;
            }

            $result_suspend_item = $this->m_purchase_order->update_group_new($arr_update_qty_suspend, $arr_update_trans_status, $pord_number);

            if ($result_suspend_item == 0) {
                $result['status'] = FALSE;
                $result['message'] = 'Item Suspend / UnSuspend gagal disimpan';
            } else {
                $result['status'] = TRUE;
                $result['message'] = 'Item Suspend / UnSuspend berhasil disimpan';
            }
        } else {
            $result['status'] = false;
            $result['message'] = 'Item Suspend tidak berhasil disimpan, karena item belum di Approval pada Receive Item';
        }
        echo json_encode($result);
    }

    function to_preview($obj_string = null) {
//        $data['list'] = $this->m_purchase_order->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['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $data['list']           = $this->m_purchase_order->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('purchase/purchase_order/v_preview_purchase_order', $data);
        $this->load->view('v_footer');
    }
    function to_preview_LAMA() {
        // get link from tbl_menu 
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

        // get label from tbl_menu 
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        // set data
        $data['list'] = $this->m_purchase_order->get_all($this->ho);

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

    function to_print() {
        // get link from tbl_menu 
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

        // get label from tbl_menu 
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        // set data
        $data['list'] = $this->m_purchase_order->get_all($this->ho);

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

    function to_print_detail() {
        // get link from tbl_menu 
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

        // get label from tbl_menu 
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

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

        if ($id != "") {
            $data['detail'] = $this->m_purchase_order->get_detail_print($id);
            $data['list'] = $this->m_purchase_order->get_detail_item_print($data['detail']->POrdNumber);

            if ($data['detail']->VendorStatus == 0) {
                if (($data['detail']->VendorTaxNumber != "") && ($data['detail']->VendorTaxNumber != NULL)) {
                    $taxes_code = 'PPH23-1';
                } else {
                    $taxes_code = 'PPH23-2';
                }

                $taxes_label = 'PPH23';
            } else {
                if (($data['detail']->VendorTaxNumber != "") && ($data['detail']->VendorTaxNumber != NULL)) {
                    $taxes_code = 'PPH23-3';
                } else {
                    $taxes_code = 'PPH23-4';
                }
                $taxes_label = 'PPH21';
            }

            $data['taxes'] = $this->m_taxes->get_by_code($taxes_code);
            $data['taxes_pph'] = $this->m_taxes->get_by_code('PPH22');
            $data['tax_label'] = $taxes_label;


            $this->load->view('v_header');
            $this->load->view('purchase/purchase_order/v_print_detail_purchase_order', $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();
        $result = 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('POrdNumber', $Number);
        }
        if ($VendorCode != "") {
            $this->db->like('VendorCode', $VendorCode);
        }
        if ($Desc != "") {
            $this->db->like('POrdDesc', $Desc);
        }
        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_purchaseorder.POrdDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_purchaseorder.POrdDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_purchaseorder');
        /* ========================end======================================= */
        $result = $this->m_purchase_order->get_all();
        for ($i = 0; $i < count($result); $i++) {
            // kalau master ambil dari get_status_master(), kalau transaksi get_status()
            $TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(//change
                'BranchName' => $result[$i]->BranchName,
                'VendorName' => $result[$i]->VendorName,
                'VendorCode' => $result[$i]->VendorCode,
                'TransNumber' => $result[$i]->POrdNumber,
                'POrdDate' => $result[$i]->POrdDate,
                'POrdTotalAmount' => $result[$i]->POrdTotalAmount,
                'POrdTotalDP' => $result[$i]->POrdTotalDP,
                'POrdDesc' => $result[$i]->POrdDesc,
                'TransStatus' => $TransStatus,
                'CreatedBy' => $result[$i]->CreatedBy
            );
        }

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

    public function ajax_preg_item() {
        $get_preq_number = $this->m_purchase_requisition->get_preq_item();
		if ($get_preq_number != false) {
            echo json_encode($get_preq_number);
            //echo $this->db->last_query();
        } else {
            echo '[]';
        }
//        echo $this->db->last_query(); die();
    }

    public function ajax_preg_adv() {
        $get_preq_adv = $this->m_purchase_requisition->get_preq_adv();
		if ($get_preq_adv != false) {
            echo json_encode($get_preq_adv);
            //echo $this->db->last_query();
        } else {
            echo '[]';
        }
//        echo $this->db->last_query(); die();
    }

    public function ajax_item() {
        $preq_no = $this->input->post('pr_no');

        if (!empty($preq_no)) {
            echo json_encode($this->m_purchase_requisition->get_detail_item_for_po($preq_no));
        } else {
            echo '[]';
        }
        //        echo $this->db->last_query(); die();       
    }

    public function get_no_po_for_so() {
        echo json_encode($this->m_purchase_order->get_purchase_order_by_transtatus());
    }

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

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

    public function get_po_number() {
        $pord_date = $this->input->post('POrd_Date') == '' ? date('d-m-Y') : $this->input->post('POrd_Date');
        $pord_number = $this->m_purchase_order->create_po_number($pord_date);

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

        echo json_encode($result);
    }

    public function get_vendor_taxes() {
        $taxes_code = $this->input->post('TaxesCode');
        $taxes_rate = $this->m_taxes->get_by_code($taxes_code);

        $result['taxes'] = $taxes_rate->TaxesRate;
        echo json_encode($result);
    }

    public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status'] = false;
        $result['message'] = get_notification_transaksi($this->name, $modus, 0);

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

}
