<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Ladur / 08-08-2014	
 *	Revisi 	: Ferry / 25-03-2015
 	Revisi 	: Fachri / 02-06-2015
 */

class Delivery_order extends CI_Controller {
    // inisialisasi manual
    public $menu_id = 161;
    public $code = "Delivery Order Number";
    public $name = "Delivery Order";
    public $trans_data = array();
	
    public function __construct() {
        parent::__construct();
		$this->load->helper('message');	
		$this->load->helper('status');			
		$this->load->helper('convert_date');
		$this->load->helper('approval');
		$this->load->helper('lables');
		$this->load->helper('custom_string_helper');
		
		$this->load->model('m_account_journal');
		$this->load->model('m_delivery_order');	
		$this->load->model('m_sales_order');	
		$this->load->model('m_sales_quotation');
		$this->load->model('m_sales_invoice');
		$this->load->model('m_inventories');
		$this->load->model('m_receive_item');
		$this->load->model('m_purchase_order');
		$this->load->model('custom/m_custom');
		$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();
            }
        }
    }
	
    //Function Index
    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{
					$group_menu 		= $this->session->userdata('group_menu');	
					// set data
					$data['menu_id'] 	=  $this->menu_id;
					
					// get link from tbl_menu 
					$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] 	= $this->m_menu->get_menulink($this->menu_id);
					$data['list_cust'] 	= $this->m_sales_quotation->get_all_customer(); 
					
					//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('sales/delivery_order/v_deliveryorder', $data);	
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
    //Function Form Edit
    public function add($SOrdNumber='',$CustomerCode='') {
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
			/*
				untuk di index/list = get_menu_by_group, 
				untuk di add = get_menu_by_group_add
				untuk di edit = get_menu_by_group_edit
			*/
            $arr_group_id           = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
			//--------------------------end-----------------------------------------------------------
            if(!empty($arr_group_id)){
				$data['available_menu'] = array_unique($arr_group_id);
				if(!in_array($this->menu_id, $data['available_menu'])) { 
					redirect(base_url() . 'error', 'refresh');	
				}
				else{
					/*
						modul untuk akses add masing masing modul berebda 
						jangan lupa copy $data nya (jika dia bener langsung ke add)
					*/
					$group_menu 		= $this->session->userdata('group_menu');
					// set data
					$data['menu_id'] 	=  $this->menu_id;

					// get link from tbl_menu 
					$data['menu_label'] 	= $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] 		= $this->m_menu->get_menulink($this->menu_id);
					$data['SOrdNumber'] 	= $SOrdNumber;
					$data['CustomerCode'] 	= $CustomerCode;
					
					$data['do_date'] 	= date('d-m-Y');
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					// set for view
					$this->load->view('v_header');
					$this->load->view('sales/delivery_order/v_new_deliveryorder', $data);
					$this->load->view('v_footer');
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

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

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

					
					$DOrdNumber				= str_replace($data['menu_link'].'/to_variant/',"",$this->uri->uri_string());
					$data['data_do'] 		= $this->m_delivery_order->get_deliveryorder_data($DOrdNumber);
					$data['list_detail'] 	= $this->m_delivery_order->m_get_detail_deliveryordervariant($DOrdNumber);
					
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					$this->load->view('v_header');
					$this->load->view('sales/delivery_order/v_newvariant',$data);
					$this->load->view('v_footer');
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
    //Function Form Insert
    public function insert() {
		try{
			/*===========================deklar variabel============================================*/
			$branchcode			= $this->session->userdata('branch');
			$cmb_customer		= $this->input->post('cmb_customer');
			$currency_code		= $this->input->post('txt_currency_code');
			$currency_rate		= $this->input->post('txt_rate');
			$txa_ship_to		= $this->input->post('txa_ship_to');
			$txa_address		= $this->input->post('txa_address');
			$txt_do_date		= $this->input->post('txt_do_date');
			
			/*=====================================do number==========================================*/
			$txt_do_no  		= $this->m_delivery_order->create_do_number($txt_do_date);
			
			/*==========================================================================================*/
			$cmb_ship_via		= $this->input->post('cmb_ship_via');
			$txt_so_no			= $this->input->post('txt_so_no');
			$txt_ship_date		= $this->input->post('txt_ship_date');
			$txt_driver			= $this->input->post('txt_driver');
			$txt_po_no			= $this->input->post('txt_po_no');
			$txt_car_number		= $this->input->post('txt_car_number');
			$txa_description	= $this->input->post('txa_description');
			$do_total_amount	= $this->input->post('do_total_amount');
			/*============================end====================================================*/
			$detail				= json_decode($this->input->post('detail'));
			
			if(count($detail)>0){
				/*	
					Check Qty DO
				*/
				foreach($detail as $row_check){
					$get_data_sord_detail 	= $this->m_delivery_order->get_detail_sales_order_for_do($row_check->SOrdDetailID, $row_check->ItemCode); //get data detail itemqty so+itemqty spd 
					
					$ItemQtyDO 				= $get_data_sord_detail->ItemQtyDO;//Qty Suspend sudah ditambahkan di model
					$ItemQtySO 				= $get_data_sord_detail->ItemQtySO;
					$TotalQtyDO 			= $row_check->ItemQty + $ItemQtyDO;
					
					if($TotalQtyDO > $ItemQtySO){
						throw new Exception("Transaksi gagal, Item Qty Delivery Order melebihi Item Qty Sales Order, Untuk Item ".$row_check->ItemDesc.", Qty DO : ".$TotalQtyDO.", Qty SO : ".$ItemQtySO.""); 
					}
				}
				/*=======================End======================================================*/
				
				/*======================insert group==============================*/
				$this->insert_group($do_total_amount, $txt_do_no, $branchcode, $cmb_customer, $txt_do_date, $txt_so_no, $txt_po_no, $txa_address, $txa_ship_to, $txt_ship_date, $cmb_ship_via, $txt_driver, $txt_car_number, $txa_description, $currency_code, $currency_rate);
				/*==============end===============================================*/
				
				/*===================insert detail====================================*/
				$this->insert_detail($detail, $currency_code, $currency_rate, $txt_do_no, $branchcode, $txt_do_date, $txa_description);
				/*=====================end=============================================*/
				
				$result_insert = $this->m_delivery_order->insert_transaction($this->transaction);
				$this->transaction 	= [];
				
				/*=============================trans roll back dan trans commit============================/*/
				if ($result_insert == 0) {
					$result['status'] 		= FALSE;
					$result['message']  	= get_notification_transaksi($this->name, 'insert', 0, $txt_do_no);
				}
				else {
					$result['status'] 		= TRUE;
					$result['message']  	= get_notification_transaksi($this->name, 'insert', 1, $txt_do_no);
					$result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
					$result['number']       = $txt_do_no;
				}
				/*==================================end======================================================*/
				echo json_encode($result);
			}
			else{
				throw new Exception("Delivery Order gagal disimpan. Tidak ada item pada Delivery Order."); 
			}
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
	
	function insert_group($do_total_amount, $txt_do_no, $branchcode, $cmb_customer, $txt_do_date, $txt_so_no, $txt_po_no, $txa_address, $txa_ship_to, $txt_ship_date, $cmb_ship_via, $txt_driver, $txt_car_number, $txa_description, $currency_code, $currency_rate){
		$data = array (
			'BranchCode'		=> $branchcode,
			'CustomerCode'		=> $cmb_customer,
			'DOrdDate'			=> date("Y-m-d", strtotime($txt_do_date)),	
			'DOrdNumber'		=> $txt_do_no,
			'SOrdDate'			=> date("Y-m-d", strtotime($this->m_sales_order->get_so_date($txt_so_no))),
			'SOrdNumber'		=> $txt_so_no,
			'CustPODate'		=> date("Y-m-d", strtotime($this->m_sales_order->get_po_date($txt_so_no))),			
			'CustPONumber'		=> $txt_po_no,
			'BillingAddress'	=> $txa_address,
			'ShipAddress' 		=> $txa_ship_to,
			'ShipDate'			=> date("Y-m-d", strtotime($txt_ship_date)),	
			'ShipmentID'		=> $cmb_ship_via,
			'DriverName'		=> $txt_driver,
			'LicencePlate'		=> $txt_car_number,
			'DOrdDesc'			=> $txa_description,
			'DOrdTotalAmount'	=> $do_total_amount,
			'CurrencyCode'		=> $currency_code,
			'CurrencyRate'		=> $currency_rate,
			'CreatedBy' 		=> $this->session->userdata("username"),
			'CreatedAt' 		=> date('Y-m-d'),
			'TransStatus'		=> 4,
			'NumberUnik' 		=> $branchcode.'/'.rand(00000,99999),
			'LastUser'			=> $this->session->userdata("username")
		);
		
		//1. Inset into Delivery Order Table
		$this->transaction['insert_group']['data'] = $data;
		//$this->m_delivery_order->insert($data);
		//----------------------------------------------------------------------------------------------------------//
	}
	
	function insert_detail($detail, $currency_code, $currency_rate, $txt_do_no, $branchcode, $txt_do_date, $txa_description){
		
		$ItemCode_Loop 	= " ";
		$total_item = 0;
		foreach($detail as $row){
			$total_item++;
			/*
				ItemStatus = 0 Inventory
				ItemStatus = 2 Service
			*/
			$ItemCode 		= $row->ItemCode;
			$ItemQty_Loop 	= $row->ItemQty;
			$arResult 		= array();

			if($row->ItemStatus != 0){
				$item_qty 				= $row->ItemQty;
				
				$data_detail = array(
					'SOrdDetailID'		=> $row->SOrdDetailID,
					'SOrdNumber'		=> $row->SOrdNumber,
					'DOrdNumber'		=> $txt_do_no,
					'ItemCode'			=> $row->ItemCode,
					'ItemDesc'			=> $row->ItemDesc,
					'ItemQty'			=> $row->ItemQty,
					'ItemUnit'			=> $row->ItemUnit,
					'ItemPrice'			=> $row->ItemPrice,
					'ItemDiscPcnt'		=> $row->ItemDiscPcnt,
					'ItemPriceCogs'		=> $row->ItemAverage,
					'ItemAmount'		=> $row->TotalAmount, 
					'ItemTax'			=> $row->ItemTax,
					'ItemPPH23' 		=> $row->Item_pph23,
					'ItemCategoryID'	=> $row->ItemCategoryID,
					'ItemCategoryCode'	=> $row->ItemCategoryCode,
					'ItemType' 			=> $row->ItemStatus,
					'LastUser'			=> $this->session->userdata('username')
				);
				
				//2. Insert into DOrdDetail
				$this->transaction['insert_detail']['data'][] = $data_detail;
				//$this->m_delivery_order->insert_detail($data_detail);
				//------------------------------------------------------------------------------------------------------//
				
				/*
					update qty do di sales order detail
				*/
				$data_detail_so	= array(
					'SOrdDetailID'  => $row->SOrdDetailID, 
					'ItemQtyDO'     => ($row->ItemQtyDO + $row->ItemQty), 
					'LastUser'      => $this->session->userdata('username')
				);
				$this->transaction['update_so']['data'][] = $data_detail_so;
				$this->transaction['update_so']['SOrdDetailID'][] = $row->SOrdDetailID;
				
				//summing jurnal
				if($currency_code != 'IDR'){
					$convert_item_curr 	= $row->ItemAverage / $currency_rate;
					$hasil_amount_qty 	= $row->ItemQty * $convert_item_curr;
				}
				else{
					$hasil_amount_qty 	= $row->ItemQty * $row->ItemAverage;
				}
			}
			else{
				$data_detail = array(
					'SOrdDetailID'		=> $row->SOrdDetailID,
					'SOrdNumber'		=> $row->SOrdNumber,
					'DOrdNumber'		=> $txt_do_no,
					'ItemCode'			=> $row->ItemCode,
					'ItemDesc'			=> $row->ItemDesc,
					'ItemQty'			=> $row->ItemQty,
					'ItemUnit'			=> $row->ItemUnit,
					'ItemPrice'			=> $row->ItemPrice,
					'ItemPriceCogs'		=> $row->ItemAverage,
					'ItemAmount'		=> $row->TotalAmount, 
					'ItemTax'			=> $row->ItemTax,
					'ItemPPH23' 		=> $row->Item_pph23,
					'ItemCategoryID'	=> $row->ItemCategoryID,
					'ItemCategoryCode'	=> $row->ItemCategoryCode,
					'ItemType' 			=> $row->ItemStatus,
					'LastUser'			=> $this->session->userdata('username')
				);
				
				//2. Insert into DOrdDetail
				$this->transaction['insert_detail']['data'][] = $data_detail;
				//$this->m_delivery_order->insert_detail($data_detail);
				//------------------------------------------------------------------------------------------------------//
			
				$data_detail_so	= array(
					'SOrdDetailID'  => $row->SOrdDetailID, 
					'ItemQtyDO'     => ($row->ItemQtyDO + $row->ItemQty), 
					'LastUser'      => $this->session->userdata('username')
				);
				$this->transaction['update_so']['data'][] 			= $data_detail_so;
				$this->transaction['update_so']['SOrdDetailID'][] 	= $row->SOrdDetailID;
				
				//summing jurnal
				if($currency_code != 'IDR'){
					$convert_item_curr = $row->ItemAverage / $currency_rate;
					$hasil_amount_qty = $row->ItemQty * $convert_item_curr;
				}
				else{
					$hasil_amount_qty = $row->ItemQty * $row->ItemAverage;
				}
			}

			@$CategoryAmount[$row->ItemCategoryID] += $hasil_amount_qty;
			@$CategoryType[$row->ItemCategoryID] += $row->ItemStatus;
		}
		
		/*===============insert journal==========================*/
		$this->insert_journal($CategoryType, $CategoryAmount, $currency_code, $currency_rate, $txt_do_date, $txa_description, $txt_do_no);
		/*===================end=================================*/
	}
	
	function insert_journal($CategoryType, $CategoryAmount, $currency_code, $currency_rate, $txt_do_date, $txa_description, $txt_do_no){
		
		foreach ($CategoryAmount as $key => $value) {
			if($CategoryType[$key] == 0) {
				//cogs akun
				$COGSAccount   = $this->m_account_journal->get_cat_item_account('COGS', $key, 'IDR');									
				if($COGSAccount == false) {$this->trans_rollback('preference','COGS Account', $currency_code);} 

				$cogs_journal  = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
				$cogs_currency = doubleval($value);
				
				$journal_cogs = array(
					'DOrdDate'          => date("Y-m-d", strtotime($txt_do_date)),
					'DordDesc' 			=> $txa_description,
					'DOrdNumber'        => $txt_do_no,
					'DOrdAccountNumber' => $COGSAccount->AccountNumber,
					'DOrdSaldoDebet'    => $cogs_journal,
					'DOrdSaldoCredit'   => 0,
					'AmountCurrency' 	=> $cogs_currency,
					'DOrdSignStatus' 	=> 0,
					'LastUser'          => $this->session->userdata("username")	
				);
				$this->transaction['insert_journal_cogs']['data'][] = $journal_cogs;
				//end cogs
				
				//inventori akun
				$InventoryAccount   = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');
				if($InventoryAccount == false) {$this->trans_rollback('preference','Inventory Account', $currency_code);} 

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

				$journal_inventory = array(
					'DOrdDate'          => date("Y-m-d", strtotime($txt_do_date)),
					'DordDesc' 			=> $txa_description,
					'DOrdNumber'        => $txt_do_no,
					'DOrdAccountNumber' => $InventoryAccount->AccountNumber,
					'DOrdSaldoDebet'    => 0,
					'DOrdSaldoCredit'   => $inventory_journal,
					'AmountCurrency' 	=> $inventory_currency,
					'DOrdSignStatus' 	=> 1,
					'LastUser'          => $this->session->userdata("username")	
				);
				//end inventori
				
				//insert jurnal do
				$this->transaction['insert_journal_inventori']['data'][] = $journal_inventory;
			}
		}
	}
	
	function insert_journal_app($CategoryType, $CategoryAmount, $currency_code, $currency_rate, $txt_do_date, $txa_description, $txt_do_no){
		foreach ($CategoryAmount as $key => $value) {
			if($CategoryType[$key] == 0) {
				//cogs akun
				$COGSAccount   = $this->m_account_journal->get_cat_item_account('COGS', $key, 'IDR');									
				if($COGSAccount == false) {$this->trans_rollback('preference','COGS Account', $currency_code);} 

				$cogs_journal  = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
				$cogs_currency = doubleval($value);
				
				$journal_cogs = array(
					'DOrdDate'          => date("Y-m-d", strtotime($txt_do_date)),
					'DordDesc' 			=> $txa_description,
					'DOrdNumber'        => $txt_do_no,
					'DOrdAccountNumber' => $COGSAccount->AccountNumber,
					'DOrdSaldoDebet'    => $cogs_journal,
					'DOrdSaldoCredit'   => 0,
					'AmountCurrency' 	=> $cogs_currency,
					'DOrdSignStatus' 	=> 0,
					'LastUser'          => $this->session->userdata("username")	
				);
				
				$this->m_delivery_order->insert_journal($journal_cogs);
				//$this->transaction['insert_journal_cogs']['data'][] = $journal_cogs;
				//end cogs
				
				//inventori akun
				$InventoryAccount   = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');
				if($InventoryAccount == false) {$this->trans_rollback('preference','Inventory Account', $currency_code);} 

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

				$journal_inventory = array(
					'DOrdDate'          => date("Y-m-d", strtotime($txt_do_date)),
					'DordDesc' 			=> $txa_description,
					'DOrdNumber'        => $txt_do_no,
					'DOrdAccountNumber' => $InventoryAccount->AccountNumber,
					'DOrdSaldoDebet'    => 0,
					'DOrdSaldoCredit'   => $inventory_journal,
					'AmountCurrency' 	=> $inventory_currency,
					'DOrdSignStatus' 	=> 1,
					'LastUser'          => $this->session->userdata("username")	
				);
				//end inventori
				
				//insert jurnal do
				$this->m_delivery_order->insert_journal($journal_inventory);
				//$this->transaction['insert_journal_inventori']['data'][] = $journal_inventory;
			}
		}
	}
    //Function Form Edit

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

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

					// inisialisasi additional parameter
					$id 				= str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
					$data['detail'] 	= $this->m_delivery_order->get_detail($id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					if($data['detail'] != false){
						// set for view
						$this->load->view('v_header');
						$this->load->view('sales/delivery_order/v_edit_deliveryorder',$data);
						$this->load->view('v_footer');
					}
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
    // Function Update
    public function update() {
        try{
			/*=======================deklar variabel==========================================*/
			$cmb_customer		= $this->input->post('cmb_customer');
			$currency_code		= $this->input->post('txt_currency_code');
			$currency_rate		= $this->input->post('txt_rate');
			$txa_address		= $this->input->post('txa_address');
			$txa_ship_to		= $this->input->post('txa_ship_to');
			$cmb_ship_via		= $this->input->post('cmb_ship_via');
			$txt_ship_date		= $this->input->post('txt_ship_date');
			$txt_do_no			= $this->input->post('txt_do_no');
			$txt_do_date		= $this->input->post('txt_do_date');
			$txt_so_no			= $this->input->post('txt_so_no');
			$txt_po_no			= $this->input->post('txt_po_no');
			$cmb_comp_po 		= $this->input->post('cmb_comp_po');
			$txa_description	= $this->input->post('txa_description');
			$txt_driver			= $this->input->post('txt_driver');
			$txt_car_number		= $this->input->post('txt_car_number');
			$branch_code		= $this->input->post('branch_code');
			$txt_direct 		= $this->input->post('txt_direct');
			$do_total_amount 	= $this->input->post('do_total_amount');
			$detail				= json_decode($this->input->post('detail'));
			
			$detail_id			= $this->input->post('detail_id');
			$detail_id			= json_decode($detail_id);
			
			$detail_item		= $this->input->post('detail_item');
			$detail_item		= json_decode($detail_item, true);
			
			/*=============================end==============================================*/
			
			if(count($detail)>0){
				/*	
					Check Qty DO
				*/
				foreach($detail as $row_check){
					$get_data_sord_detail 	= $this->m_delivery_order->get_detail_sales_order_for_do($row_check->SOrdDetailID, $row_check->ItemCode); //get data detail itemqty so+itemqty spd 
					$item_qty_inventori 	= $this->m_inventories->get_item_qty($row_check->ItemCode, $branch_code); //get data inventory tampilkan qty saja
					
					$ItemQtyDO 				= $get_data_sord_detail->ItemQtyDO;//Qty Suspend sudah ditambahkan di model
					$ItemQtySO 				= $get_data_sord_detail->ItemQtySO;
					$TotalQtyDO 			= ($row_check->ItemQty - $ItemQtyDO) + ($ItemQtyDO + $get_data_sord_detail->ItemQtySpd);
					
					if($TotalQtyDO > $ItemQtySO){
						throw new Exception("Transaksi gagal, Item Qty Delivery Order melebihi Item Qty Sales Order, Untuk Item ".$row_check->ItemDesc.", Qty DO : ".$TotalQtyDO.", Qty SO : ".$ItemQtySO.""); 
					}
					
					
					if($txt_direct == 1){
						$get_po_detail_by_do_direct = $this->m_purchase_order->get_detail_sum_pord($cmb_comp_po, $row_check->ItemCode);
						
						if(empty($get_po_detail_by_do_direct->ItemCode)){
							throw new Exception('Maaf transaksi Do Direct gagal, Item Code '.$row_check->ItemCode.' Tidak ada di Transaksi Purchase Order');
						}
						else{
							if($row_check->ItemQty > $get_po_detail_by_do_direct->ItemQtyAllPo){
								throw new Exception('Maaf transaksi Do Direct gagal, Item Code '.$row_check->ItemCode.' melebihi Qty Purchases Order');
							}
						}
					}
				}
				/*=======================End======================================================*/
				
				/*=========================update group=============================================*/
				$this->update_group($do_total_amount, $cmb_comp_po, $branch_code, $txt_do_no, $cmb_customer, $txa_address, $txa_ship_to, $cmb_ship_via, $txt_ship_date, $txa_description, $currency_code, $currency_rate, $txt_so_no, $txt_po_no, $txt_driver, $txt_car_number);
				/*======================end============================================================*/
				
				foreach($detail as $row){
					if($row->ItemStatus != 0){
						/*
							Update Detail
						*/
						$data_detail = array(
							'SOrdDetailID' 	=> $row->SOrdDetailID,
							'DOrdNumber' 	=> $txt_do_no,
							'POrdNumber' 	=> $cmb_comp_po,
							'ItemCode' 		=> $row->ItemCode,
							'ItemQty' 		=> $row->ItemQty,
							'ItemUnit' 		=> $row->ItemUnit,
							'ItemPriceCogs' => $row->ItemAverage,
							'ItemAmount' 	=> $row->TotalAmount,
							'ItemTax' 		=> $row->ItemTax,
							'ItemPPH23' 		=> $row->Item_pph23,
							'LastUser' 		=> $this->session->userdata('username')
						);
						
						$this->transaction['update_detail']['data'][] = $data_detail;
						$this->transaction['update_detail']['DOrdDetailID'][] = $row->DOrdDetailID;
						/*==============================END======================*/
						
						/*
							Update QTY DO
						*/
						$data_detail_so	= array(
							'SOrdDetailID'	=> $row->SOrdDetailID, 
							'ItemQtyDO'		=> (($row->ItemQtyDO - $row->LastQtyDO) + $row->ItemQty), 
							'LastUser'		=> $this->session->userdata('username')
						);
						
						$this->transaction['update_so']['data'][] = $data_detail_so;
						$this->transaction['update_so']['SOrdDetailID'][] = $row->SOrdDetailID;
						/*=======================END=========================*/
					}
					else{
						/*
							Update Detail
						*/
						$data_detail = array(
							'SOrdDetailID' 	=> $row->SOrdDetailID,
							'DOrdNumber' 	=> $txt_do_no,
							'POrdNumber' 	=> $cmb_comp_po,
							'ItemCode' 		=> $row->ItemCode,
							'ItemQty' 		=> $row->ItemQty,
							'ItemUnit' 		=> $row->ItemUnit,
							'ItemPriceCogs' => $row->ItemAverage,
							'ItemAmount' 	=> $row->TotalAmount,
							'ItemTax' 		=> $row->ItemTax,
							'ItemPPH23' 		=> $row->Item_pph23,
							'LastUser' 		=> $this->session->userdata('username')
						);
						
						$this->transaction['update_detail']['data'][] = $data_detail;
						$this->transaction['update_detail']['DOrdDetailID'][] = $row->DOrdDetailID;
						/*==============================END======================*/
						
						/*
							Update QTY DO
						*/
						$data_detail_so	= array(
							'SOrdDetailID'	=> $row->SOrdDetailID, 
							'ItemQtyDO'		=> (($row->ItemQtyDO - $row->LastQtyDO) + $row->ItemQty), 
							'LastUser'		=> $this->session->userdata('username')
						);
						
						$this->transaction['update_so']['data'][] = $data_detail_so;
						$this->transaction['update_so']['SOrdDetailID'][] = $row->SOrdDetailID;
						/*=======================END=========================*/
					}
					
					if($currency_code != 'IDR'){
						$convert_item_curr = $row->ItemAverage / $currency_rate;
						$hasil_amount_qty = $row->ItemQty * $convert_item_curr;
					}
					else{
						$hasil_amount_qty = $row->ItemQty * $row->ItemAverage;
					}
					
					@$CategoryAmount[$row->ItemCategoryID] += $hasil_amount_qty;
					@$CategoryType[$row->ItemCategoryID] += $row->ItemStatus;
				}
				
				/*==================delete per grid==========================================*/
				$this->transaction['delete_detail']['total'] = count($detail_id);
				if(count($detail_id)>0){
					foreach ($detail_id as $DOrdDetailID) {
						$this->transaction['delete_detail']['DOrdDetailID'][] = $DOrdDetailID;
					}
					
					for($x = 0; $x < count($detail_item['a']); $x++) {
						$SOrdDetailID 	= $detail_item['a'][$x];
						$ItemQtyDO 		= $detail_item['b'][$x];
						$LastQtyDO 		= $detail_item['c'][$x];
						$ItemQty 		= $detail_item['d'][$x];
						$ItemCode 		= $detail_item['e'][$x];
						
						$total_qty_do = $ItemQtyDO - $ItemQty;
						
						$data_detail_so	= array(
							'SOrdDetailID'	=> $SOrdDetailID, 
							'ItemQtyDO'		=> $total_qty_do, 
							'LastUser'		=> $this->session->userdata('username')
						);
						
						$this->transaction['update_so']['data'][] = $data_detail_so;
						$this->transaction['update_so']['SOrdDetailID'][] = $SOrdDetailID;
					}
				}
				/*==========================end=================================================*/
				
				/*===============insert journal==========================*/
				$this->insert_journal($CategoryType, $CategoryAmount, $currency_code, $currency_rate, $txt_do_date, $txa_description, $txt_do_no);
				/*===================end=================================*/
				
				$result_update = $this->m_delivery_order->update_transaction($this->transaction);
				$this->transaction 	= [];
				
				/*=============================trans roll back dan trans commit============================/*/
				if ($result_update == 0) {
					$result['status'] 	= FALSE;
					$result['message']  = get_notification_transaksi($this->name, 'update', 0, $txt_do_no);
				}
				else {
					$result['status'] 	= TRUE;
					$result['message']  = get_notification_transaksi($this->name, 'update', 1, $txt_do_no);
				}
				
				echo json_encode($result);
				/*==================================end======================================================*/	
			
			}
			else{
				throw new Exception("Delivery Order gagal disimpan. Tidak ada item pada Delivery Order."); 
			}
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
	
	function update_group($do_total_amount, $cmb_comp_po, $branch_code, $txt_do_no, $cmb_customer, $txa_address, $txa_ship_to, $cmb_ship_via, $txt_ship_date, $txa_description, $currency_code, $currency_rate, $txt_so_no, $txt_po_no, $txt_driver, $txt_car_number){
		$this->transaction['delete_journal']['DOrdNumber'] = $txt_do_no;
					
		$data = array (
			'BranchCode'		=> $this->session->userdata('branch'),
			'CustomerCode'		=> $cmb_customer,
			'BillingAddress'	=> $txa_address,
			'ShipAddress'		=> $txa_ship_to,
			'ShipmentID'		=> $cmb_ship_via,
			'ShipDate'			=> date('Y-m-d', strtotime($txt_ship_date)),
			'DOrdDesc'			=> $txa_description,
			'CurrencyCode'		=> $currency_code,
			'CurrencyRate'		=> $currency_rate,
			'SOrdNumber'		=> $txt_so_no,
			'SOrdDate'			=> date('Y-m-d', strtotime($this->m_sales_order->get_so_date($txt_so_no))),
			'CustPONumber'		=> $txt_po_no,
			'CustPODate'		=> date('Y-m-d', strtotime($this->m_sales_order->get_po_date($txt_so_no))),			
			'DriverName'		=> $txt_driver,
			'DOrdTotalAmount'	=> $do_total_amount,
			'LicencePlate'		=> $txt_car_number,
			'CompPONumber'		=> $cmb_comp_po,
			'PrintStatus'		=> 0,
			'NumberUnik' 		=> $branch_code.'/'.rand(00000,99999),
			'AppFinished' 		=> 2,
			'LastUser'			=> $this->session->userdata('username')
		);
		
		$this->transaction['update_group']['data']= $data;
		$this->transaction['update_group']['DOrdNumber'] = $txt_do_no;
	}

	// Function Suspend Transaction Data
	public function suspend_data(){
		try{
			$result_edit	= 0;
			$DOrdNumber		= str_replace(".", "/", $this->input->post('id'));
			$data			= $this->m_delivery_order->get_detail($DOrdNumber);
			
			if($data->TransStatus == 4){
				$data_do = array (			
					'TransStatus'   => $this->input->post('trans_status'),
					'LastUser'      => $this->session->userdata("username")
				);
				
				//1. Update Sales Order TransStatus
				$this->transaction['update_group']['data']= $data_do;
				$this->transaction['update_group']['DOrdNumber'] = $DOrdNumber;
				
				//2. Update Item Qty Sales Quotation
				$data_detail = $this->m_delivery_order->get_detail_item($DOrdNumber, $data->BranchCode);
				foreach($data_detail as $row){
					$ItemQtyDO      = $this->m_sales_order->get_qty_do($row->SOrdDetailID);
					
					$newitem_qtydo  = intval($ItemQtyDO) - intval($row->ItemQty);
					$detail_qtydo   = array('ItemQtyDO' => $newitem_qtydo);
					
					$this->transaction['update_so']['data'][] = $detail_qtydo;
					$this->transaction['update_so']['SOrdDetailID'][] = $row->SOrdDetailID;	
				}
				
				$result_suspend = $this->m_delivery_order->suspend_transaction($this->transaction);
				$this->transaction 	= [];
				
				/*=============================trans roll back dan trans commit============================/*/
				if ($result_suspend == 0) {
					$result['status'] 	= FALSE;
					$result['message']  = get_notification('cancel', 0);
				}
				else {
					$result['status'] 	= TRUE;
					$result['message']  = get_notification('cancel', 1);
				}
				/*==================================end======================================================*/
				echo json_encode($result);
			}
			else {
				throw new Exception(get_notification('cancel', 0));
			}
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
	}
	
    // Function Approval Manager
    public function approval(){ 
		/*=======================deklar variabel====================================================*/
		$DOrdNumber			= $this->input->post('id');
		$CurrencyCode		= $this->input->post('txt_currency_code');
		$CurrencyRate		= $this->input->post('txt_rate')?$this->input->post('txt_rate'):0;
		$FiscalRate 		= 1;
		$SOrdSubTotal		= $this->input->post('hdn_sub_total');
		
		$SOrdTaxPcnt 		= $this->input->post('hdn_ppn_pcnt');
		$SOrdTaxes			= $this->input->post('hdn_ppn');
		$SOrdTaxesPPH23			= $this->input->post('hdn_pph23');
		

		$SOrdTotalAmount 	= $this->input->post('hdn_total_amount');
		$SOrdNumber 		= $this->input->post('txt_so_no');
		$branch_code		= $this->input->post('branch_code');
		$chk_direct			= $this->input->post('txt_direct');
		$number_unik		= $this->input->post('number_unik');
		
		if($chk_direct == 1){
			$cmb_comp_po	= $this->input->post('cmb_comp_po');
		}
		
		$txt_do_date		= $this->input->post('txt_do_date');
		$txt_ship_date		= $this->input->post('txt_ship_date');
		
		$txa_description	= $this->input->post('txa_description');
		$SInvDisc			= $this->input->post('hdn_amont_disc');
		$SInvNumber 		= $this->m_sales_invoice->create_si_number($txt_do_date);
		
		$detail_so			= $this->m_delivery_order->join_so_new($DOrdNumber);
		$detail_item		= $this->m_delivery_order->get_detail_item($DOrdNumber, $detail_so[0]->BranchCode);
		$detail				= json_decode($this->input->post('detail'));
		$finished_so		= false;
		$result_insert 		= 0;
		$result_edit		= 0;
		$TotalQty			= 0;
		
		$CategoryAmountSi 	= array();
		$CategoryTypeSum 	= array();
		$CategoryAmountNew 	= array();
		$CategoryPPNAmount 	= array();
		$CategoryTypeSi 	= array();
		$CategoryAmount 	= array();
		$CategoryType 		= array();
		
		/*
			jika dia do direct maka function dibawah ini langsung dijalankan
			0 = no do direc
			1 = do direct
		*/
		$this->db->trans_begin();
		
		foreach($detail as $row_grid){
			$item_qty_inventori 		= $this->m_inventories->get_item_qty($row_grid->ItemCode, $branch_code); //get data inventory tampilkan qty saja
			if($chk_direct != 1){
				if($row_grid->ItemStatus == 0){
					if($row_grid->ItemQty > $item_qty_inventori){
						$result['status'] 		= FALSE;
						$result['message']  	= "Transaksi gagal, Item Qty DO melebihi Item Qty Di Inventory untuk Item ". $row_grid->ItemDesc ." silahkan lihat kembali Qty Inventory";
						echo json_encode($result);
						$this->db->trans_rollback();
						die();
					}
				}
			}
			else{
				$get_po_detail_by_do_direct = $this->m_purchase_order->get_detail_sum_pord($cmb_comp_po, $row_grid->ItemCode);
				if($row_grid->ItemQty > $get_po_detail_by_do_direct->ItemQtyAllPo){
					$result['status'] 		= FALSE;
					$result['message']  	= 'Maaf transaksi Do Direct gagal, Item Code '.$row_grid->ItemCode.' melebihi Qty Purchases Order';
					echo json_encode($result);
					$this->db->trans_rollback();
					die();
				}
			}
			
			//cek lock status adjustment 
			$get_inventori_code = $this->m_inventories->get_inventori_by_item($row_grid->ItemCode, $branch_code);
			if(!empty($get_inventori_code->ItemCode)){
				if($get_inventori_code->LockStatus == 1){
					$result['status'] 		= FALSE;
					$result['message']  	= "Produk ".$get_inventori_code->ItemCode.", sedang dalam proses Adjustment.";
					echo json_encode($result);
					$this->db->trans_rollback();
					die();
				}
			}
			//end
		}
		
		if($chk_direct == 1){
			$unbilled_amount    = 0;
			$unbilled_status    = FALSE;
			
			$prec_no 					=  $this->m_receive_item->create_ri_number($txt_do_date);
			$this->insert_receive_item($cmb_comp_po, $txa_description, $branch_code, $txt_do_date, $prec_no, $txt_ship_date);
			
			$this->insert_detail_receive_item($DOrdNumber, $TotalQty, $txt_do_date, $CurrencyCode, $CurrencyRate, $unbilled_amount, $unbilled_status, $cmb_comp_po, $prec_no, $txa_description);
			
			$data_appfinish = array(	
				'TransStatus'		=> 1,
				'AppFinished'       => 1,
				'AppLevel1Status' 	=> 1,
				'AppLevel1Code'     => $this->session->userdata("username"),
				'AppLevel1Date'		=> date("Y-m-d"),
				'LastUser'			=> $this->session->userdata("username")
			);
			
			$this->m_receive_item->update($data_appfinish, $prec_no);
		}
		/*=============end==================================================*/
		
		/*==============================end==============================================================*/
		$data = array(	
			'TransStatus'		=> 1,
			'AppFinished'       => 1,
			'AppLevel1Status' 	=> 1,
			'AppLevel1Code'     => $this->session->userdata("username"),
			'AppLevel1Date'		=> date("Y-m-d"),
			'LastUser'			=> $this->session->userdata("username")
		);
		
		$this->m_delivery_order->delete_journal($DOrdNumber);
		//$this->transaction['delete_journal']['DOrdNumber'] = $DOrdNumber;
		
		$get_detail_item_do = $this->m_delivery_order->get_detail_item($DOrdNumber, $branch_code);
		
		foreach($get_detail_item_do as $row_detail_do){
			//update do approval di SO
			$data_so = array(
				'ItemQtyDOApp'	=> ($row_detail_do->ItemQtyDOApp + $row_detail_do->ItemQty), 
				'LastUser'		=> $this->session->userdata('username')
			);
			
			$this->m_sales_order->update_detail($data_so, $row_detail_do->SOrdDetailID);
			//$this->transaction['update_so']['data'][] = $data_so;
			//$this->transaction['update_so']['SOrdDetailID'][] = $row_detail_do->SOrdDetailID;
			//end
			
			//update qty do di SQ
			$data_detail_sq	= array(
				'ItemQtyDO'     => ($row_detail_do->ItemQtyDOApp+ $row_detail_do->ItemQty), 
				'LastUser'      => $this->session->userdata('username')
			);
			
			$this->m_sales_quotation->update_detail($data_detail_sq, $row_detail_do->SQuoDetailID);
			//$this->transaction['update_sq']['data'][] = $data_detail_sq;
			//$this->transaction['update_sq']['SQuoDetailID'][] = $row_detail_do->SQuoDetailID;
			//end
					
			//kondisi status so (all item proses so)
			$ItemQtyDOApp 	= $row_detail_do->ItemQtyDOApp + $row_detail_do->ItemQty;
			$ItemQtySO		= $row_detail_do->ItemQtySO;
			
			if($ItemQtyDOApp==$ItemQtySO){
				$finished_so = true;
			}
			else{
				$finished_so = false;
			}
			//end
			
			if($row_detail_do->ItemStatus == 0){
				$get_item_inventory = $this->m_inventories->get_inventori_by_item($row_detail_do->ItemCode, $branch_code);
				$New_ItemQty 		= $get_item_inventory->ItemQty - $row_detail_do->ItemQty;
				$new_itemvalue      = $New_ItemQty * $get_item_inventory->ItemAverage;
				
				$data_inventory = array(
					'ItemQty' 		=> $New_ItemQty,
					'ItemValue' 	=> $new_itemvalue
				);
				
				$this->m_inventories->update($data_inventory, $row_detail_do->ItemCode);
				//$this->transaction['update_inventori']['data'][] = $data_inventory;
				//$this->transaction['update_inventori']['ItemCode'][] = $row_detail_do->ItemCode;
				
				/*
					Update detail do direct
				*/
				$data_detail_do = array(
					'ItemPriceCogs' => $get_item_inventory->ItemAverage
				);
				$this->m_delivery_order->update_detail($data_detail_do, $row_detail_do->DOrdDetailID);
				/*===================End=============*/
			
				if($CurrencyCode != 'IDR'){
					$convert_item_curr = $get_item_inventory->ItemAverage / $CurrencyRate;
					$hasil_amount_qty = $row_detail_do->ItemQty * $convert_item_curr;
				}
				else{
					$hasil_amount_qty = $row_detail_do->ItemQty * $get_item_inventory->ItemAverage;
				}
				
				@$CategoryAmount[$row_detail_do->ItemCategoryID] += $hasil_amount_qty;
				@$CategoryType[$row_detail_do->ItemCategoryID] = $row_detail_do->ItemStatus;
			}
			else{
				if($CurrencyCode != 'IDR'){
					$convert_item_curr = 0;
					$hasil_amount_qty = $row_detail_do->ItemQty * $convert_item_curr;
				}
				else{
					$hasil_amount_qty = 0;
				}
				
				@$CategoryAmount[$row_detail_do->ItemCategoryID] += $hasil_amount_qty;
				@$CategoryType[$row_detail_do->ItemCategoryID] = $row_detail_do->ItemStatus;
			}
			
			$TotalQty += $row_detail_do->ItemQty;
		}
		/*===============insert journal do==========================*/
		$this->insert_journal_app($CategoryType, $CategoryAmount, $CurrencyCode, $CurrencyRate, $txt_do_date, $txa_description, $DOrdNumber);
		/*===================end=================================*/
		
		$do_number_explode  = explode(",", $SOrdNumber);	
			
		$TotalQtyRI_On_RI 	= 0;
		$TotalQtySpd_On_PO 	= 0;
		$get_po_set_finish 	= 0;
		
		foreach($do_number_explode as $key => $value){
			$TotalQtyRI_On_RI 	= $this->m_sales_order->set_finish($value);
			
			$TotalQtySpd_On_PO 	= $this->m_sales_order->get_total_qty_so_spd($value);
			$get_po_set_finish 	= $this->m_sales_order->set_finish_so_new($value);
			$get_qty_ri 		= $this->m_sales_order->get_qty_delivery_order($value, $DOrdNumber);
			
			$QtyDO 				= empty($TotalQtyRI_On_RI->TotalQtyDO) ? 0 : $TotalQtyRI_On_RI->TotalQtyDO;
			$QtySpd 			= empty($TotalQtySpd_On_PO->TotalQtySpd) ? 0 : $TotalQtySpd_On_PO->TotalQtySpd;
			$QtyDO_FromNumber 	= empty($get_qty_ri->TotalQtyDO_All) ? 0 : $get_qty_ri->TotalQtyDO_All;
			
			$total_qty_po 		= ($QtyDO + $QtySpd) + $QtyDO_FromNumber;
			
			if($total_qty_po == $get_po_set_finish->TotalQtySO){
				$trans_stataus = 2;
			}
			else{
				$trans_stataus = 1;
			}
			
			
			$data_prec = array (
				'TransStatus'   => $trans_stataus,
				'LastUser'      => $this->session->userdata("username")
			);
			
			$this->m_sales_order->update($data_prec, $value);
			
			//$this->transaction['update_proses_so']['data'][] 			= $data_prec;
			//$this->transaction['update_proses_so']['SOrdNumber'][] 	= $value;
		} 
		//------------------------------------------------------------------------------------------------------//
		
		//1. Update Delivery Order.
		$this->m_delivery_order->update($data, $DOrdNumber);
		//$this->transaction['update_group']['data']= $data;
		//$this->transaction['update_group']['DOrdNumber'] = $DOrdNumber;
		//end
		
		//1. Update Purhcase Order Status
		
		/*=============================================MODUL SALES INVOICE================================================================*/
		foreach($detail_so as $row_group){
			$SOrdNumber = $row_group->SOrdNumber;
			if($row_group->SOrdTaxesStatus == 0) { $SInvTaxesStatus = 0; } else { $SInvTaxesStatus = 1; }
			if($row_group->SOrdInTaxStatus == 0) { $SInvInTaxStatus = 0; } else { $SInvInTaxStatus = 1; }
			
			$SInvDueDate	= date('Y-m-d', strtotime('+'. $row_group->NetDueIn .' days', strtotime(date('Y-m-d'))));
			
			//masuk group SI
			$data_si = array(
				'BranchCode'		=> $row_group->BranchCode, 
				'CustomerCode'		=> $row_group->CustomerCode, 
				'SInvDate'			=> date('Y-m-d'), 
				'SInvNumber'		=> $SInvNumber, 
				'DOrdDate'			=> date('Y-m-d', strtotime($row_group->DOrdDate)), 
				'DOrdNumber'		=> $row_group->DOrdNumber, 
				'SOrdNumber'		=> $SOrdNumber, 
				'CustPONumber'		=> $row_group->CustPONumber, 
				'ShipDate'			=> $row_group->ShipDate, 
				'ShipmentID'		=> $row_group->ShipmentID, 
				'TermsPaymentID'	=> $row_group->TermsPaymentID, 
				'FOBID'				=> $row_group->FOBID, 
				'SInvDueDate'		=> $SInvDueDate, 
				'BillingAddress'	=> $row_group->BillingAddress, 
				'ShippingAddress'	=> $row_group->ShipAddress, 
				'CurrencyCode'		=> $row_group->CurrencyCode, 
				'CurrencyRate'		=> $row_group->CurrencyRate, 
				
				'SInvSubTotal'		=> $SOrdSubTotal, 
				'SInvDiscount'		=> $SInvDisc, 
				'SInvPPNPcnt'		=> $row_group->SOrdTaxPcnt, 
				'SInvPPNOut'		=> $SOrdTaxes, 
				'SInvTotalAmount'	=> ($SOrdTotalAmount - $row_group->SOrdPPh23), 
				
				'SInvTaxesStatus'	=> $row_group->SOrdTaxesStatus, 
				'SInvInTaxStatus'	=> $row_group->SOrdInTaxStatus, 

				'SInvPPH23' 		=> $row_group->SOrdPPh23,
				'SOrdPPh23Pcnt' 	=> $row_group->SOrdPPh23Pcnt,
				
				'SInvEstFreight'	=> $row_group->SOrdEstFreight, 
				'SInvDPStatus' 		=> $row_group->SOrdDPStatus,
				'SInvDesc' 			=> $row_group->DOrdDesc,
				'TransStatus'		=> 4, 
				'CreatedBy' 		=> $this->session->userdata('username'),
				'CreatedAt' 		=> date('Y-m-d'),
				'NumberUnik' 		=> $number_unik,
				'LastUser'			=> $this->session->userdata('username')
			);
			
			$this->m_sales_invoice->insert($data_si);
			//$this->transaction['insert_group_si']['data'][] = $data_si;
			//end
		}
		
		foreach($detail as $row){
			//insert item di SI
			$detail_si = array(
				'SOrdNumber'		=> $row->SOrdNumber, 
				'SInvNumber'		=> $SInvNumber, 
				'SOrdDetailID'		=> $row->SOrdDetailID,
				'ItemCode'			=> $row->ItemCode,
				'ItemDesc'			=> $row->ItemDesc, 
				'ItemQty'			=> $row->ItemQty, 
				'ItemUnit'			=> $row->ItemUnit, 
				'ItemPrice'			=> $row->ItemPrice,
				'ItemDiscPcnt'		=> $row->ItemDiscPcnt,
				'ItemPriceCogs'		=> $row->ItemAverage, 
				'ItemTax'			=> $row->ItemTax, 
				//'ItemPPH23' 		=> 
				'ItemAmount'		=> $row->TotalAmount, 
				'ItemTotalAmount'	=> $row->TotalAmount + $row->ItemTax, 
				'SalesmanCode'		=> $row->SalesmanCode, 
				'ItemCategoryID'	=> $row->ItemCategoryID,
				'ItemCategoryCode'	=> $row->ItemCategoryCode,
				'ItemType'			=> $row->ItemStatus, 
				'ItemPPH23' 		=> $row->Item_pph23,
				'LastUser'			=> $this->session->userdata('username')
			);
			
			$this->m_sales_invoice->insert_detail($detail_si);
			//$this->transaction['insert_detail_si']['data'][] = $detail_si;
			//end
			
			//perhitungan amount dari so untuk jurnal sales invoice
			@$CategoryAmountSi[$row->ItemCategoryID]    	+= $row->TotalAmount;
			@$CategoryTypeSi[$row->ItemCategoryCode]     	=  $row->ItemStatus;
			@$CategoryPPNAmount[$row->ItemCategoryID] 	+= $row->ItemTax;
			@$CategoryTypeSum[$row->ItemCategoryID]     =  $row->ItemStatus;
			@$CategoryAmountNew[$row->ItemCategoryID]   += $row->TotalAmount;
		}
		
		
		//insert jurnal
		$x = 100;
		$total_records  			= count(@$CategoryAmountSi);
		$total_loop     			= 0;
		$total_ratio    			= 0;
		$Persen 					= 100;
		$ItemRatio 				  	= 0;		
		$ReceivableAmountCurrency 	= 0;
		$RecivTotal 				= 0;
		$sub_total 					= 0;
		$ppn_total 					= 0;
		$payable_value 				= 0;
		$payable_currency 			= 0;
		
		/*
			Journal Receiveable End Unbill
		*/
		
		foreach($CategoryAmountSi as $key=>$value){
			$total_loop++;
			
			if($total_loop == $total_records){
				$ItemRatio = $Persen - $total_ratio;
			} 
			else {
				$ItemRatio = floor(abs((doubleval($value) / $SOrdSubTotal) * 100));
			}
			$total_ratio  	= $total_ratio + $ItemRatio;
			$sub_total 		= $SOrdSubTotal * ($ItemRatio / 100);
			$ppn_total 		= $SOrdTaxes * ($ItemRatio / 100);
			$pph_23 		= $SOrdTaxesPPH23 * ($ItemRatio / 100);
			
			$item_ppn       	= ($CurrencyCode == 'IDR' && $SOrdTaxPcnt > 0) ? (doubleval($ppn_total)) : 0;    
			$Total_Purchase 	= $sub_total + $item_ppn - $pph_23;
			
			$payable_value      = $CurrencyCode == 'IDR' ? $Total_Purchase : $Total_Purchase * $CurrencyRate;
			$payable_currency   = $Total_Purchase;
			
			if($CategoryTypeSum[$key] == 0){
				$ReceivableAccount	= $this->m_account_journal->get_cat_sales_account('SRAccountReceivable',$key,$CurrencyCode);
				if($ReceivableAccount == false) {$this->trans_rollback('preference','Receivable Account,Sales','');}
			}
			else{
				$ReceivableAccount    	= $this->m_account_journal->get_sys_service_account('SalesUnbilled', $CurrencyCode);
				if($ReceivableAccount == false) {$this->trans_rollback('preference','Expense,Expense','');}
			}
			
			//$get_invoice_journal = $this->m_sales_invoice->get_sales_invoice_journal($ReceivableAccount->AccountNumber, $SInvNumber);
			$journal_Unbilled        = array(
				'SInvDate'              => date('Y-m-d'),
				'SInvNumber'            => $SInvNumber,
				'SInvAccountNumber'     => $ReceivableAccount->AccountNumber,
				'SInvSaldoDebet'        => $payable_value, 
				'SInvSaldoCredit'       => 0,
				'AmountCurrency'        => $payable_currency,
				'SInvSignStatus'        => 0,
				'LastUser'              => $this->session->userdata("username")	
			);	
			
			$this->m_sales_invoice->insert_journal($journal_Unbilled);
		}
		/*============================END========================*/
		
		/*
			Journal Sales Account End Sales Expense
		*/
		$x = 100;
		$total_records_new  			= count(@$CategoryAmountNew);
		$total_loop_new     			= 0;
		$total_ratio_new    			= 0;
		$Persen_new 					= 100;
		$ItemRatio_new 				  	= 0;	
		$payable_value 					= 0;
		$payable_currency 				= 0;	
		
		
		foreach($CategoryAmountNew as $key=>$value){
			$total_loop_new++;
			
			if($total_loop_new == $total_records_new){
				$ItemRatio_new = 100 - $total_ratio_new;
			} 
			else {
				$ItemRatio_new = floor(abs((doubleval($value) / $SOrdSubTotal) * 100));
			}
			$total_ratio_new  	= $total_ratio_new + $ItemRatio_new;
			$sub_total 			= doubleval($SOrdSubTotal) * ($ItemRatio_new / 100);
			
			if($CategoryTypeSum[$key] == 0){
				$SalesAccount = $this->m_account_journal->get_cat_item_account('Sales',$key,'IDR');
				if($SalesAccount == false) {$this->trans_rollback('preference','Sales Account,Sales','');}
			}
			else{
				$SalesAccount    = $this->m_account_journal->get_sys_service_account('SalesExpense', 'IDR',$key);
				if($SalesAccount == false) {$this->trans_rollback('preference','Sales Account,Expense','');}
			}
			
			//$get_invoice_journal = $this->m_sales_invoice->get_sales_invoice_journal($SalesAccount->AccountNumber, $SInvNumber);
			
			$payable_value      = $CurrencyCode == 'IDR' ? $sub_total : $sub_total * $CurrencyRate;
			$payable_currency   = $sub_total;
		
			$journal_sales       = array(
				'SInvDate'              => date('Y-m-d'),
				'SInvNumber'            => $SInvNumber,
				'SInvAccountNumber'     => $SalesAccount->AccountNumber,
				'SInvSaldoDebet'        => 0, 
				'SInvSaldoCredit'       => $payable_value,
				'AmountCurrency'        => $payable_currency,
				'SInvSignStatus'        => 0,
				'LastUser'              => $this->session->userdata("username")	
			);	
			
			$this->m_sales_invoice->insert_journal($journal_sales);		}
		/*=====================================END===============*/
		
		/*
			function ini jalan jika ada ppn
		*/
		if($data_si['SInvPPNOut'] > 0){
			if($CurrencyCode != 'IDR'){
				$PPnFiscalAccount   = $this->m_account_journal->get_account_name('Piutang PPn Fiscal'); 
				if($PPnFiscalAccount == false) {$this->trans_rollback('preference','Piutang PPn Fiscal,Expense','');}
				if($PPnFiscalAccount == false) {$this->trans_rollback('ppn');}
				
				$data_taxable_journal = array(
					'SInvDate'			=> date('Y-m-d'), 
					'SInvNumber'		=> $SInvNumber, 
					'SInvAccountNumber'	=> $PPnFiscalAccount->AccountNumber, 
					'SInvSaldoDebet'	=> (doubleval($SOrdTaxes)*doubleval($FiscalRate)), 
					'SInvSaldoCredit'	=> 0, 
					'AmountCurrency'	=> doubleval($SOrdTaxes), 
					'SInvSignStatus'    => 0, 
					'LastUser'			=> $this->session->userdata('username')
				);
				
				$this->m_sales_invoice->insert_journal($data_taxable_journal);
				
				//$this->transaction['insert_journal']['data'][] = $data_taxable_journal;
				
				$TaxableAccount		= $this->m_account_journal->get_sys_sales_account('SalesTaxable','IDR');
				if($TaxableAccount == false) {$this->trans_rollback('preference','Sales Taxable Cr,Expense','');}
				
				$data_taxable_journal_credit = array(
					'SInvDate'			=> date('Y-m-d'), 
					'SInvNumber'		=> $SInvNumber, 
					'SInvAccountNumber'	=> $TaxableAccount->AccountNumber, 
					'SInvSaldoDebet'	=> 0, 
					'SInvSaldoCredit'	=> (doubleval($SOrdTaxes)*doubleval($FiscalRate)), 
					'AmountCurrency'	=> doubleval($SOrdTaxes), 
					'SInvSignStatus'    => 0, 
					'LastUser'			=> $this->session->userdata('username')
				);
				
				$this->m_sales_invoice->insert_journal($data_taxable_journal_credit);
				//$this->transaction['insert_journal']['data'][] = $data_taxable_journal_credit;
			}
			else{
				$TaxableAccount		= $this->m_account_journal->get_sys_sales_account('SalesTaxable','IDR');
				if($TaxableAccount == false) {$this->trans_rollback('preference','Sales Taxable Db,Expense','');}
				
				$data_taxable_journal = array(
					'SInvDate'			=> date('Y-m-d'), 
					'SInvNumber'		=> $SInvNumber, 
					'SInvAccountNumber'	=> $TaxableAccount->AccountNumber, 
					'SInvSaldoDebet'	=> 0, 
					'SInvSaldoCredit'	=> (doubleval($SOrdTaxes)*doubleval($CurrencyRate)), 
					'AmountCurrency'	=> doubleval($SOrdTaxes), 
					'SInvSignStatus'    => 0, 
					'LastUser'			=> $this->session->userdata('username')
				);
				
				$this->m_sales_invoice->insert_journal($data_taxable_journal);
				//$this->transaction['insert_journal']['data'][] = $data_taxable_journal;
			}
		}
		/*====================================END=======================================*/
		
		/*
			PPH 23
		*/
		if($data_si['SInvPPH23'] > 0){
			$PPh23Account   = $this->m_account_journal->get_account_name('PPh Pasal 23 Dibayar Dimuka'); 
			if($PPh23Account == false) {$this->trans_rollback('preference','Piutang PPh 23,Expense','');}
			

			$journal_taxpph23 = array(
                'SInvDate' => date('Y-m-d'),
                'SInvNumber' => $SInvNumber,
                'SInvAccountNumber' => $PPh23Account->AccountNumber,
                'SInvSaldoDebet' => (doubleval($SOrdTaxesPPH23)*doubleval($CurrencyRate)),
                'SInvSaldoCredit' => 0, 
                'AmountCurrency' => doubleval($SOrdTaxesPPH23), 
                'SInvSignStatus' => 1,
                'LastUser' => $this->session->userdata("username")
            );

			
			$this->m_sales_invoice->insert_journal($journal_taxpph23);
		}
		/*=============================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']  	= 'Delivery Order berhasil di approve, silahkan reload halaman list, No Transaksi Sales Invoice anda : '.$SInvNumber.'';
		}
		/*==================================end======================================================*/
		echo json_encode($result);
	}
	
	/*=============insert receive item jika do direct========================*/
	function insert_receive_item($cmb_comp_po, $txa_description, $branch_code, $txt_do_date, $prec_no, $txt_ship_date){
		$get_purchases_order 	= $this->m_purchase_order->get_purchase_order_by_do($cmb_comp_po);
		
		$data = array (
			'BranchCode'		=> $branch_code,
			'VendorCode' 		=> $get_purchases_order->VendorCode,
			'PRecNumber' 		=> $prec_no,
			'PRecDate'          => date("Y-m-d", strtotime($txt_do_date)),
			'POrdDate'          => $get_purchases_order->POrdDate,
			'POrdNumber'		=> $get_purchases_order->POrdNumber,
			'VendorDONumber'    => "",                
			'ShipmentDate'		=> date("Y-m-d", strtotime($txt_ship_date)),	
			'ShipmentID'		=> $get_purchases_order->ShipmentID,
			'TermsPaymentID'    => $get_purchases_order->TermsPaymentID,
			'FOBID'				=> $get_purchases_order->FOBID,
			'CurrencyCode'      => $get_purchases_order->CurrencyCode,
			'CurrencyRate'		=> $get_purchases_order->CurrencyRate,
			'PRecDesc'          => $txa_description,
			'PRecSubTotal'      => $get_purchases_order->POrdSubTotal,
			'PRecPPn10Pcnt'     => $get_purchases_order->POrdPPn10Pcnt,                
			'PRecPPn10'         => $get_purchases_order->POrdPPn10,
			'PRecTotalAmount'   => $get_purchases_order->POrdTotalAmount,
			'PRecTaxesStatus'   => $get_purchases_order->POrdTaxesStatus,
			'PRecInTaxStatus'   => $get_purchases_order->POrdInTaxStatus,
			'CreatedBy' 		=> $this->session->userdata("username"),
			'CreatedAt' 		=> date("Y-m-d", strtotime($txt_do_date)),
			'LastUser'          => $this->session->userdata("username")
		);
		
		$this->m_receive_item->insert($data);
		//$this->transaction['insert_ri']['data'] = $data;
	}
	/*===================end==================================================*/
	
	function insert_detail_receive_item($DOrdNumber, $TotalQty, $txt_do_date, $CurrencyCode, $CurrencyRate, $unbilled_amount, $unbilled_status, $cmb_comp_po, $prec_no, $txa_description){
		
		$CategoryIDAmt				= array();
		$CategoryIDCode				= array();
		$CategoryIDType 			= array();
		$get_purchases_order_detail = $this->m_purchase_order->get_detail_item($cmb_comp_po);
		
		$po_number      			= explode(",", $cmb_comp_po);	
		
		foreach($get_purchases_order_detail as $row_detail){
			$get_qty_do  = $this->m_delivery_order->get_qty_dordetail($cmb_comp_po, $row_detail->ItemCode, $DOrdNumber);
			$total_price = ($row_detail->ItemPrice - ($row_detail->ItemPrice * $row_detail->ItemDisc) / 100);
			
			if(!empty($get_qty_do->ItemCode)){
				$detail_data = array(
						'POrdDetailID'          => $row_detail->POrdDetailID,
						'POrdNumber'            => $row_detail->POrdNumber,
						'PRecNumber'            => $prec_no,
						'ItemCode'              => $row_detail->ItemCode,
						'ItemDesc'              => $row_detail->ItemDesc,
						'itemUnit'              => $row_detail->ItemUnit,
						'itemQty'               => $get_qty_do->ItemQty,
						'ItemPrice'             => $row_detail->ItemPrice,
						'ItemAmount'            => $row_detail->ItemAmount,
						
						'ItemTaxPPn10'          => $row_detail->ItemTaxPPn10,
						'ItemTotalAmount'       => $row_detail->ItemTotalAmount,
						
						'ItemCategoryID'        => $row_detail->ItemCategoryID,
						'ItemCategoryCode'      => $row_detail->ItemCategoryCode,
						'ItemType'              => $row_detail->ItemType,
						'ItemStatus'            => $row_detail->ItemStatus,
						'LastUser'              => $this->session->userdata("username")				
				); 
				
				$this->m_receive_item->insert_detail($detail_data);
				
				//$this->transaction['insert_ri_detail']['data'][] = $detail_data;
				
				//3. Update ItemQTYRI pada Purchase Order Detail
				$newItemQtyRI       = $row_detail->ItemQtyRI + $get_qty_do->ItemQty;
				
				$detail_data_po = array(
					'ItemQtyRI'	=> $newItemQtyRI,				
					'LastUser' 	=> $this->session->userdata("username")					
				);				
				
				$this->m_purchase_order->update_detail($detail_data_po, $row_detail->POrdDetailID);
				
				//$this->transaction['update_qty_po']['data'][] 			= $detail_data_po;
				//$this->transaction['update_qty_po']['POrdDetailID'][] 	= $row_detail->POrdDetailID;
				//---------------------------------------------------------------------------------------------------------//
					
				$get_inventory = $this->m_inventories->get_inventories($row_detail->ItemCode);
				
				if($row_detail->POrdTaxesStatus == 1){
					if($row_detail->POrdInTaxStatus == 1){
						$total_price = (100 / (100 + $row_detail->POrdPPn10Pcnt) * $total_price);
					}
				}
				
				if($row_detail->ItemType == 0){
					$ItemAmount 	= $get_qty_do->ItemQty * $total_price;		
					$item_qty       = ($get_inventory->ItemQty) + ($get_qty_do->ItemQty);
					$item_value     = doubleval($get_inventory->ItemValue) + doubleval($ItemAmount * $row_detail->CurrencyRatePo);
					$item_average   = doubleval($item_value) / $item_qty;
					
					$data_inventory = array(
										'ItemQty'       => $item_qty,
										'ItemAverage'   => $item_average,
										'ItemValue'     => $item_value,
										'LastUser'      => $this->session->userdata("username")
										);
					
					$this->m_inventories->update($data_inventory, $row_detail->ItemCode);
				}
				//$this->transaction['update_inventori']['data'][] 		= $data_inventory;
				//$this->transaction['update_inventori']['ItemCode'][] 	= $row_detail->ItemCode;
					
				 //2. insert to table detail receive item
				
				@$CategoryIDAmt[$row_detail->ItemCategoryID]   += ($ItemAmount);
				@$CategoryIDCode[$row_detail->ItemCategoryID]   = $row_detail->ItemCategoryCode;
				@$CategoryIDType[$row_detail->ItemCategoryID]   = $row_detail->ItemType;
			}
		}
		
		/*
			insert journal reciv item based on category
		*/
		
		$this->insert_journal_recive_item($cmb_comp_po, $CategoryIDType, $CategoryIDAmt, $CategoryIDCode, $CurrencyCode, $CurrencyRate, $txt_do_date, $prec_no, $unbilled_amount, $unbilled_status, $txa_description);
		/*====================end=============================*/
		
		//1. Update Purhcase Order Status
		$TotalQtyRI_On_RI 	= 0;
		$TotalQtySpd_On_PO 	= 0;
		$get_po_set_finish 	= 0;
		
		foreach($po_number as $key => $value){
			$TotalQtySpd_On_PO 	= $this->m_delivery_order->get_total_qty_po($value);
			
			$get_po_set_finish 	= $this->m_purchase_order->set_finish_po($value);
			$get_qty_ri 		= $this->m_purchase_order->get_qty_receive_item($value, $prec_no);
			
			$total_qty_po 		= ($TotalQtySpd_On_PO->TotalQtyRI + $TotalQtySpd_On_PO->TotalQtySpd) + $TotalQty;
			if(strcmp(doubleval($total_qty_po),doubleval($get_po_set_finish->TotalQtyPO)) == 0){
				$trans_stataus = 2;
			}
			else{
				$trans_stataus = 1;
			}
			
			$data_prec = array (
				'TransStatus'   => $trans_stataus,
				'LastUser'      => $this->session->userdata("username")
			);
			
			$this->m_purchase_order->update($data_prec, $value);
			//$this->transaction['update_po']['data'][] 			= $data_prec;
			//$this->transaction['update_po']['POrdNumber'][] 	= $value;
		} 
		//------------------------------------------------------------------------------------------------------//
	}
	
	function insert_journal_recive_item($cmb_comp_po, $CategoryIDType, $CategoryIDAmt, $CategoryIDCode, $CurrencyCode, $CurrencyRate, $txt_do_date, $prec_no, $unbilled_amount, $unbilled_status, $txa_description){
		
		//4. insert journal inventory - Persesian Barang Dagang based on category
		$get_group_purchase_order = $this->m_purchase_order->get_purchase_order_by_do($cmb_comp_po);
		$Currecny_code_po = $get_group_purchase_order->CurrencyCode;
		$Currecny_rate_po = $get_group_purchase_order->CurrencyRate;
		
		foreach ($CategoryIDAmt as $key => $value) {
			if($CategoryIDType[$key] == 0) {
				$InventoryAccount   = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');									
				if($InventoryAccount == false) {$this->trans_rollback('preference','Inventory Account', $Currecny_code_po);} 
				$inventory_journal  = $Currecny_code_po == 'IDR' ? doubleval($value) : doubleval($value * $Currecny_rate_po);
				$inventory_currency = doubleval($value);

				$journal_inventory  = array(
										'PRecDate'              => date("Y-m-d", strtotime($txt_do_date)),
										'PRecNumber'            => $prec_no,
										'PRecDesc'              => $txa_description,
										'PRecAccountNumber'     => $InventoryAccount->AccountNumber,
										'PRecSaldoDebet'        => $inventory_journal,
										'PRecSaldoCredit'       => 0,
										'AmountCurrency'        => $inventory_currency,
										'PRecSignStatus'        => 0, 
										'ItemCategoryID'        => $key,
										'LastUser'              => $this->session->userdata("username")	
									);						
				
				$this->m_receive_item->insert_journal($journal_inventory);
				//$this->transaction['insert_journal_ri']['data'][] = $journal_inventory;
				
				$unbilled_amount    += doubleval($value);
				$unbilled_status     = TRUE;
			}
		}
        //--------------------------------------------------------------------------------------------------------------//
		
		//5. insert journal UnBilled
		if($unbilled_status){
			$UnbilledAccount    = $this->m_account_journal->get_sys_item_account('Unbilled');
			if($UnbilledAccount == false) {$this->trans_rollback('preference','Unbilled Account', $Currecny_code_po);} 

			$unbilled_journal  = $Currecny_code_po == 'IDR' ? $unbilled_amount : $unbilled_amount * $Currecny_rate_po;
			$unbilled_currency = $unbilled_amount;

			$journal_unbilled = array(
									'PRecDate'              => date("Y-m-d", strtotime($txt_do_date)),
									'PRecNumber'            => $prec_no,
									'PRecDesc'              => $txa_description,
									'PRecAccountNumber'     => $UnbilledAccount->AccountNumber,
									'PRecSaldoDebet'        => 0,
									'PRecSaldoCredit'       => $unbilled_journal,
									'AmountCurrency'        => $unbilled_currency,
									'PRecSignStatus'        => 0, 
									'ItemCategoryID'        => $key,
									'LastUser'              => $this->session->userdata("username")	
								);
			
			$this->m_receive_item->insert_journal($journal_unbilled);
			//$this->transaction['insert_journal_ri_unbilled']['data'] = $journal_unbilled;
		}
		//--------------------------------------------------------------------------------------------------------------//
	}
	
	/*
		Jangan lupa cek dari do ke si hanya satu dan dua
	*/
	function reverse_data_detail(){
		try{
			$DOrdNumber			= $this->input->post('id');
			$CurrencyCode		= $this->input->post('txt_currency_code');
			$CurrencyRate		= $this->input->post('txt_rate');
			$FiscalRate 		= 1;
			$SOrdSubTotal		= $this->input->post('hdn_sub_total');
			$SOrdTaxPcnt 		= $this->input->post('hdn_ppn_pcnt');
			$SOrdTaxes			= $this->input->post('hdn_ppn');
			$SOrdTotalAmount 	= $this->input->post('hdn_total_amount');
			$SOrdNumber 		= $this->input->post('txt_so_no');
			$branch_code		= $this->input->post('branch_code');
			$chk_direct			= $this->input->post('txt_direct');
			
			$number_unik		= $this->input->post('number_unik');
			$txt_do_date		= $this->input->post('txt_do_date');
			$txa_description	= $this->input->post('txa_description');
			$SInvDisc			= $this->input->post('hdn_amont_disc');
			$detail_so			= $this->m_delivery_order->join_so_new($DOrdNumber);
			$detail_item		= $this->m_delivery_order->get_detail_item($DOrdNumber, $detail_so[0]->BranchCode);
			$detail				= json_decode($this->input->post('detail'));
			$finished_so		= false;
			$result_insert 		= 0;
			$result_edit		= 0;
			$date_transaction 	= check_end_periode($DOrdNumber);
			
			$get_sales_order = $this->m_delivery_order->get_sales_order($SOrdNumber);
			if($get_sales_order){
				$trans_status = 0;
			}
			else{
				$trans_status = 1;
			}
			
			$get_detail_preq = $this->m_custom->check_item_reverse_do($DOrdNumber, 'at_salesinvoice', 'at_sinvdetail', 'SInvNumber', 'DOrdNumber');
			$get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);//Check Periode End
			if($chk_direct == 1){
				$cmb_comp_po	= $this->input->post('cmb_comp_po');
				$get_po_number 	= $this->m_delivery_order->get_po_number($cmb_comp_po);
				if ($get_po_number != false) {
					throw new Exception("Transaksi ini adalah DO Direct, silahkan reverse, Receive Item dengan No Transaksi ".$get_po_number->PRecNumber."");
				}
			}
			
			if ($get_detail_preq) {
				throw new Exception(msg_check_po_reverse('Sales Invoice'));
			} else if ($get_end_periode) {
				throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
			} 
			
			/*$get_sales_order = $this->m_delivery_order->get_sales_order($SOrdNumber);
			if($get_sales_order){
				throw new Exception("Transaksi gagal di Reverse, SO dengan No ".$SOrdNumber." mempunyai Down Payment, selesaikan pembayaran DP atau By Pass SO");
			}*/
			
			foreach ($detail as $row_detail) {
				$ItemQty 		= $row_detail->ItemQty;
				$ItemCode 		= $row_detail->ItemCode;
				$SOrdNumber 	= $row_detail->SOrdNumber;
				
				if($row_detail->ItemStatus == 0){	
					$item_lock_status = $this->m_inventories->get_inventori_by_item($ItemCode, $branch_code);
					if ($item_lock_status->LockStatus == 1) {
						throw new Exception(('Tidak bisa dilakukan proses Reverse, karena item ' . $row_detail->ItemCode . ' pada listing sedang dilakukan proses Adjustment')); //item adjust
					}
					
					$item_qty = ($item_lock_status->ItemQty) + ($row_detail->ItemQty);
					$TotalAverage = ($row_detail->ItemAverage * $row_detail->ItemQty);
					$item_value = doubleval($item_lock_status->ItemValue) + doubleval($TotalAverage);
					
					if (($item_qty == 0)) {
						$item_average = 0;
					} else {
						$item_average = doubleval($item_value) / $item_qty;
					}
					
					$data_inventori = array(
						'ItemQty' 		=> $item_qty,
						'ItemValue' 	=> $item_value,
						'ItemAverage' 	=> $item_average
					);
					$this->transaction['update_inventory']['data'][] = $data_inventori;
					$this->transaction['update_inventory']['ItemCode'][] = $ItemCode;
				}
			}
			
			$data_so = array(
				'TransStatus' => $trans_status,
				'LastUser' => $this->session->userdata("username")
			);
			
			$this->transaction['update_proses_so']['data'] = $data_so;
			$this->transaction['update_proses_so']['SOrdNumber'] = $SOrdNumber;
			
			$data_sret = array(
				'TransStatus' => 4,
				'AppLevel1Status' => 0,
				'AppLevel1Code' => NULL,
				'AppLevel1Date' => NULL,
				'AppFinished' => 0,
				'LastUser' => $this->session->userdata("username")
			);
			$this->transaction['update_do']['data'] = $data_sret;
			$this->transaction['update_do']['DOrdNumber'] = $DOrdNumber;	 
			
			$get_do_for_delete = $this->m_delivery_order->get_si_for_delete($DOrdNumber);
			foreach($get_do_for_delete as $row_sinv){
				$this->transaction['delete_invoice']['SInvNumber'][] = $row_sinv->SInvNumber;
			}	
			
			$result_approve = $this->m_delivery_order->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $DOrdNumber);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $DOrdNumber);
            }
            /* ==================================end====================================================== */
			echo json_encode($result);
		}
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
		
	}
	
    function to_preview($obj_string = null){
        // set data
        $data['menu_id'] =  $this->menu_id;
        $data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		$data_filter            = arrayParamInUrlToStr($obj_string);
		$data['branch_code'] = $data_filter['cmb_branch'];
		$data['company_code'] = $data_filter['cmb_company'];
        $data['list'] = $this->m_delivery_order->get_all_print($data_filter);

        $this->load->view('v_header');
        $this->load->view('sales/delivery_order/v_preview_deliveryorder', $data);
        $this->load->view('v_footer');	
    }
	
    //Function To Print
    public function to_print(){	
        // set data
       $data['menu_id'] =  $this->menu_id;
       $data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);

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

       $this->load->view('v_header');
       $this->load->view('sales/delivery_order/v_print_deliveryorder', $data);	
       $this->load->view('v_footer');	
    }
	
    // Function Print
    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());
//		$this->m_delivery_order->set_print_status($id);

        if($id != ""){		
            $data['detail'] 	= $this->m_delivery_order->get_detail_print($id);
            $data['variant'] 	= $this->m_delivery_order->get_detail_variant($id);
            $data['list'] = $this->m_delivery_order->get_detail_item_print($data['detail']->DOrdNumber,$data['detail']->BranchCode);		

            $this->load->view('v_header');
            $this->load->view('sales/delivery_order/v_print_detail_deliveryorder', $data);	
            $this->load->view('v_footer');	
        }
    }
	
    //Function preview data
    function to_preview_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_preview_detail/',"",$this->uri->uri_string());
        $this->m_delivery_order->set_print_status($id);

        if($id != ""){		
            $data['detail'] = $this->m_delivery_order->get_detail($id);
            $data['list'] = $this->m_delivery_order->get_detail_item($data['detail']->SQuoNumber);		

            $this->load->view('v_header');
            $this->load->view('sales/delivery_order/v_preview_detail_deliveryorder', $data);	
            $this->load->view('v_footer');	
        }
    }
	
    function to_print_journal(){	
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

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

        $this->load->view('v_header');
        $this->load->view('sales/delivery_order/v_print_journal_deliveryorder',$data);	
        $this->load->view('v_footer');	
    }
	
    function to_preview_journal(){	
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

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

        $this->load->view('v_header');
        $this->load->view('sales/delivery_order/v_preview_journal_deliveryorder',$data);	
        $this->load->view('v_footer');	
    }
	
    public function ajax(){
		$page	= ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
		$rows	= ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
		
		$hasil = array();
		/*===========rows*page tidak boleh melebihi dari jumlah data======= */
		
		/*=================================post dari find di kiri====================================================*/
		$param 				= $this->input->post('param');
		$Number				= isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : ''; 
		$Desc				= isset($param['txt_Description']) ? $param['txt_Description'] : ''; 
		
		$DateFrom			= isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
		$DateTo				= isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
		$TransStatus		= isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
		$BranchCode			= isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
		$DODirect			= isset($param['chk_DO_Direct']) ? $param['chk_DO_Direct'] : '';
		
		$cmb_CustomerCode	= isset($param['cmb_CustomerCode']) ? $param['cmb_CustomerCode'] : '';
		
		/*============================================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('DOrdNumber', $Number);} 
		if($Desc != ""){$this->db->like('DOrdDesc', $Desc);}
		if($cmb_CustomerCode != ""){$this->db->where('CustomerCode', $cmb_CustomerCode);} 
		
		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_deliveryorder.DOrdDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_deliveryorder.DOrdDate <=', date("Y-m-d", strtotime($DateTo))); 
			}
        }
		/*==========================end=================================================================*/
		
		$count_data = $this->db->count_all_results('at_deliveryorder');
		
		$offset 	= $count_data - ($rows * $page);
		if($offset > 0){
			$rows = $rows;
		}
		else{
			$rows = $count_data - ($rows*($page-1));
		}
		/*========================end=======================================*/
		$result = $this->m_delivery_order->get_all(); 
		
		for($i=0; $i<=($rows-1); $i++){
			// kalau master ambil dari get_status_master(), kalau transaksi get_status()
			$TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(
				'BranchName' 	=>	$result[$i]->BranchName,
				'CustomerName' 	=>	$result[$i]->CustomerName,
				'TransNumber' 	=>	$result[$i]->DOrdNumber,
				'DOrdDate' 		=>	$result[$i]->DOrdDate,
				'SOrdNumber' 	=>	$result[$i]->SOrdNumber,
				'CustPONumber' 	=>	$result[$i]->CustPONumber,
				'DOrdDesc' 		=>	$result[$i]->DOrdDesc,
				'TransStatus' 	=>	$TransStatus,
				'CreatedBy' 	=>	$result[$i]->EmployeeName
			);
		}
		
		if(empty($hasil)){
			$emptyVar = array();
			echo json_encode($emptyVar);
		}
		else{
			$result = array();
			$result['total'] = $count_data;
			$result['rows'] = $hasil;
			echo json_encode($result);
		}
    }

    public function ajax_item(){
        $id = $this->input->post('so_number');
		
        if(!empty($id)){
            echo json_encode($this->m_sales_order->get_detail_item_for_do($id));
        }
        else{
            echo '[]';
        }
		//echo $this->db->last_query();
    }        
        
    public function ajax_detail(){
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $param	= explode('.', str_replace($data['menu_link'].'/ajax_detail/',"",$this->uri->uri_string()));
		$id		= $param[0];
		$branch	= $param[1];
		
        $result = $this->m_delivery_order->get_detail_item($id, $branch);
        foreach($result as $row) {
			if($row->ItemStatus == 0){
				$Average = $row->ItemPriceCogs;
			}
			else{
				$Average = 0;
			}
		
			$hasil[] = array(
				'RowStatus'			=> 1,
				'DOrdDetailID' 		=> $row->DOrdDetailID,
				'SOrdDetailID' 		=> $row->SOrdDetailID,
				'SOrdNumber' 		=> $row->SOrdNumber,
				
				'DOrdNumber' 		=> $row->DOrdNumber,
				'ItemCategoryID'	=> $row->ItemCategoryID, 
				'ItemCategoryCode'	=> $row->ItemCategoryCode, 
				'ItemDesc' 			=> $row->ItemDesc,
				'ItemCode' 			=> $row->ItemCode,
				'ItemQty' 			=> $row->ItemQty,
				'ItemQtySpd' 		=> $row->ItemQtySpd, 
				'LastQtyDO'			=> $row->ItemQty, 
				'ItemQtyDO'			=> $row->ItemQtyDO, 
				'ItemPrice'			=> $row->ItemPrice, 
				'ItemAverage'		=> $Average,
				'TotalAmount'		=> $row->ItemAmount,
				'ItemUnit' 			=> $row->ItemUnit,
				'ItemTax' 			=> $row->ItemTax,
				'Item_pph23' 		=> $row->ItemPPH23,
				'ItemStatus' 		=> $row->ItemStatus,
				'ItemDiscPcnt' 		=> $row->ItemDiscPcnt,
				'max_item'			=> $row->ItemMax,
				'ItemQtySO'			=> $row->ItemQtySO,
				'SalesmanCode' 		=> $row->SalesmanCode
			); 
		}
		
		echo json_encode($hasil);
	}
	
    function get_data_so(){
        $CustomerCode = $this->input->post('cust_code');
        
        if(!empty($CustomerCode)){
           echo json_encode($this->m_sales_order->get_so_for_do($CustomerCode));
        }
        else{
            echo '[]';
        }
    }
	
	public function trans_rollback($modus, $AccounName, $Currency) {
        $this->db->trans_rollback();
        $result['status']   = false;

        if($modus == 'approval'){
            $result['message']  = get_notification($modus, 0);
        }
        else{
             $result['message']  = get_notification_preference($modus, 0, $AccounName, $Currency);               
        }
                
        echo json_encode($result);
        die();
    }
	
	public function set_print_status(){
		$this->m_delivery_order->set_print_status();
	}
	
	function update_print(){
		$NoDeliveryOrder = $this->input->post('no_do');		
		
		$data = array (
			'PrintStatus' 		=> 1,
			'LastUser'			=> $this->session->userdata('username')
		);
		
		$this->transaction['update_group']['data']= $data;
		$this->transaction['update_group']['DOrdNumber'] = $NoDeliveryOrder;
		
		$result_insert = $this->m_delivery_order->update_print_transaction($this->transaction);
		$this->transaction 	= [];
			
		if ($result_insert == 0) {
			$result['status'] 		= FALSE;
		}
		else {
			$result['status'] 		= TRUE;
		}
		echo json_encode($result);
	}

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

		$DOrdNumber			= str_replace($data['menu_link'].'/get_detail_deiveryordervariant/',"",$this->uri->uri_string());
		$list_detail = $this->m_delivery_order->m_get_detail_deliveryordervariant($DOrdNumber);
		echo json_encode($list_detail);
	}

	function insert_other(){
		$txt_do_no			= $this->input->post('txt_do_no');
		$BranchCode 		= $this->m_delivery_order->get_BranchCodeDO($txt_do_no);
		$txt_do_date		= $this->input->post('txt_do_date');
		$detail				= json_decode($this->input->post('detail'));

		foreach($detail as $row){
			$data_variant = array("VrNumber" 	=> $txt_do_no,
								 "BranchCode" 	=> $BranchCode,
								 "VrDate" 		=> date("Y-m-d"),
								 "VrNumber" 	=> $txt_do_no,
								 "ItemCode" 	=> $row->ItemCode,
								 "VrDesc" 		=> $row->Variant,
								 "ItemQty" 		=> $row->QTY,
								 "CreatedBy" 	=> $this->session->userdata('username'),
								 "CreatedAt" 	=> date("Y-m-d"),
								 "LastUser"		=> $this->session->userdata('username'));

			$this->trans_data['insert_variant']['data'][] = $data_variant;
		}

		$result_return = $this->m_delivery_order->insert_variant($this->trans_data);

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification('insert', 1);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('insert', 0);
        }

        echo json_encode($result);

	}
}