<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Agus / 08-08-2014	
 *	Revisi 	: Ferry / 20-02-2015
 *	Revisi 	: Fachri / 25-05-2015
 */
 
class Sales_order extends CI_Controller {
    public $menu_id     = 160;

    public $app1        = array("MGR","SPV");
    public $app2        = array("DIR");
    public $app_level   = array("DIR","MGR","SPV");
	public $jobtitle_status = array('0', '1');
	
    public $code        	= "Sales Order Number";
    public $name        	= "Sales Order";
	public $transaction 	= [];
	
    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('setup/m_preference');	

		$this->load->model('m_customer');
		$this->load->model('m_taxes');
		$this->load->model('m_items');
		$this->load->model('m_sales_invoice');
		$this->load->model('m_sales_order');
		$this->load->model('m_sales_quotation');
		$this->load->model('m_sales_receipt');
		$this->load->model('m_delivery_order');
		$this->load->model('m_sales_journal');
		
		$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();
            }
        }
	}
	
    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/sales_order/v_salesorder', $data);	
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
    //Function Form Edit
    public function add($SQuoNumber='',$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['SQuoNumber'] 	= $SQuoNumber;
					$data['CustomerCode'] 	= $CustomerCode;

					$data['so_date']    = date('d-m-Y');
					// 
					$data['taxes_ppn10']	= $this->m_taxes->get_by_code('PPN');
					
					//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/sales_order/v_new_salesorder', $data);
					$this->load->view('v_footer');
					//----------------------end--------------------------------------------------------		
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
    //Function Form Insert
    public function insert() {
		try{
			$result_insert = 0;
			
			// Defines sales order varibles
			$cmb_customer		= $this->input->post('cmb_customer');
			$txa_address		= $this->input->post('txa_address');
			$cmb_ship_via		= $this->input->post('cmb_ship_via');
			$txa_ship_to		= $this->input->post('txa_ship_to');
			$txt_ship_date		= $this->input->post('txt_ship_date');
			$currency_code		= $this->input->post('hdn_currency_code');
			$currency_rate		= $this->input->post('txt_rate');
			$cmb_fob			= $this->input->post('cmb_fob');
			$txt_so_date		= $this->input->post('txt_so_date');
			
			/*=====================================jcos number==========================================*/
			$txt_so_no  		= $this->m_sales_order->create_so_number($txt_so_date);
			/*==========================================================================================*/
			
			$txt_sq_no			= $this->input->post('txt_sq_no');
			$txt_sq_date		= $this->input->post('txt_sq_date');
			$txt_po_no			= $this->input->post('txt_po_no');
			$txa_description	= $this->input->post('txa_description');
			$cmb_terms			= $this->input->post('cmb_terms');
			$chk_dpstatus		= $this->input->post('chk_payment_dp')?$this->input->post('chk_payment_dp'):0;
			$txt_downpayment	= $this->input->post('txt_downpayment');
			$discount			= $this->input->post('txt_discount');
			$ppn_val			= $this->input->post('ppn');
			$txt_pph23_hide		= $this->input->post('txt_pph23_hide');
			$ppn_pcnt			= $this->input->post('txt_ppn_rate');
			$est_freight		= $this->input->post('txt_freight');
			$sub_total			= $this->input->post('sub_total');
			$total_purchase		= $this->input->post('total_purchase');
			$taxes_status		= $this->input->post('chk_taxtable')?$this->input->post('chk_taxtable'):0;
			$intax_status		= $this->input->post('chk_inclusive')?$this->input->post('chk_inclusive'):0;

			$hdn_pph23_pcnt = $this->input->post('hdn_pph23_pcnt');
			
			$detail_post		= $this->input->post('detail');
			$detail				= json_decode($detail_post);
			
			$sub_total_hide		 		= $this->input->post('sub_total_hide');
			$total_purchase_hide 		= $this->input->post('total_purchase_hide');
			$ppn_val_hide		  		= $this->input->post('ppn_hide');
			$TotalAmountReceipt_Fiscal 	= 0;
			/*======================menghituung total grid di table==============================================================*/
			if(count($detail) > 0) {
				
				foreach($detail as $row_check){
					
					$ItemQtySO 	= 0;
					$ItemQtySQ 	= 0;
					$TotalQtySO = 0;
					
					$check_qty_from_sod_detail = $this->m_sales_quotation->get_detail_sum_squo($row_check->SQuoNumber, $row_check->ItemCode);
					
					$ItemQtySO 	= $check_qty_from_sod_detail->ItemQtySO;//Qty Suspend sudah ditambahkan di model
					$ItemQtySQ 	= $check_qty_from_sod_detail->ItemQtySQ;
					$TotalQtySO = $row_check->ItemQty + $ItemQtySO;
					
					if($TotalQtySO > $ItemQtySQ){
						throw new Exception("Transaksi gagal, Item Qty Sales Order melebihi Item Qty Sales Quotation, Untuk Item ".$row_check->ItemDesc.", Qty SO : ".$TotalQtySO.", Qty SQ : ".$ItemQtySQ."");
					}
				}
				
				/*========================================Check for Over Limit====================================================*/
				$cust_balance				= $this->m_customer->get_saldo_balance($cmb_customer);
				$OverLimit = $this->new_sales_order_limit($cmb_customer, $cust_balance->SalesLimit, $total_purchase_hide, $txt_so_no);
				if($OverLimit > 0){
					$TransStatus = 7;
				}
				else{
					$TransStatus = 4;
				}
				/*
					End Function Over Limit
				*/
				
				$data = array (
					'BranchCode'		=> $this->session->userdata('branch'),
					'CustomerCode' 		=> $cmb_customer,
					'SOrdDate'			=> date("Y-m-d", strtotime($txt_so_date)),	
					'SOrdNumber'		=> $txt_so_no,
					'SQuoDate'			=> date("Y-m-d", strtotime($txt_sq_date)),
					'SQuoNumber'		=> $txt_sq_no,
					'CustPONumber'		=> $txt_po_no,
					'CustPODate'		=> $this->m_sales_quotation->get_po_date($txt_po_no),
					'BillingAddress'	=> $txa_address,
					'ShippingAddress'	=> $txa_ship_to,
					'ShipingDate'		=> date("Y-m-d", strtotime($txt_ship_date)),	
					'SOrdDesc'			=> $txa_description,
					'FOBID'				=> $cmb_fob,

					'ShipmentID'		=> $cmb_ship_via,
					'TermsPaymentID'	=> $cmb_terms,
					'CurrencyCode'		=> $currency_code,
					'CurrencyRate'		=> $currency_rate,
					'SOrdSubTotal'		=> $sub_total_hide,
					'SOrdDiscount'		=> $discount,
					'SOrdTaxPcnt'		=> $ppn_pcnt,
					'SOrdTaxes'			=> $ppn_val_hide,
					'SOrdEstFreight'	=> $est_freight,
					'SOrdTotalAmount'	=> $total_purchase_hide,
					'SOrdTaxesStatus'	=> $taxes_status,
					'SOrdInTaxStatus'	=> $intax_status,
					'SOrdDPStatus'		=> $chk_dpstatus,
					'SOrdTotalDP'		=> $chk_dpstatus == 0 ? 0 : $txt_downpayment,
					'SRecTotalDP'		=> 0,
					'OverDueDays'		=> 0,
					'SOrdPPh23' 		=> $txt_pph23_hide,
					//'TransStatus'		=> $TransStatus,
					'TransStatus'		=> 4,
					'SOrdPPh23Pcnt' 	=> $hdn_pph23_pcnt,
					'CreatedBy' 		=> $this->session->userdata("username"),
					'CreatedAt' 		=> date('Y-m-d'),
					'LastUser'			=> $this->session->userdata("username")
				);
				
				//1. Insert Sales Order data.
				$this->transaction['insert_group']['data'] = $data;
				
				foreach($detail as $row) {
					if($row->ItemTax > 0){
						$ItemTaxStatus = 1;
					}
					else{
						$ItemTaxStatus = 0;
					}
					
					$detail_data = array(
						'SQuoDetailID'		=> $row->SQuoDetailID,
						'SQuoNumber'		=> $row->SQuoNumber,
						'SOrdNumber'		=> $txt_so_no,
						'ItemCode'			=> $row->ItemCode,
						'ItemDesc'			=> $row->ItemDesc,
						'itemUnit'			=> $row->ItemUnit,
						'itemQty'			=> $row->ItemQty,
						'ItemQtyDO'			=> 0,
						'ItemPrice'			=> doubleval($row->ItemPrice_Hide),
						'ItemDiscPcnt' 		=> $row->ItemDisc,
						'ItemAmount'		=> doubleval($row->ItemAmount_Hide),
						'ItemTaxStatus'		=> $ItemTaxStatus,
						'ItemTaxPPNOut'		=> doubleval($row->ItemTax),
						'ItemTotalAmount'	=> doubleval($row->ItemAmount_Hide+$row->ItemTax),
						'SalesmanCode'		=> $row->SalesmanCode,
						'ItemCategoryID'	=> $row->ItemCategoryID,
						'ItemCategoryCode' 	=> $row->ItemCategoryCode,
						'ItemType' 			=> $row->ItemStatus,
						'ItemTaxPPh23' 		=> $row->Item_PPh23,
						'LastUser'			=> $this->session->userdata("username")				
					);    
					
					//2. Insert Sales Order detail data.
					$this->transaction['insert_detail']['data'][] = $detail_data;
					
					//Edit Quantity pada Salaes Quotation
					$curr_qty_so    = $this->m_sales_quotation->get_qty_so($row->SQuoDetailID);
					$item_qty_so 	= doubleval($curr_qty_so + $row->ItemQty); //qty SO lama di SQ  + qty baru di SO
					
					$squo_detail = array(
						'ItemQtySO'     => $item_qty_so,
						'LastUser'      => $this->session->userdata("username")				
					);
					
					//3. Update QtySO pada Sales Quotation
					$this->transaction['update_sq']['data'][] 			= $squo_detail;
					$this->transaction['update_sq']['SQuoDetailID'][] 	= $row->SQuoDetailID;
				}
				
				$result_transaction = $this->m_sales_order->insert_transaction_all($this->transaction);
				$this->transaction 	= [];
				/*=============================trans roll back dan trans commit============================/*/
				if ($result_transaction == 0) {
					$result['status'] 	= FALSE;
					$result['message']  = get_notification_transaksi($this->name, 'insert', 0, $txt_so_no);
				}
				else {
					$result['status'] 	= TRUE;
					$result['message']  = get_notification_transaksi($this->name, 'insert', 1, $txt_so_no);
				}
				echo json_encode($result);
				/*==================================end======================================================*/
			}
			else{
				throw new Exception("Sales Order gagal disimpan. Tidak ada item pada Sales Order.");
			}
			/*=========================================end==================================================================================== */
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            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{
					/*
						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;
					//$data['menu_model'] = $this->menu_model;
					date_default_timezone_set("Asia/Bangkok");
					// 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);
					
					// inisialisasi additional parameter
					$id                     = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
					$data['detail']         = $this->m_sales_order->get_detail($id);
					$data['taxes_ppn10']	= $this->m_taxes->get_by_code('PPN');
					// Change date format to dd-mm-yyyy
					$squo_datetemp          = explode(",", $data["detail"]->SQuoDate);
					
					foreach($squo_datetemp as $row=>$result){
						$squo_datetemp[$row] = date("d-m-Y", strtotime($result));
					}        
					
					$data["detail"]->SQuoDate = implode(",", $squo_datetemp);
					$cust_balance				= $this->m_customer->get_saldo_balance($data["detail"]->CustomerCode);
					
					$OverLimit = $this->new_sales_order_limit($data["detail"]->CustomerCode, $cust_balance->SalesLimit, $data["detail"]->SOrdTotalAmount, $data["detail"]->SOrdNumber);
					$over_limit		= $OverLimit * $data['detail']->CurrencyRate;
					$approval_limit = $this->m_preference->get_jobtitle_by_limit($over_limit);
					
					if($data["detail"]->TransStatus == 7){
						if($OverLimit > 0){
							if($approval_limit == false){
								$data["app_over_limit"] = false;
								$data['app_over_limit_by'] = '';
							}
							else{
								$data["app_over_limit"] = true;
								$data['app_over_limit_by']	= $approval_limit[0]->JobTitleCode;
							}
						}
						else{
							$data["app_over_limit"] = false;
							$data["app_over_limit_by"] = '';
						}
					}
					else{
						$data["app_over_limit"] = false;
						$data["app_over_limit_by"] = '';
					}
					
					//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/sales_order/v_edit_salesorder', $data);
						$this->load->view('v_footer');
					}
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function update(){
		try{
			/*=======================deklar variabel=============================*/
			$cmb_customer		= $this->input->post('cmb_customer');
			$txa_address		= $this->input->post('txa_address');
			$cmb_ship_via		= $this->input->post('cmb_ship_via');
			$txa_ship_to		= $this->input->post('txa_ship_to');
			$txt_ship_date		= $this->input->post('txt_ship_date');
			$currency_code		= $this->input->post('txt_currency_code');
			$currency_rate		= $this->input->post('txt_rate');
			$cmb_fob			= $this->input->post('cmb_fob');
			$txt_so_no			= $this->input->post('txt_so_no');
			$txt_so_date		= $this->input->post('txt_so_date');
			$txt_sq_no			= $this->input->post('txt_sq_no');
			$txt_sq_date		= $this->input->post('txt_sq_date');
			$txt_po_no			= $this->input->post('txt_po_no');
			$txa_description	= $this->input->post('txa_description');
			$cmb_terms			= $this->input->post('cmb_terms');
			$chk_dpstatus		= $this->input->post('chk_payment_dp');
			$txt_downpayment	= $this->input->post('txt_downpayment');
			$discount			= $this->input->post('txt_discount');
			$ppn_val			= $this->input->post('ppn');
			$ppn_pcnt			= $ppn_val == 0 ? 0 : 10;
			$pph22				= $this->input->post('txt_pph22');
			$pph23				= $this->input->post('txt_pph23');
			$txt_pph23_hide		= $this->input->post('txt_pph23_hide');

			$est_freight		= $this->input->post('txt_freight');
			$sub_total			= $this->input->post('sub_total');
			$total_purchase		= $this->input->post('total_purchase');
			$taxes_status		= $this->input->post('chk_taxtable');
			$intax_status		= $this->input->post('chk_inclusive');
			$hdn_pph23_pcnt = $this->input->post('hdn_pph23_pcnt');
			
			$total_purchase_hide = $this->input->post('total_purchase_hide');
			$ppn_val_hide		 = $this->input->post('ppn_hide');
			$sub_total_hide		 = $this->input->post('sub_total_hide');
			$currency_code		= $this->input->post('hdn_currency_code');
			$currency_rate		= $this->input->post('txt_rate');
			/*======================end==============================================*/
			
			$ppn_pcnt			= $this->input->post('txt_ppn_rate');
			$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);
			
			if(count($detail) > 0) {
				foreach($detail as $row_check){
					
					$ItemQtySO 	= 0;
					$ItemQtySQ 	= 0;
					$TotalQtySO = 0;
					
					$check_qty_from_sod_detail = $this->m_sales_quotation->get_detail_sum_squo($row_check->SQuoNumber, $row_check->ItemCode);
					
					$ItemQtySO 	= $check_qty_from_sod_detail->ItemQtySO;
					$ItemQtySQ 	= $check_qty_from_sod_detail->ItemQtySQ;
					$TotalQtySO = ($row_check->ItemQty - $ItemQtySO) + ($ItemQtySO + $check_qty_from_sod_detail->ItemQtySpd);
					
					
					if($TotalQtySO > $ItemQtySQ){
						throw new Exception("Transaksi gagal, Item Qty Sales Order melebihi Item Qty Sales Quotation, Untuk Item ".$row_check->ItemDesc.", Qty SO : ".$TotalQtySO.", Qty SQ : ".$ItemQtySQ."");
					}
				}
				
				$result_edit  	= 0;
				$AppLimitStatus = $this->m_sales_order->check_approval_limit($txt_so_no);
				
				if($AppLimitStatus==false){
					/*========================================Check for Over Limit====================================================*/
					$cust_balance				= $this->m_customer->get_saldo_balance($cmb_customer);
					$OverLimit = $this->new_sales_order_limit($cmb_customer, $cust_balance->SalesLimit, $total_purchase_hide, $txt_so_no);
					if($OverLimit > 0){
						$TransStatus = 7;
					}
					else{
						$TransStatus = 4;
					}
					/*
						End Function Over Limit
					*/
				}
				else{
					/*
						ambil trans status yang asli jika transaksi AppLimitStatus = 1
					*/
					$TransStatus 		= $this->m_sales_order->get_so_status($SOrdNumber);
					/*======================end======================================*/
				}
	
				/*=============================update sales order group=================================================*/
				$data = array (
					'CustPONumber'		=> $txt_po_no,
					'ShippingAddress'	=> $txa_ship_to,
					'ShipingDate'		=> date("Y-m-d", strtotime($txt_ship_date)),	
					'SOrdDesc'			=> $txa_description,
					'FOBID'				=> $cmb_fob,
					'ShipmentID'		=> $cmb_ship_via,
					'TermsPaymentID'	=> $cmb_terms,
					'CurrencyRate'		=> $currency_rate,
					'SOrdSubTotal'		=> $sub_total_hide,
					'SOrdDiscount'		=> $discount,
					'SOrdTaxPcnt'		=> $ppn_pcnt,
					'SOrdTaxes'			=> $ppn_val_hide,
					'SOrdEstFreight'	=> $est_freight,
					'SOrdTotalAmount'	=> $total_purchase_hide,
					'SOrdTaxesStatus'	=> $taxes_status,
					'SOrdInTaxStatus'	=> $intax_status,
					'SOrdDPStatus'		=> $chk_dpstatus,
					'SOrdTaxPcnt' 		=> $ppn_pcnt,
					'SOrdTotalDP'		=> $chk_dpstatus == 0 ? 0 : $txt_downpayment,
					'SRecTotalDP'		=> 0,
					'SOrdPPh23Pcnt' 	=> $hdn_pph23_pcnt,
					//'OverDueDays'		=> $over_due_days,
					'TransStatus'		=> $TransStatus,
					'SOrdPPh23' 		=> $txt_pph23_hide,
					'LastUser'			=> $this->session->userdata("username")
				);
				$this->transaction['update_group']['data'] 			= $data;
				$this->transaction['update_group']['SOrdNumber'] 	= $txt_so_no;
			
				/*=================end====================================================================*/
				
				/*
					detail dari grid 
					update hanya qty,price, amount, ppn out, disc
					update qty sq jika ada qty di so dirubah
				*/
				foreach($detail as $row) {
					if($row->RowStatus==1){
						$detail_data = array(
							'ItemQty'		=> $row->ItemQty,
							'ItemPrice'		=> $row->ItemPrice_Hide,
							'ItemAmount'	=> $row->ItemAmount_Hide,
							'ItemTaxPPNOut'	=> $row->ItemTax,
							'ItemTaxPPh23' 	=> $row->Item_PPh23,
							'ItemTotalAmount' => ($row->ItemAmount_Hide + $row->ItemTax),
							'ItemDiscPcnt' 	=> $row->ItemDisc,
							'LastUser'		=> $this->session->userdata("username")				
						);    
						
						//2. Update Sales Order detail data.
						$this->transaction['update_detail']['data'][] 			= $detail_data;
						$this->transaction['update_detail']['SOrdDetailID'][] 	= $row->SOrdDetailID;
					}
					
					//3. Update Squo Detail -> Item Qauntity SO
					$preqdetail     = $this->m_sales_quotation->get_detail_item_by_id($row->SQuoDetailID);
					$TotalNewQty_SO = doubleval($preqdetail->ItemQtySO - $row->TempQty) + doubleval($row->ItemQty);
						$detail_data_sq = array(
							'ItemQtySO' 	=> $TotalNewQty_SO,				
							'LastUser' 		=> $this->session->userdata("username")					
						 );	
						 $this->transaction['update_sq']['data'][] 			= $detail_data_sq;
						 $this->transaction['update_sq']['SQuoDetailID'][] 	= $row->SQuoDetailID;
					//-------------------------------------------------------------------------------------------------------//
				}
				
				/*===========================delete detail=================================================================*/
				$this->transaction['delete_detail']['total'] = count($detail_id);
				if(count($detail_id)>0){
					foreach ($detail_id as $SOrdDetailID) {
						$this->transaction['delete_detail']['SOrdDetailID'][] = $SOrdDetailID;
						
						//ganti no sq dan sq date di so
						$get_squodetail = $this->m_sales_order->get_detail_cek_sreq($txt_so_no);
						$new_squo_no    = '';
						$new_squo_date  = '';
						$new_cust_po  	= '';
						
						foreach($get_squodetail as $row) {
							$new_squo_no    = $new_squo_no . $row->SQuoNumber . ', ';
							$new_squo_date  = $new_squo_date . $row->SQuoDate . ', ';
							$new_cust_po  	= $new_cust_po . $row->CustPONumber . ', ';
						}
						
						if($new_squo_no != ''){
							$new_squo_no = substr($new_squo_no, 0, (intval(strlen($new_squo_no)) - 2));
						}
						if($new_squo_date != ''){
							$new_squo_date = substr($new_squo_date, 0, (intval(strlen($new_squo_date)) - 2));
						}
						if($new_cust_po != ''){
							$new_cust_po = substr($new_cust_po, 0, (intval(strlen($new_cust_po)) - 2));
						}
							
						$data_so = array(
							'SQuoNumber'    => $new_squo_no,
							'SQuoDate'      => $new_squo_date,
							'CustPONumber'  => $new_cust_po,
							'LastUser'      => $this->session->userdata("username")					
						);
						
						$this->transaction['update_so']['data'][] 			= $data_so;
						$this->transaction['update_so']['SOrdNumber'][] 	= $txt_so_no;
							
						//$this->m_sales_order->update($data_so, $txt_so_no);
					}
					
					for($x = 0; $x < count($detail_qty['a']); $x++) {
						$curr_qty_so    = $this->m_sales_quotation->get_detail_item_by_id($detail_qty['a'][$x]);
						$new_qty_so     = $curr_qty_so->ItemQtySO - $detail_qty['b'][$x];
						
						$squo_detail = array(
							'ItemQtySO'	=> $new_qty_so,
							'LastUser'	=> $this->session->userdata("username")				
						);
						
						//1. Update QtySO pada Sales Quotation
						$this->transaction['update_transaction_sq']['data'][] 			= $squo_detail;
						$this->transaction['update_transaction_sq']['SQuoDetailID'][] 	= $detail_qty['a'][$x];
						
						//$this->m_sales_quotation->update_detail($squo_detail, $detail_qty['a'][$x]);
					}
				}
				/*=============================end==========================================================================*/
				$result_update = $this->m_sales_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_so_no);
			}
			else {
				$result['status'] 	= TRUE;
				$result['message']  = get_notification_transaksi($this->name, 'update', 1, $txt_so_no);
			}
			echo json_encode($result);
			/*==================================end======================================================*/	
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function suspend_data() {
        try{
			$SOrd_number		= str_replace(".", "/", $this->input->post('id'));
			$data				= $this->m_sales_order->get_detail($SOrd_number);
			$SQuo_number		= explode(",", $data->SQuoNumber);
			$arr_transstatus 	= array();
			$arr_transstatus 	= array();
			
			if($data->TransStatus == 0 || $data->TransStatus == 4 || $data->TransStatus == 7){
			 
				$data_so = array (			
					'TransStatus'   => 3,
					'LastUser'      => $this->session->userdata("username")
				);
				
				//1. Update Sales Order TransStatus
				$this->transaction['update_group']['data'] 			= $data_so;
				$this->transaction['update_group']['SOrd_number'] 	= $SOrd_number;
				
				//2. Update Item Qty Sales Quotation
				$data_detail = $this->m_sales_order->get_detail_item($SOrd_number);
	
				foreach($data_detail as $row){
					$detail_sq      = $this->m_sales_quotation->get_detail_item_by_id($row->SQuoDetailID);
	
					$newitem_qtyso  = doubleval($detail_sq->ItemQtySO) - doubleval($row->ItemQty);
					$detail_qtyso   = array(
						'ItemQtySO' 	=> $newitem_qtyso
					);
					
					$this->transaction['update_detail']['data'][] 			= $detail_qtyso;
					$this->transaction['update_detail']['SQuoDetailID'][] 	= $row->SQuoDetailID;
				}
				
				$result_suspend_data 	= $this->m_sales_order->suspend_trasaction($this->transaction);
				$this->transaction 		= [];
				/*=============================trans roll back dan trans commit============================/*/
				if ($result_suspend_data == 0) {
					$result['status'] 	= FALSE;
					$result['message']  = get_notification('cancel', 0);
				}
				else {
					$result['status'] 	= TRUE;
					$result['message']  = get_notification('cancel', 1);
				}
				echo json_encode($result);
				/*==================================end======================================================*/	
			}
			else {
				throw new Exception(get_notification('cancel', 0));
			}
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
	
	/*================================delete item===========================================================================*/
    public function delete() {
        $id             = $this->input->post('id');
        $TransStatus    = $this->m_sales_order->get_transstatus($id);
		
        $this->db->trans_begin();
        $i = 1;
		
        $detail = $this->m_sales_order->get_detail_item($id);
		
        foreach($detail as $row) {
            if($TransStatus == 7) {
                $rec_total_dp = $this->m_sales_order->get_rec_total_dp($id);
                $downpayment = $this->m_sales_order->get_downpayment($id);
								
                if($rec_total_dp == 0) {
                    $result['status'] = true;
                    $result['message'] = get_notification_transaksi($this->name, 'delete', 0);
					
                    if($i == 1) {
                        $this->m_sales_order->set_trans_status($id, 3);	
                    }
					
                    if($this->m_items->check_item_service($row->ItemCode) != 4) {
                        $reset_item = 0;
                        $item_qty_so = $this->m_sales_quotation->get_qty_so($row->SQuoDetailID);
                        $reset_item = intval($item_qty_so) - intval($row->ItemQty);	
                        $this->m_sales_quotation->set_qty_so($row->SQuoDetailID, $reset_item);		
                    }
                }
                else if(doubleval($rec_total_dp) < ($downpayment)) {
                    $result['status'] = false;
                    $result['message'] = "Gagal, Proses Pelunasan Down Payment Masih Dalam Proses.";
                }
                else {
                    $result['status'] = false;
                    $result['message'] = "Gagal, Proses Pembayaran Down Payment Sudah Lunas.";
                }
            }
            else {
                $result['status'] = false;
                $result['message'] = get_notification_transaksi($this->name, 'delete', 1);
            }
			
            $i = $i+1;
        }
		
        if($this->db->trans_status() == FALSE) {
            $this->db->trans_rollback();
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'delete', 1);
        }
        else {
            $this->db->trans_commit();
        }			
		
        echo json_encode($result);		
    }
	/*============================end======================================================================*/
	
    public function approval() {
		try{
			$detail_so = json_decode($this->input->post('detail_so'));
			//------------------------------------------------------------------------------------------------------//
			
			$SOrdNumber 	= $this->input->post('SOrdNumber');	
			$SQuoNumber 	= $this->input->post('SQuoNumber');
			$SQuoNumber 	= explode(",", $SQuoNumber);
			$TotalSales 	= $this->input->post('TotalSales'); //sub total + ppn
			$SubTotal 		= $this->input->post('SubTotal');
			$CustomerCode	= $this->input->post('CustomerCode');
			$DownPayment	= $this->input->post('DownPayment');
			$SOrdDate		= $this->input->post('SOrdDate');
			$CurrencyCode	= $this->input->post('CurrencyCode');
			$CurrencyRate	= $this->input->post('CurrencyRate');
			$SOrdDPStatus	= $this->input->post('SOrdDPStatus');
			$trans_status 	= 1;
			
			//--------------------------------------------------------------------------------------------------------//
			
			/*
				get data sales order tabel
			*/
			$data           = $this->m_sales_order->get_group_detail($SOrdNumber);
			/*=========================End==================================*/
			
			//1. Update Purhcase Requisition Status
			/*
				Code from PO
			*/
			$TotalQtySO_On_SO 	= 0;
			$TotalQtySpd_On_SQ 	= 0;
			$get_sq_set_finish 	= 0;
			
			$this->db->trans_begin();
			foreach($SQuoNumber as $key => $value){
				$TotalQtySO_On_SO 	= $this->m_sales_quotation->set_finish($value);
				$TotalQtySpd_On_SQ 	= $this->m_sales_quotation->get_total_qty_sq_spd($value);
				$get_sq_set_finish 	= $this->m_sales_quotation->set_finish_sq($value);
				$get_qty_so 		= $this->m_sales_quotation->get_qty_sales_order($value, $SOrdNumber);
				$total_qty_so 		= ($TotalQtySO_On_SO + $TotalQtySpd_On_SQ) + $get_qty_so->TotalQtySO ;
				
				if(round($total_qty_so, 2) == round($get_sq_set_finish->TotalQtySQ, 2)){
					if ($get_sq_set_finish->TransStatus != 8) {
						$data_sq = array (
							'TransStatus'   => 2,
							'LastUser'      => $this->session->userdata("username")
						);
						$this->m_sales_quotation->update($data_sq,$value);
						
						//$this->transaction['update_sq']['data'][] 			= $data_sq;
						//$this->transaction['update_sq']['SQuoNumber'][] 	= $value;
					}
				}
				else{
					$data_sq = array (
						'TransStatus'   => 1,
						'LastUser'      => $this->session->userdata("username")
					);
					$this->m_sales_quotation->update($data_sq,$value);
					
					//$this->transaction['update_sq']['data'][] 			= $data_sq;
					//$this->transaction['update_sq']['SQuoNumber'][] 	= $value;
				}
			} 
			/*=====================================End=============================================*/
			
			/*
				Downpaymen check
			*/
			if($DownPayment > 0){
				foreach($detail_so as $row){
					@$ItemTypeCategori[$row->ItemCategoryID]    = $row->ItemStatus;                    
					@$ItemCategoryAmount[$row->ItemCategoryID] += $row->ItemAmount;                    
					@$ItemCategoryID[$row->ItemCategoryID]     = $row->ItemCategoryID;                    
					@$ItemCategoryCode[$row->ItemCategoryID]   = $row->ItemCategoryCode;
				}
				
				/*
					deklar variabel total baru untuk insert kedalam group
				*/
				$for_total          = 0;
				$ratio_total        = 0;
				$total_baris        = count(@$ItemCategoryAmount);
				/*==================end===================================*/
					
				foreach(@$ItemCategoryAmount as $key => $value){
					$for_total++;
					
					if (($SOrdDPStatus == 1) && ($data->SOrdTotalDP - $data->SRecTotalDP > 0)){
						$trans_status = 0;                    
					}
					/*
						perhitungan item ratio untuk dp dan ratio total
					*/
					if($for_total == $total_baris){
						$item_ratio = 100 - $ratio_total;
					} 
					else {
						$item_ratio = floor(abs((doubleval($value) / $SubTotal) * 100));
					}
					$ratio_total    = $ratio_total + $item_ratio;
					
					$dp_ratio  		= $DownPayment * ($item_ratio / 100);
					
					/*======================end==========================================*/
					
					//insert tabel sinv recipt(tabel baru)
					$data_si_receipt_dp = array(
						'BranchCode'		=> $this->session->userdata('branch'), 
						'CustomerCode'		=> $CustomerCode, 
						'InvoiceNumber'		=> $SOrdNumber, 
						'InvoiceDate'		=> date('Y-m-d', strtotime($SOrdDate)), 
						'InvoiceCurrCode'	=> $CurrencyCode, 
						'InvoiceCurrRate'	=> $CurrencyRate, 
						'InvoiceFiscalRate'	=> 1,
						'InvoiceAmount'		=> doubleval($dp_ratio), 
						'InvoiceOwing'		=> doubleval($dp_ratio), 
						'InvoiceType'		=> 1,
						'ItemCategoryRatio' => $item_ratio,
						'ItemCategoryID'    => @$ItemCategoryID[$key],
						'ItemCategoryCode'  => @$ItemCategoryCode[$key],
						'ItemType'          => @$ItemTypeCategori[$key],
						'DPStatus' 			=> 1,
						'PPnFiscalStatus' 	=> 0,
						'LastUser'			=> $this->session->userdata('username')
					);
					
					$this->m_sales_order->insert_invoice_receive($data_si_receipt_dp);
					//$this->transaction['insert_receive']['data'][] = $data_si_receipt_dp;
					//end insert tabel sinvrecip	
				}
			}
			
			$data_so = array (
				'TransStatus'       => $trans_status,						
				'AppLevel1Status'   => 1,
				'AppLevel1Code'     => $this->session->userdata("username"),
				'AppLevel1Date'     => date("Y-m-d"),
				'LastUser'          => $this->session->userdata("username")
			);
			
			//2.Update Sales Order for Status only
			$this->m_sales_order->update($data_so,$SOrdNumber);
			
			//$this->transaction['update_group']['data'] 			= $data_so;
			//$this->transaction['update_group']['SOrdNumber'] 	= $SOrdNumber;
				
			//--------------------------------------------------------------------------------------------------------//
			
			//update tempoutstanding di customer
			$get_customer_by_code 	= $this->m_customer->get_TemOutstanding($CustomerCode);
			$total_temp_outstanding = $get_customer_by_code + $SubTotal;
			
			$data_customer = array(
				'TempOutStanding' 	=> $total_temp_outstanding
			);
			$this->m_customer->update($data_customer,$CustomerCode);
			
			//$this->transaction['update_customer']['data'] 			= $data_customer;
			//$this->transaction['update_customer']['CustomerCode'] 	= $CustomerCode;
			//end
			
			//$result_app = $this->m_sales_order->approved_transaction($this->transaction);
			//$this->transaction 	= [];
			/*=============================trans roll back dan trans commit============================/*/
	
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$result['status'] = FALSE;
				$result['message']  = get_notification('approval', 0);
			} else {
				$this->db->trans_commit();
				$result['status'] = TRUE;
				$result['message']  = get_notification('approval', 1);
			}
			/*==================================end======================================================*/	
			echo json_encode($result);	
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function approval_limit() {
		try{
			$sord_number    = $this->input->post('SOrdNumber');
	
			$data = array (				
				'TransStatus'		=> 4,
				'AppLimitStatus'	=> 1,
				'AppLimitCode'		=> $this->session->userdata("username"),
				'AppLimitDate'		=> date("Y-m-d"),	
				'LastUser'			=> $this->session->userdata("username")
			);
			$this->transaction['update_group']['data'] 			= $data;
			$this->transaction['update_group']['SOrdNumber'] 	= $sord_number;
			
			$result_app_limit = $this->m_sales_order->approved_transaction_limit($this->transaction);
			$this->transaction 	= [];
			/*=============================trans roll back dan trans commit============================/*/
			if ($result_app_limit == 0) {
				$result['status'] 	= FALSE;
				$result['message']  = get_notification('approval', 0);
			}
			else {
				$result['status'] 	= TRUE;
				$result['message']  = get_notification('approval', 1);
			}
			/*==================================end======================================================*/	
			echo json_encode($result);
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
    
	function bye_pass_dp(){
		try{
			$detail_so = json_decode($this->input->post('detail_so'));
			//------------------------------------------------------------------------------------------------------//
			
			$SOrdNumber 	= $this->input->post('SOrdNumber');	
			$SQuoNumber 	= $this->input->post('SQuoNumber');
			$SQuoNumber 	= explode(",", $SQuoNumber);
			$TotalSales 	= $this->input->post('TotalSales'); //sub total + ppn
			$SubTotal 		= $this->input->post('SubTotal');
			$CustomerCode	= $this->input->post('CustomerCode');
			$DownPayment	= $this->input->post('DownPayment');
			$SOrdDate		= $this->input->post('SOrdDate');
			$CurrencyCode	= $this->input->post('CurrencyCode');
			$CurrencyRate	= $this->input->post('CurrencyRate');
			$SOrdDPStatus	= $this->input->post('SOrdDPStatus');
			
			$get_delivery_order = $this->m_delivery_order->get_delivery_order($SOrdNumber);
			
			if($get_delivery_order){
				throw new Exception("Transaksi gagal di By Pass, SO dengan No ".$SOrdNumber." mempunyai DO Silahkan Reverse dan Suspen DO");
			}
			
			$trans_status 	= 1;
			$Sum_Downpayment 	= 0;
			$Sum_Owing 			= 0;
			
			$get_sales_receipt = $this->m_sales_receipt->get_sales_receipt_for_dp($SOrdNumber, $CustomerCode);
			
			if($get_sales_receipt == 1){
				throw new Exception(msg_check_bypass_dp('Sales Receipt'));
			}
			
			$get_invoice_receive = $this->m_sales_order->get_invoice_receive($SOrdNumber);
			foreach($get_invoice_receive as $row_invoice){
				$ItemCategoryRatio 	= $row_invoice->ItemCategoryRatio;
				$InvoiceOwing 		= $row_invoice->InvoiceOwing;
				$PaymentTotal 		= $row_invoice->ReceiptAmount + $row_invoice->ReceiptRounded;
				$TotalOwing_New 	= ($row_invoice->ReceiptAmount + $row_invoice->ReceiptRounded + $row_invoice->InvoiceOwing) - $row_invoice->InvoiceAmount;
				
				//insert tabel sinv recipt(tabel baru)
				$data_si_receipt_dp = array(
					'InvoiceAmount'		=> doubleval($PaymentTotal), 
					'InvoiceOwing'		=> doubleval($TotalOwing_New), 
					'LastUser'			=> $this->session->userdata('username')
				);
				
				$this->transaction['update_receive']['data'][] 			= $data_si_receipt_dp;
				$this->transaction['update_receive']['SOrdNumber'][] 	= $SOrdNumber;
				
				$Sum_Downpayment += $PaymentTotal;
			}
			
			$get_sales_receipt = $this->m_sales_receipt->get_sordetail_dp($CustomerCode, $SOrdNumber);
			foreach($get_sales_receipt as $row_dp){
				$Total_owing = $Sum_Downpayment - $row_dp->PaymentAmount;
				
				$data_so_dp = array (
					'StatusDPFor'       => 1,
					'LastUser'          => $this->session->userdata("username")
				);
				
				$this->transaction['update_sordetail_dp']['data'][] 			= $data_so_dp;
				$this->transaction['update_sordetail_dp']['SOrdNumber'][] 	= $SOrdNumber;
				$this->transaction['update_sordetail_dp']['CustomerCode'][] 	= $CustomerCode;
			}
			
			$data_so = array (
				'SOrdTotalDP' 		=> $Sum_Downpayment,
				'TransStatus'       => $trans_status,
				'LastUser'          => $this->session->userdata("username")
			);
			
			//2.Update Sales Order for Status only
			$this->transaction['update_group']['data'] 			= $data_so;
			$this->transaction['update_group']['SOrdNumber'] 	= $SOrdNumber;
			
			$result_byepass = $this->m_sales_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);
        }
	}
	
    //Function preview datari
	public 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['lables']         = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste
	   	$data_filter            = arrayParamInUrlToStr($obj_string);
		$data['branch_code'] = $data_filter['cmb_branch'];
		$data['company_code'] = $data_filter['cmb_company'];
		
        $data['list'] 			= $this->m_sales_order->get_all_print($data_filter);

        $this->load->view('v_header');
        $this->load->view('sales/sales_order/v_preview_salesorder', $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_sales_order->get_all();

        $this->load->view('v_header');
        $this->load->view('sales/sales_order/v_print_salesorder', $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());
	
        if($id!=""){
            $data['detail'] = $this->m_sales_order->get_detail_print($id);
            $data['list'] = $this->m_sales_order->get_detail_item_print($data['detail']->SOrdNumber);		

            $this->load->view('v_header');
            $this->load->view('sales/sales_order/v_print_detail_salesorder', $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());

        if($id!=""){
            $data['detail'] = $this->m_sales_order->get_detail($id);
            $data['list'] = $this->m_sales_order->get_detail_item($data['detail']->SOrdNumber);		
			
            $this->load->view('v_header');
            $this->load->view('sales/sales_order/v_preview_detail_salesorder', $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'] : '';
		$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('SOrdNumber', $Number);} 
		if($Desc != ""){$this->db->like('SOrdDesc', $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_salesorder.SOrdDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_salesorder.SOrdDate <=', date("Y-m-d", strtotime($DateTo))); 
			}
        }
		/*==========================end=================================================================*/
		
		$count_data = $this->db->count_all_results('at_salesorder'); 
		
		/*========================end=======================================*/
		$result = $this->m_sales_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(
				'BranchName' 		=>	$result[$i]->BranchName,
				'CustomerName' 		=>	$result[$i]->CustomerName, 
				'SQuoNumber' 		=>	$result[$i]->SQuoNumber, 
				'TransNumber' 		=>	$result[$i]->SOrdNumber, 
				'SOrdDate' 			=>	$result[$i]->SOrdDate,
				'SOrdTotalAmount' 	=>	$result[$i]->SOrdTotalAmount, 
				'SOrdTotalDP' 		=>	$result[$i]->SOrdTotalDP, 
				'SOrdDesc' 			=>	$result[$i]->SOrdDesc, 
				'CreatedBy' 			=>	$result[$i]->CreatedBy, 
				'TransStatus' 		=>	$TransStatus
			);
		}
		
		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 get_data_sq($CustomerCode=''){
//		$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======= */
//		
//		/*===========str replace customer code==============================*/
//		$SelectedSQuoNumber = $this->input->post('squo_no');
//		if (strpos($SelectedSQuoNumber,',') !== false) {
//			$SelectedSQuoNumber = explode(',', $SelectedSQuoNumber);
//		}
//		
//		if($CustomerCode==''){
//        	$CustomerCode = $this->input->post('cust_code');
//		}
//		else{
//			$CustomerCode = str_replace('_','-',$CustomerCode);
//		}
//		/*=======================end========================================*/
//		
//		/*========================jika kondisi tidak sama dengan kosong di find lakukan proses di if=================*/
//		$this->db->where_in('TransStatus',array(0,1));
//		$this->db->where('BranchCode', $this->session->userdata('branch'));
//		$this->db->where('CustomerCode',$CustomerCode);
//		/*==========================end=================================================================*/
//		$count_data = $this->db->count_all_results('at_salesquotation'); 
//		echo $this->db->last_query();
//		
//		$offset 	= $count_data - ($rows * $page);
//		if($offset > 0){
//			$rows = $rows;
//		}
//		else{
//			$rows = $count_data - ($rows*($page-1));
//		}
//		/*========================end=======================================*/
//		$result = $this->m_sales_quotation->get_sq_by_cust($CustomerCode,$SelectedSQuoNumber);
//		
//		for($i=0; $i<=($rows-1); $i++){
//			
//            $hasil[] = array(
//				'SQuoNumber' 	=>	$result[$i]->SQuoNumber,
//				'SQuoDate' 		=>	$result[$i]->SQuoDate, 
//				'CustPONumber' 	=>	$result[$i]->CustPONumber, 
//				'SQuoDesc' 		=>	$result[$i]->SQuoDesc
//			);
//		}
//		
//		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 get_data_sq($CustomerCode=''){
		$SelectedSQuoNumber = $this->input->post('squo_no');
		if (strpos($SelectedSQuoNumber,',') !== false) {
			$SelectedSQuoNumber = explode(',', $SelectedSQuoNumber);
		}
		
		if($CustomerCode==''){
        	$CustomerCode = $this->input->post('cust_code');
		}
		else{
			$CustomerCode = str_replace('_','-',$CustomerCode);
		}
		
        if(!empty($CustomerCode)){
            echo json_encode($this->m_sales_quotation->get_sq_by_cust($CustomerCode,$SelectedSQuoNumber));
        }
        else{
            echo '[]';
        }
    }	
    
    public function ajax_item() {
        $sq_number 		= $this->input->post('sq_no');
		$CurrencyCode 	= $this->input->post('currency_code');
        $result 		= $this->m_sales_quotation->get_detail_item($sq_number);
		
		foreach($result as $row){
			
			$get_item_price = $this->m_sales_order->get_item_price($row->ItemCode,$row->BranchCode, $CurrencyCode);
			if($row->ItemStatus == 0){
				if(!empty($get_item_price->ItemPrice)){
					$Price 	= $get_item_price->ItemPrice;
					$Amount = $row->ItemQty * $get_item_price->ItemPrice;
				}
				else{
					$Price 	= 0;
					$Amount = 0;
				}
			}
			else{
				$Price 	= 0;
				$Amount = 0;
			}
			
			$hasil[] = array(
				'ItemCode' 			=> $row->ItemCode,
				'ItemDesc' 			=> $row->ItemDesc,
				'ItemQty' 			=> $row->ItemQty,
				'ItemUnit' 			=> $row->ItemUnit,
				'ItemCategoryCode' 	=> $row->ItemCategoryCode,
				'ItemCategoryID' 	=> $row->ItemCategoryID,
				'RequiredDate' 		=> $row->ItemCategoryID,
				'ItemSpdStatus' 	=> $row->ItemSpdStatus,
				'Memo' 				=> $row->Memo,
				'ItemQtySO'			=> $row->ItemQtySO,
				'ItemQtySpd'		=> $row->ItemQtySpd,
				'SQuoDetailID'		=> $row->SQuoDetailID,
				'ItemStatus'		=> $row->ItemStatus,
				'TempQty'			=> $row->TempQty,
				'RowStatus'			=> $row->RowStatus,
				'ItemQtyDO'			=> $row->ItemQtyDO,
				'ItemDisc'			=> $row->ItemDisc,
				'Status'			=> $row->Status,
				'SQuoNumber'		=> $row->SQuoNumber,
				'SQuoDate'			=> $row->SQuoDate,
				'CustPONumber' 		=> $row->CustPONumber,
				'SQuoDesc' 			=> $row->SQuoDesc,
				'ItemAverage'		=> $row->ItemAverage,
				'ItemPrice'			=> $Price,
				'ItemAmount'		=> $Amount,
				'SalesmanCode'		=> $row->SalesmanCode,
				'EmployeeName'		=> $row->EmployeeName, 
				'ItemMax'			=> $row->ItemMax,
				'ItemTax'			=> $row->ItemTax,
				'ItemPrice_Hide'	=> $Price,
				'ItemAmount_Hide'	=> 0
			);
		}
		
		if(!empty($hasil)){
			echo json_encode($hasil);
		}
		else{
			$emptyVar = array();
			echo json_encode($emptyVar);
		}     

//       echo $this->db->last_query(); die();
    }
            
    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_sales_order->get_detail_item($id));
        }
        else{
            echo '[]';
        }
        
//        echo $this->db->last_query(); die();
    }	    
        
    public function ajax_filter(){
        $cust = $this->input->post('cust_code');
		
        if(!empty($cust)){
           echo json_encode($this->m_sales_order->get_by_cust($cust));
        }
        else{
            echo '[]';
        }
    }	

    public function get_sord_number() {
        $sord_date      = $this->input->post('SOrd_Date') == '' ? date('d-m-Y') : $this->input->post('SOrd_Date');
        $sord_number    = $this->m_sales_order->create_sord_number($sord_date);

        $result['status']   = true;
        $result['number']   = $sord_number;
        
        echo json_encode($result);
    }
    
    public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status']   = false;

        if($modus == 'approval'){
            $result['message']  = get_notification($modus, 0);
        }
        else {
            $result['message']  = get_notification_transaksi($this->name, $modus, 0);            
        }
        
        echo json_encode($result);
        die();
    }
	
	 public function suspend_item(){
		try{
			$suspend_all    		 = 1;
			$trans_status   		 = 1;
			
			$so_number    		 	 = $this->input->post('so_number');
			$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_delivery_order->check_item_do_approved_by_sordnumber($so_number);
			
			if($check_approved == false){
				foreach($detail as $row){
					$SOrdDetailID       = $row->SOrdDetailID;
					
					$get_item_qty_on_sr = $this->m_sales_order->get_detail_sum_pord($SOrdDetailID, $row->ItemCode);
					if($row->Status == "Yes"){
						$item_qty_do        = $get_item_qty_on_sr->ItemQtySO - $get_item_qty_on_sr->ItemQtyDO;
					}
					else{
						$item_qty_do        = 0;
					}
					
					$item_qty_suspend   = $item_qty_do;
					
					if($row->RowStatus == 2){
						if($item_qty_suspend == 0){
							if($get_item_qty_on_sr->Item_DO == $get_item_qty_on_sr->ItemQtySO){
								throw new Exception("Item tidak berhasil di Suspend, Qty SO sudah di proses keseluruhan di DO");
							}
						}
						else{
							if(($get_item_qty_on_sr->ItemQtyDO > $get_item_qty_on_sr->ItemQtySO)){
								 throw new Exception("Item tidak berhasil di Suspend, Qty DO melebihi Qty SO silahkan lihat kembali transaksi");
							}
						}
						
						$data = array (
									'ItemQtySpd'        => $item_qty_suspend,
									'ItemSpdStatus'     => $row->Status == 'Yes' ? 1 : 0,
									'LastUser'          => $this->session->userdata("username"),
									'SOrdDetailID' 		=> $SOrdDetailID
								);
	
						//Edit POrdDetail for Suspend Item Status
						$arr_update_qty_suspend[] = $data;
						//-----------------------------------------------------------------------------------------------------//
					}
					
					if (($row->Status == 'No') or ($row->ItemQtyDO > 0)) {
						$suspend_all    = 0;
					}
					
					if(($row->ItemQty-($row->ItemQtyDO+$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){
						$DOrdAppStatus = $this->m_delivery_order->check_do_app_status($so_number);
						
						if($DOrdAppStatus == 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_sales_order->update_group_new($arr_update_qty_suspend,$arr_update_trans_status, $so_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';
				}
				echo json_encode($result);
			}
			else{  
				throw new Exception("Item Suspend tidak berhasil disimpan, karena item belum di Approval pada Delivery Order");    
			}
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
    }
	
	function reverse_data_detail() {
        try {
            $txt_so_no  		= $this->input->post('txt_so_no');
            $result_approve = 0;
			$detail_post		= $this->input->post('detail');
			$detail				= json_decode($detail_post);
			
            /*
              Check Kondisi apakah transaksi ini sudah di buat di RI
             */
            $get_detail_preq = $this->m_custom->check_item_reverse($txt_so_no, 'at_deliveryorder', 'at_dorddetail', 'DOrdNumber', 'SOrdNumber');
			$get_dp_for_reverse = $this->m_custom->check_dp_for_reverse($txt_so_no, 'at_srecdetail','SInvNumber','at_salesreceipt','SrecNumber');
			
            if ($get_detail_preq) {
                throw new Exception(msg_check_po_reverse('Delivery Order'));
            } else if ($get_dp_for_reverse) {
                throw new Exception(msg_check_dp_reverse($txt_so_no, 'Sales Receipts'));
            }
			
			/*
              Rubah status
             */
            $data = array(
                'TransStatus' => 4,
                'AppLevel1Status' => 0,
                'AppLevel1Code' => NULL,
                'AppLevel1Date' => NULL,
				'AppLimitStatus' => 0,
				'AppLimitCode' => NULL,
				'AppLimitDate' => NULL,
                'LastUser' => $this->session->userdata("username")
            );
            $this->transaction['reverse_so']['data'] = $data;
            $this->transaction['reverse_so']['SOrdNumber'] = $txt_so_no;
            /* =========================END========================= */
			
			foreach($detail as $row_detail){
				$data_group_sq = array(
					'TransStatus' => 1,
					'LastUser'      => $this->session->userdata("username")
				);
				
				$this->transaction['update_group']['data'][] 			= $data_group_sq;
				$this->transaction['update_group']['SQuoNumber'][] 		= $row_detail->SQuoNumber;
			}
					
			/* =============================trans roll back dan trans commit============================/ */
            $result_approve = $this->m_sales_order->approved_reverse($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_so_no);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_so_no);
            }
            /* ==================================end====================================================== */
			echo json_encode($result);
            
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }
	
	function new_sales_order_limit($CustomerCode, $SalesLimit, $TOtalSO, $SOrdNumber){		
		/*
			Get Sales Order yg statusnya 0,1,2
		*/
		$get_sum_sales_order 	= $this->m_sales_order->get_sales_order_header($CustomerCode);
		$SOrdTotalAmount 		= empty($get_sales_order_header->SOrdTotalAmount) ? 0 : $get_sales_order_header->SOrdTotalAmount;
		
		/*
			Get So Detail Item Spd status 1,2
		*/
		$get_sum_sales_order_itemspd = $this->m_sales_order->get_sales_order_detail_itemspd($CustomerCode, $SOrdNumber);
		$AmountItemQtySpd				= empty($get_sum_sales_order_itemspd->AmountItemQtySpd) ? 0 : $get_sum_sales_order_itemspd->AmountItemQtySpd;
		
		/*
			Sales Invoice Migrasi
		*/
		$get_sales_invoice_migrasi = $this->m_sales_invoice->get_sales_invoice_on_progres($CustomerCode);
		$AmountInvoiceMigrasi		= empty($get_sales_invoice_migrasi->SInvTotalAmount) ? 0 : $get_sales_invoice_migrasi->SInvTotalAmount;
		/*
			Sales Receipt yang bukan DP
		*/
		$get_receipt_finished = $this->m_sales_receipt->get_sales_receipt_on_finshed($CustomerCode);
		if($get_receipt_finished != FALSE){			
			foreach($get_receipt_finished as $row_sum){
				$SRecTotalAmnt				= empty($row_sum->SRecTotalAmnt) ? 0 : $row_sum->SRecTotalAmnt;
				
				@$Sum_SRecTotalAmnt += $SRecTotalAmnt;
			}
		}
		else{
			@$Sum_SRecTotalAmnt = 0;
		}
		
		/*
			Sales Receipt yang Pembayran Fiscal
		*/
		$get_receipt_finished_fiscal = $this->m_sales_receipt->get_sales_receipt_on_finshed_fiscal_new($CustomerCode);
		if($get_receipt_finished_fiscal != FALSE){			
			foreach($get_receipt_finished_fiscal as $row_sum_fiscal){
				$SInvFiscalRate				= $row_sum_fiscal->SInvFiscalRate;
				$SRecTotalAmnt_Fiscal				= empty($row_sum_fiscal->SRecTotalAmnt) ? 0 : $row_sum_fiscal->SRecTotalAmnt;
				
				@$Sum_SRecTotalAmntFiscal += ($SRecTotalAmnt_Fiscal);
			}
		}
		else{
			@$Sum_SRecTotalAmntFiscal = 0;
		}
		
		/*
			Amount Sales Journal 
		*/
		$get_sales_journal = $this->m_sales_journal->get_sales_journal_amount($CustomerCode);
		if($get_sales_journal != FALSE){
			foreach($get_sales_journal as $row_sales_journal){
				$CurrencyCode = $row_sales_journal->CurrencyCode;
				$CurrencyRate = $row_sales_journal->CurrencyRate;
				$SJrnAmount = $row_sales_journal->SJrnAmount;
				$InvoiceType = $row_sales_journal->InvoiceType;
				
				/*
					0 = Non Fiscal
					1 =  Fiscal
				*/
				
				if($InvoiceType == 0){
					$TOtalAmountJournal = $SJrnAmount;
				}
				else{
					$TOtalAmountJournal = $SJrnAmount / $CurrencyRate;
				}
				@$Sum_TOtaalAmountJournal += $TOtalAmountJournal;
			}
		}
		else{
			@$Sum_TOtaalAmountJournal += 0;
		}
		/*
			Get Sales Order yg statusnya 4 dan App Limit
		*/
		$get_sales_order_header_app_limit 	= $this->m_sales_order->get_sales_order_header_app_limit($CustomerCode, $SOrdNumber);
		$SOrdTotalAmount_Limit 		= empty($get_sales_order_header_app_limit->SOrdTotalAmount) ? 0 : $get_sales_order_header_app_limit->SOrdTotalAmount;
		
		/*
			Check Kondisi dia app Limit atau bukan
			jika transaksi app limit maka SO tidak ditambahkan , tapi jika dia bukan app limit SO ditambahkan
		*/
		$get_sales_order = $this->m_sales_order->get_sales_order_limitstatus($CustomerCode, $SOrdNumber);
		if($get_sales_order == false){
			/*
				Kondisi ini pass add so baru
			*/
			$RealTOtalSO = $TOtalSO;
		}
		else{
			/*Kondisi ini pas edit so*/
			if(($get_sales_order->TransStatus == 4) && ($get_sales_order->AppLimitStatus == 1)){
				$RealTOtalSO = 0;	
			}
			else{
				$RealTOtalSO = $TOtalSO;
			}
		}
		
		$Outstanding = ($SOrdTotalAmount + $SOrdTotalAmount_Limit + $RealTOtalSO - $AmountItemQtySpd + $AmountInvoiceMigrasi) - (($Sum_SRecTotalAmnt + $Sum_SRecTotalAmntFiscal) - $Sum_TOtaalAmountJournal);
		
		$OverLimit = $Outstanding - $SalesLimit;
		//echo $SOrdTotalAmount .'+'. $SOrdTotalAmount_Limit .'+'. $RealTOtalSO .'-'. $AmountItemQtySpd .'+'. $AmountInvoiceMigrasi .'-'. $Sum_SRecTotalAmnt .'+'. $Sum_SRecTotalAmntFiscal .'-'. $SJrnAmount;
		//die();
		/*if(($Outstanding) > $SalesLimit){
			$over_limit 	= doubleval($TotalOutstanding) - doubleval($cust_balance->SalesLimit);
		}
		else{
			$over_limit 	= 0;
		}*/
		return $OverLimit;
	}
	
	function get_sales_limit(){
		$SOrdNumber 				= $this->input->post('SOrdNumber');
		$CustomerCode 				= $this->input->post('customer_code');
		$total_purchase 			= $this->input->post('total_purchase');
		$cust_balance					= $this->m_customer->get_saldo_balance($CustomerCode);
		
		$sales_limit = $this->new_sales_order_limit($CustomerCode, $cust_balance->SalesLimit, $total_purchase, $SOrdNumber);
		$result['limit_customer'] 	= $sales_limit;
		echo json_encode($result);
	}
	
	//function sales_order_limit(){
//		$CustomerCode 				= $this->input->post('customer_code');
//		$SOrdNumber 				= $this->input->post('SOrdNumber');
//		$TotalAmountReceipt_Fiscal 	= 0;
//		/*
//			Customer Balance - DP + SO Amount + Temp Outstanding > Sales Limit
//			
//			yang ada variabel di koding dibawah
//			SaldoBalance = (OutStanding - SaldoDPBalance ) + TempOutStanding
//		*/
//		$get_invoice_on_progres  		= $this->m_sales_invoice->get_sales_invoice_on_progres($CustomerCode);
//		$get_receipt_finished  			= $this->m_sales_receipt->get_sales_receipt_on_finshed($CustomerCode); //get sales receipt yang sudah bayar yg status 2
//		//$get_receipt_finished_fiscal 	= $this->m_sales_receipt->get_sales_receipt_on_finshed_fiscal($CustomerCode);
//		$get_sordetail_dp 		 		= $this->m_sales_order->get_sales_order_detaildp($CustomerCode);//sordetail dp yang belum lunas dan yang dp for 1
//		$get_sales_order_header  		= $this->m_sales_order->get_sales_order_header($CustomerCode);//so total amount transtatus 1,2
//		$get_sales_order_limit  		= $this->m_sales_order->get_sales_order_limit($CustomerCode);//so total amount 4 dan sudah di app limit
//		$get_delivery_order_header 		= $this->m_delivery_order->get_delivery_order_header($CustomerCode);//do total amount transtatus 2 finish
//		$cust_balance					= $this->m_customer->get_saldo_balance($CustomerCode);
//		$get_sales_limit_status  		= $this->m_sales_order->get_sales_order_limitstatus($CustomerCode, $SOrdNumber);
//		$get_sales_order_dp_end_limit  	= $this->m_sales_order->get_sales_order_dp_end_for_limit($CustomerCode);//so total amount transtatus 0 dp dan limit 1
//		
//		/*if($get_receipt_finished_fiscal != false){
//			foreach($get_receipt_finished_fiscal as $row_fiscal){
//				if($row_fiscal->CurrencyCode == 'IDR'){
//					$TotalAmountReceipt_Fiscal += ($row_fiscal->SRecTotalAmnt_Fiscal);
//				}
//				else{
//					$TotalAmountReceipt_Fiscal += ($row_fiscal->SRecTotalAmnt_Fiscal / $row_fiscal->FiscalRate);
//				}
//			}
//		}*/
//			
//		$Outstanding 				= empty($get_invoice_on_progres->SInvTotalAmount) ? 0 : $get_invoice_on_progres->SInvTotalAmount;
//		$TotalDP 					= empty($get_sordetail_dp->TotalDP) ? 0 : $get_sordetail_dp->TotalDP;
//		$SOrdTotalAmount 			= empty($get_sales_order_header->SOrdTotalAmount) ? 0 : $get_sales_order_header->SOrdTotalAmount;
//		$SOrdTotalAmount_Limit 		= empty($get_sales_order_limit->TotalAMoun) ? 0 : $get_sales_order_limit->TotalAMoun;
//		$DOrdTotalAmount 			= empty($get_delivery_order_header->DOrdTotalAmount) ? 0 : $get_delivery_order_header->DOrdTotalAmount;
//		$SOrdAmount_ForDP			= empty($get_sales_order_dp_end_limit->SOrdTotalAmountDP) ? 0 : $get_sales_order_dp_end_limit->SOrdTotalAmountDP;
//		$SRecTotalAmnt				= empty($get_receipt_finished->SRecTotalAmnt) ? 0 : $get_receipt_finished->SRecTotalAmnt;
//		$SRecTotalAmnt				= empty($get_receipt_finished->SRecTotalAmnt) ? 0 : $get_receipt_finished->SRecTotalAmnt;
//		$AmountReceipt_Fiscal		= empty($TotalAmountReceipt_Fiscal) ? 0 : $TotalAmountReceipt_Fiscal;
//					
//		/*
//			Hutang 			= $Outstanding_Invoice - $TotalDP
//			TempOutstanding = doubleval($SOrdTotalAmount - $DOrdTotalAmount)
//		*/
//		
//		if(!empty($get_sales_limit_status->SOrdNumber)){
//			if(($get_sales_limit_status->AppLimitStatus == 0) && ($get_sales_limit_status->AppLevel1Status == 0)){
//				$total_purchase 		= $this->input->post('total_purchase');
//			}
//			else{
//				$total_purchase 		= 0;
//			}
//		}
//		else{
//			$total_purchase 		= $this->input->post('total_purchase');
//		}
//		
//		$TotalOutstanding 			= doubleval(round($Outstanding, 2) - $TotalDP - ($SRecTotalAmnt + $AmountReceipt_Fiscal)) + doubleval(round($SOrdTotalAmount, 2) - round($DOrdTotalAmount, 2))  + doubleval($total_purchase + $SOrdTotalAmount_Limit + $SOrdAmount_ForDP);
//		$TotalOutstanding_Limit 	= $TotalOutstanding -  doubleval($cust_balance->SalesLimit);
//		
//		$result['limit_customer'] 	= $TotalOutstanding_Limit;
//		echo json_encode($result);
//	}
	
	//function sales_order_over_due(){
//		$CustomerCode 			= $this->input->post('customer_code');
//		/*============================================Check for Over Due=================================================*/
//		$over_due				= 0;
//		$over_due_days			= 0;
//		$invoice				= $this->m_sales_invoice->get_invoice_for_check_overdue($CustomerCode);
//		
//		if(count($invoice) > 0){
//			$DueDate			= $invoice[0]->NetDueIn;
//			$OldestSInvDate		= $invoice[0]->SInvDate;
//			$PaymentDeadline	= date('Y/m/d', strtotime('+'. $DueDate .' days', strtotime($OldestSInvDate)));
//			
//			if(date('Y/m/d') > $PaymentDeadline){
//				$over_due		= 1;
//				$over_due_days	= floor((strtotime(date('Y/m/d'))- strtotime($PaymentDeadline))/24/3600);
//			}
//		}else{
//			$over_due      		= 0;
//			$over_due_days 		= 0;
//		}
//		$result['over_due_customer'] 	= $over_due_days;
//		echo json_encode($result);
//		/*=============================================end===============================================================*/
//	}

	/*================== Daswan untuk view list item price ===============================*/
	public function view_list_price($ItemCode,$CustomerCode=""){
    	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['CustomerCode'] 	= $CustomerCode;
					
					//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/sales_order/v_list_price_item', $data);	
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

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