<?php
class CT_barangbahanpenolong extends CI_Controller{
	function __construct()
	{
	  parent::__construct();
		if (!$this->dx_auth->is_logged_in()) {
			header('HTTP/1.1 401 Unauthorize');die('expire'); 
		}
		
		$uid = $this->session->userdata('DX_user_id');
		
		if(!permissionAuth(2) && $uid != RID){ 
			header('HTTP/1.1 401 Unauthorize');die('noaccess');
		}
		
		$this->load->model("settings/mdl_settings", 'mdl_settings');

	}
	
	function index(){
	
		$this->load->view('settings/view_bahanpenolong');
	
	}
	
	
	function loadData(){
	
		$search = isset($_POST['_search'])?$_POST['_search']:false;
		$searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
		$searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
		$filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
		$limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
		$sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_bahan_penolong'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
			
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_name_customs" ) {
						$searchString = $k->data;
						$where .= " and part_name_customs like  '%".$searchString."%'"; 
					} else if ( $k->field == "hs_code" ) {
						$searchString = $k->data;
						$where .= " and hs_code like  '%".$searchString."%'"; 
					} else if ( $k->field == "bm" ) {
						$searchString = $k->data;
						$where .= " and bm like  '%".$searchString."%'"; 
					} else if ( $k->field == "cek_price" ) {
						$searchString = $k->data;
						$where .= " and cek_price like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_no2" ) {
						$searchString = $k->data;
						$where .= " and part_no2 like  '%".$searchString."%'"; 
					} else if ( $k->field == "saldo_awal" ) {
						$searchString = $k->data;
						$where .= " and saldo_awal like  '%".$searchString."%'"; 
					}  else if ( $k->field == "kode_barang" ) {
						$searchString = $k->data;
						$where .= " and kode_barang like  '%".$searchString."%'"; 
					}
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_bahanpenolong_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_settings->data_bahanpenolong_CountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
		if ($page > $total_pages) $page=$total_pages;
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){
						
			$responce->rows[$i]['id_bahan_penolong']=$r->id_bahan_penolong; 
			$responce->rows[$i]['part_no']=$r->part_no; 
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['part_name_customs']=$r->part_name_customs;
			$responce->rows[$i]['hs_code']=$r->hs_code;
			$responce->rows[$i]['bm']=$r->bm;
			$responce->rows[$i]['cek_price']=$r->cek_price;
			$responce->rows[$i]['part_no2']=$r->part_no2;
			$responce->rows[$i]['currency']=$r->currency;
			$responce->rows[$i]['item_code']=$r->item_code;
			$responce->rows[$i]['uom']=$r->uom;
			$responce->rows[$i]['seri_mesin']=$r->seri_mesin;
			$responce->rows[$i]['item_type1']=$r->item_type1;
			$responce->rows[$i]['item_type2']=$r->item_type2;
			$responce->rows[$i]['net_weight_unit']=$r->net_weight_unit;
			$responce->rows[$i]['dangerous_good']=$r->dangerous_good;
			$responce->rows[$i]['saldo_awal']=$r->saldo_awal;
			$responce->rows[$i]['consumable']=$r->consumable;
			$responce->rows[$i]['kode_barang']=$r->kode_barang;
			$responce->rows[$i]['kode_supplier']=$r->kode_supplier;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			$responce->rows[$i]['aktif']=$r->aktif;
			$i++;
		}
		echo json_encode($responce);		
	
	
	}
	
	function view_uploadbahanpenolong(){
		
		$this->load->view('settings/view_uploadbahanpenolong');
	
	}
	function view_bahanpenolong_stockawal(){
		
		$this->load->view('settings/view_bahanpenolong_stockawal');
	
	}
	
	function upload_file_bahanpenolong(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_bahanpenolong';
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'BP';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'invoice/bahan_penolong/';
		  $config['allowed_types'] = 'csv';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'invoice/bahan_penolong/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$myFile = $apppath.'invoice/bahan_penolong/';
				//echo $myFile; die();
				/* echo " exec('[spuload_stockawal_fg] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')";
				die(); */
				 
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_bahanpenolong] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')
					
					END TRY
					BEGIN CATCH 
						SELECT 
						'error' AS status
						,ERROR_MESSAGE() AS description;
						
					END CATCH;
					
					");
				 
				 $rs = $qry->result_array();
				 // $r = $qry->result();		
				 // var_dump($r);die();
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
				
				$status = $status;
				$msg = $msg;
			 }
			 else
			 {
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			 }
		  }
		  @unlink($_FILES[$file_element_name]);
	   }
	   echo json_encode(array('status' => $status, 'msg' => $msg));
	
	
	}
	
	function delete_uploadbahanpenolong(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_uploadbahanpenolong_upload = (isset($_POST['id_uploadbahanpenolong_upload']) && !empty($_POST['id_uploadbahanpenolong_upload']))?$_POST['id_uploadbahanpenolong_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$username = $this->session->userdata('DX_user_id');
	    $username = $this->session->userdata('DX_username');
		$apppath = $this->config->item('APP_upload_path');
		
		$tipe='BP';
		
		$path=$apppath.'invoice/bahan_penolong/'.$filename;
		$pathnew=$apppath.'invoice/bahan_penolong/log/'.$filename;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[spuload_bahanpenolong] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_uploadbahanpenolong_upload ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		//  echo json_encode($responce);
		 // $stmt = " exec('[spuload_assylist]') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
		
		$status = $status;
		$msg = $msg;
		
		if ($status=='00'){
			copy($path, $pathnew) or die(array('sts' => '00','desc' => "Unable to copy $path to $pathnew."));
			if (file_exists($path)) {
				unlink($path);
			} else {
				echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
				die();
			}
		}
		echo json_encode(array('sts' => $status, 'desc' => $msg));
	
	
	}
	
	function data_uploadbahanpenolong(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_uploadbahanpenolong_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_upload" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[date_upload],101)  =  '$searchString'"; 
					} else if ( $k->field == "status_upload" ) {
						$searchString = $k->data;
						$where .= " and status_upload like  '%".$searchString."%'"; 
					}  else if ( $k->field == "create_by" ) {
						$searchString = $k->data;
						$where .= " and create_by like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->upload_bahanpenolongAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->upload_bahanpenolongcountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_uploadbahanpenolong_upload']=$r->id_uploadbahanpenolong_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$r->filename; //str_replace(".csv","", $r->filename); 
			$responce->rows[$i]['filename2']=str_replace(".csv","", $r->filename); 
			
			$responce->rows[$i]['status_upload']=$r->status_upload;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['tipe']=$r->tipe;
			$responce->rows[$i]['filepath']=$r->filepath;
			$i++;
		}
		echo json_encode($responce);	
	
	}
	function proses_uploadbahanpenolong(){
	
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $id_uploadbahanpenolong_upload = (isset($_POST['id_uploadbahanpenolong_upload']) && !empty($_POST['id_uploadbahanpenolong_upload']))?$_POST['id_uploadbahanpenolong_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$tipe = 'BP';
		
		//$qry = $this->db->query("
		$qry = $this->db->query("
		
			BEGIN TRY
			  exec('[spi_bahan_penolong] @filename=''$filename'', @id_uploadbahanpenolong_upload=$id_uploadbahanpenolong_upload, @tipe=''$tipe'',  @username=''$username'' ')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
	
	}
	
	function viewdatauploadbahanpenolong(){
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $id_uploadbahanpenolong_upload = (isset($_POST['id_uploadbahanpenolong_upload']) && !empty($_POST['id_uploadbahanpenolong_upload']))?$_POST['id_uploadbahanpenolong_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$filepath = (isset($_POST['filepath']) && !empty($_POST['filepath']))?$_POST['filepath']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$filenya = $filepath .'/'. $filename;
		$f = fopen($filenya, "r");
		$data = "<table border=1>";
		while (($line = fgetcsv($f)) !== false) {
			$data .= "<tr>";
			foreach ($line as $cell) {
					$data .= "<td>" . htmlspecialchars($cell) . "</td>";
			}
			$data .=  "<tr>\n";
		}	
		$data .=  "</table>";	
		
		echo $data;
	
	}
	
	function loaddata_stockawal(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
		$searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
		$searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
		$filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
		$limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
		$sidx = isset($_POST['sidx'])?$_POST['sidx']:'id'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
			
		$where = " 1=1 and typebahan='BP' ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_stock" ) {
						$searchString = $k->data;
						$where .= " and date_stock = '$searchString'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->stockawal_bahanbaku_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_settings->stockawal_bahanbaku_CountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
		if ($page > $total_pages) $page=$total_pages;
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){
						
			$responce->rows[$i]['id_stock_awal']=$r->id_stock_awal; 
			$responce->rows[$i]['date_stock']=$r->date_stock; 
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['part_name_customs']=$r->part_name_customs;
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['qty']=$r->qty;
			$responce->rows[$i]['unit']=$r->unit;
			$responce->rows[$i]['unit_konversi']=$r->unit_konversi;
			$responce->rows[$i]['pengali']=$r->pengali;
			$responce->rows[$i]['netto']=$r->netto;
			$responce->rows[$i]['brutto']=$r->brutto;
			$responce->rows[$i]['typebahan']=$r->typebahan;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			
			$i++;
		}
		echo json_encode($responce);		
	}
	
	function proses_stockawal_add(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$tipe = (isset($_POST['tipe']) && !empty($_POST['tipe']))?$_POST['tipe']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_stockawal_upload = (isset($_POST['id_stockawal_upload']) && !empty($_POST['id_stockawal_upload']))?$_POST['id_stockawal_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$typebahan = 'BP';
		
		// echo " exec('spi_stock_awal_bp @filename=''$filename'', @id_stockawal_upload=$id_stockawal_upload, @tipe=''$tipe'',  @username=''$username'', @typebahan=''$typebahan''  ') ";
		// die(); 
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_stock_awal_bp @filename=''$filename'', @id_stockawal_upload=$id_stockawal_upload, @tipe=''$tipe'',  @username=''$username'', @typebahan=''$typebahan''  ')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
	
	
	}
	
	function view_bahanpenolong_data_in(){
	
		$this->load->view('settings/view_bahanpenolong_data_in');
	
	}
	
	function v_data_bp_in_All(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
		$searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
		$searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
		$filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
		$limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
		$sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_data_in_dtl'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
			
		$tglawal = (isset($_POST['tglawal']) && !empty($_POST['tglawal']))?$_POST['tglawal']:Date('Y-m-d');
		$tglakhir = (isset($_POST['tglakhir']) && !empty($_POST['tglakhir']))?$_POST['tglakhir']:Date('Y-m-d');
		
		$where = " 1=1 and BC23Tg between '$tglawal' and '$tglakhir' ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "kode_barang" ) {
						$searchString = $k->data;
						$where .= " and kode_barang like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_name_customs" ) {
						$searchString = $k->data;
						$where .= " and part_name_customs like  '%".$searchString."%'"; 
					}  else if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "doc_in_no" ) {
						$searchString = $k->data;
						$where .= " and doc_in_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "CAR" ) {
						$searchString = $k->data;
						$where .= " and CAR like  '%".$searchString."%'"; 
					}  else if ( $k->field == "BC23No" ) {
						$searchString = $k->data;
						$where .= " and BC23No like  '%".$searchString."%'"; 
					} else if ( $k->field == "PasokNama" ) {
						$searchString = $k->data;
						$where .= " and PasokNama like  '%".$searchString."%'"; 
					}  else if ( $k->field == "doc_in_date" ) {
						$searchString = $k->data;
						$where .= " and doc_in_date = '$searchString'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->v_data_bp_in_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_settings->v_data_bp_in_CountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
		if ($page > $total_pages) $page=$total_pages;
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){
						
			$responce->rows[$i]['id_data_in_dtl']=$r->id_data_in_dtl; 
			$responce->rows[$i]['id_data_in_hdr']=$r->id_data_in_hdr; 
			$responce->rows[$i]['id_bc_in_hdr']=$r->id_bc_in_hdr;
			$responce->rows[$i]['kode_barang']=$r->kode_barang;
			$responce->rows[$i]['part_name_customs']=$r->part_name_customs;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['qty_in']=$r->qty_in;
			$responce->rows[$i]['doc_in_no']=$r->doc_in_no;
			$responce->rows[$i]['doc_in_date']=$r->doc_in_date;
			$responce->rows[$i]['CAR']=$r->CAR;
			$responce->rows[$i]['BC23No']=$r->BC23No;
			$responce->rows[$i]['BC23Tg']=$r->BC23Tg;
			$responce->rows[$i]['typedok']=$r->typedok;
			$responce->rows[$i]['PasokNama']=$r->PasokNama;
			$responce->rows[$i]['PasokAlmt']=$r->PasokAlmt;
			$i++;
		}
		echo json_encode($responce);		
	}
	
	function view_bahanpenolong_update(){
		
		$part_no  = (isset($_POST['part_no']) && !empty($_POST['part_no']))?$_POST['part_no']:'';
		$part_name_customs  = (isset($_POST['part_name_customs']) && !empty($_POST['part_name_customs']))?$_POST['part_name_customs']:'';
		$part_name  = (isset($_POST['part_name']) && !empty($_POST['part_name']))?$_POST['part_name']:'';
		$hs_code  = (isset($_POST['hs_code']) && !empty($_POST['hs_code']))?$_POST['hs_code']:'';
		$bm  = (isset($_POST['bm']) && !empty($_POST['bm']))?$_POST['bm']:'';
		$cek_price  = (isset($_POST['cek_price']) && !empty($_POST['cek_price']))?$_POST['cek_price']:'';
		$idx = (isset($_POST['idx']) && !empty($_POST['idx']))?$_POST['idx']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$part_no2 = str_replace(" ", "",$part_no);
		$saldo_awal  = (isset($_POST['saldo_awal']) && !empty($_POST['saldo_awal']))?$_POST['saldo_awal']:'0';
		$kode_barang  = (isset($_POST['kode_barang']) && !empty($_POST['kode_barang']))?$_POST['kode_barang']:'';
		$uom  = (isset($_POST['uom']) && !empty($_POST['uom']))?$_POST['uom']:'';
		$aktif  = (isset($_POST['aktif']) && !empty($_POST['aktif']))?$_POST['aktif']:'';
		
		$data["part_no"] = $part_no;
		$data["part_no2"] = $part_no2; 
		$data["part_name_customs"] = $part_name_customs; 
		$data["idx"] = $idx; 
		$data["part_name"] = $part_name; 
		$data["hs_code"] = $hs_code; 
		$data["bm"] = $bm; 
		$data["cek_price"] = $cek_price; 
		$data["saldo_awal"] = $saldo_awal; 
		$data["kode_barang"] = $kode_barang;
		$data["uom"] = $uom;
		$data["aktif"] = $aktif;
		$this->load->view('settings/view_bahanpenolong_update', $data);
	
	}
	
	function update_bahanpenolong(){
		$part_no  = (isset($_POST['part_no']) && !empty($_POST['part_no']))?trim($_POST['part_no']):'';
		$part_name_customs  = (isset($_POST['partnamecustoms']) && !empty($_POST['partnamecustoms']))? trim($_POST['partnamecustoms']):'';
		$part_name  = (isset($_POST['partname']) && !empty($_POST['partname']))?trim($_POST['partname']):'';
		$hs_code  = (isset($_POST['hscode']) && !empty($_POST['hscode']))?trim($_POST['hscode']):'';
		$bm  = (isset($_POST['bm']) && !empty($_POST['bm']))?$_POST['bm']:'';
		$cek_price  = (isset($_POST['cek_price']) && !empty($_POST['cek_price']))?$_POST['cek_price']:'0';
		$idx = (isset($_POST['id']) && !empty($_POST['id']))?$_POST['id']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$part_no2 = str_replace(" ", "",$part_no);
		$saldo_awal  = (isset($_POST['txtsaldoawal_bp']) && !empty($_POST['txtsaldoawal_bp']))?$_POST['txtsaldoawal_bp']:'0';
		$kode_barang  = (isset($_POST['kodebarang']) && !empty($_POST['kodebarang']))?trim($_POST['kodebarang']):'';
		$aktif  = (isset($_POST['aktif']) && !empty($_POST['aktif']))?trim($_POST['aktif']):'';
		$uom  = (isset($_POST['uom']) && !empty($_POST['uom']))?trim($_POST['uom']):'';
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		
		
		$qry = $this->db->query("
			declare @command varchar(50) = '$command'
			BEGIN TRY
				if @command = 'UPDATE'
				begin
					update tbl_data_bahan_penolong set
					part_no = '$part_no'
					,part_name = '$part_name'
					,part_name_customs = '$part_name_customs'
					,hs_code = '$hs_code'
					,bm = '$bm'
					,cek_price = $cek_price
					,part_no2 = '$part_no2'
					,kode_barang = '$kode_barang'
					,saldo_awal = $saldo_awal
					,aktif = '$aktif'
					,uom = '$uom'
					where id_bahan_penolong = $idx
				end
				
				if @command = 'INSERT'
				begin
					if (select count(*) from tbl_data_bahan_penolong where part_no2 = '$part_no2') > 0
					begin
						SELECT 
						'00' AS status
						,' DATA SUDAH ADA' AS description;
						return
					end					
					insert into tbl_data_bahan_penolong(
						part_no
					,part_name
					,part_name_customs
					,hs_code
					,bm
					,cek_price 
					,part_no2
					,kode_barang
					,saldo_awal
					,aktif
					,uom
					) values (
					'$part_no'
					,'$part_name'
					,'$part_name_customs'
					,'$hs_code'
					,'$bm'
					, $cek_price
					,'$part_no2'
					,'$kode_barang'
					,$saldo_awal
					,'aktif'
					,'$uom'
					)
					
				end
				
				if @command = 'DELETE'
				begin
					delete tbl_data_bahan_penolong where id_bahan_penolong = $idx
					
				end
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description;
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
		
	}
	
	function view_bahanpenolong_data_out(){
	
		$this->load->view('settings/view_bahanpenolong_data_out');
	
	}
	
	function view_bahanpenolong_data_out_ct(){
		
		$this->load->view('settings/view_bahanpenolong_data_out_ct');
	}
	
	function view_bahanpenolong_data_out_ct_upload(){
	
		$this->load->view('settings/view_bahanpenolong_data_out_ct_upload');
	
	}
	
	
	function upload_file__bp_out(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_bp_out';
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'BPOUT';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'inventory/bahan_penolong_out/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'inventory/bahan_penolong_out/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$myFile = $apppath.'inventory/bahan_penolong_out/';
				//echo $myFile; die();
				/* echo " exec('[spuload_stockawal_fg] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')";
				die(); */
				 
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_bahanpenolong_out] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')
					
					END TRY
					BEGIN CATCH 
						SELECT 
						'error' AS status
						,ERROR_MESSAGE() AS description;
						
					END CATCH;
					
					");
				 
				 $rs = $qry->result_array();
				 // $r = $qry->result();		
				 // var_dump($r);die();
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
				
				$status = $status;
				$msg = $msg;
			 }
			 else
			 {
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			 }
		  }
		  @unlink($_FILES[$file_element_name]);
	   }
	   echo json_encode(array('status' => $status, 'msg' => $msg));
	
	
	}
	
	function upload_file__bp_out_ct(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_bp_out_ct';
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'BPCT';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'inventory/bahan_penolong_out_ct/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'inventory/bahan_penolong_out_ct/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$myFile = $apppath.'inventory/bahan_penolong_out_ct/';
				//echo $myFile; die();
				/* echo " exec('[spuload_stockawal_fg] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')";
				die(); */
				 
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_bahanpenolong_out_ct] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')
					
					END TRY
					BEGIN CATCH 
						SELECT 
						'error' AS status
						,ERROR_MESSAGE() AS description;
						
					END CATCH;
					
					");
				 
				 $rs = $qry->result_array();
				 // $r = $qry->result();		
				 // var_dump($r);die();
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
				
				$status = $status;
				$msg = $msg;
			 }
			 else
			 {
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			 }
		  }
		  @unlink($_FILES[$file_element_name]);
	   }
	   echo json_encode(array('status' => $status, 'msg' => $msg));
	
	
	}
	
	function delete_uploadbahanpenolong_out_ct(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_uploadbp_out_upload = (isset($_POST['id_uploadbp_out_upload']) && !empty($_POST['id_uploadbp_out_upload']))?$_POST['id_uploadbp_out_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$username = $this->session->userdata('DX_user_id');
	    $username = $this->session->userdata('DX_username');
		$apppath = $this->config->item('APP_upload_path');
		
		$tipe='BPCT';
		
		$path=$apppath.'inventory/bahan_penolong_out_ct/'.$filename;
		$pathnew=$apppath.'inventory/bahan_penolong_out_ct/log/'.$filename;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[spuload_bahanpenolong_out_ct] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_uploadbp_out_upload ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		//  echo json_encode($responce);
		 // $stmt = " exec('[spuload_assylist]') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
		
		$status = $status;
		$msg = $msg;
		
		if ($status=='00'){
			copy($path, $pathnew) or die(array('sts' => '00','desc' => "Unable to copy $path to $pathnew."));
			if (file_exists($path)) {
				unlink($path);
			} else {
				echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
				die();
			}
		}
		echo json_encode(array('sts' => $status, 'desc' => $msg));
	
	
	}
	
	function delete_uploadbahanpenolong_out(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_uploadbp_out_upload = (isset($_POST['id_uploadbp_out_upload']) && !empty($_POST['id_uploadbp_out_upload']))?$_POST['id_uploadbp_out_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$username = $this->session->userdata('DX_user_id');
	    $username = $this->session->userdata('DX_username');
		$apppath = $this->config->item('APP_upload_path');
		
		$tipe='BPCT';
		
		$path=$apppath.'inventory/bahan_penolong_out/'.$filename;
		$pathnew=$apppath.'inventory/bahan_penolong_out/log/'.$filename;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[spuload_bahanpenolong_out] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_uploadbp_out_upload ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		//  echo json_encode($responce);
		 // $stmt = " exec('[spuload_assylist]') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
		
		$status = $status;
		$msg = $msg;
		
		if ($status=='00'){
			copy($path, $pathnew) or die(array('sts' => '00','desc' => "Unable to copy $path to $pathnew."));
			if (file_exists($path)) {
				unlink($path);
			} else {
				echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
				die();
			}
		}
		echo json_encode(array('sts' => $status, 'desc' => $msg));
	
	
	}
	
	function data_upload_bp_out(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_uploadbp_out_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		$tipe_bp = isset($_POST['tipe_bp'])?$_POST['tipe_bp']:'0';
		$where = " tipe='$tipe_bp' ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_upload" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[date_upload],101)  =  '$searchString'"; 
					} else if ( $k->field == "status_upload" ) {
						$searchString = $k->data;
						$where .= " and status_upload like  '%".$searchString."%'"; 
					}  else if ( $k->field == "create_by" ) {
						$searchString = $k->data;
						$where .= " and create_by like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->upload_bahanpenolong_outAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->upload_bahanpenolongcountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_uploadbp_out_upload']=$r->id_uploadbp_out_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$r->filename; 
			$responce->rows[$i]['data2']=str_replace(array('.xls', '.XLS'), array('',''), $r->filename); 
			$responce->rows[$i]['status_upload']=$r->status_upload;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['tipe']=$r->tipe;
			$responce->rows[$i]['filepath']=$r->filepath;
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function prosesfile_bp_out_ct(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $id_uploadbp_out_upload = (isset($_POST['id_uploadbp_out_upload']) && !empty($_POST['id_uploadbp_out_upload']))?$_POST['id_uploadbp_out_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		$tipe = 'BPOUT';
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_bahanpenolong_out_ct @filename=''$filename'', @id_uploadbp_out_upload=$id_uploadbp_out_upload, @tipe=''$tipe'',  @username=''$username'' ')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
		
	}
	
	function prosesfile_bp_out(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $id_uploadbp_out_upload = (isset($_POST['id_uploadbp_out_upload']) && !empty($_POST['id_uploadbp_out_upload']))?$_POST['id_uploadbp_out_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		$tipe = 'BPOUT';
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_bahanpenolong_out @filename=''$filename'', @id_uploadbp_out_upload=$id_uploadbp_out_upload, @tipe=''$tipe'',  @username=''$username'' ')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
		
	}
	
	function data_bahanpenolong_out(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_bp_out_dtl'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		$tglawal = isset($_POST['tglawal'])?$_POST['tglawal']:date('Y-m-d');	
		$tglakhir = isset($_POST['tglakhir'])?$_POST['tglakhir']:date('Y-m-d');	
		$doc_out_to = isset($_POST['doc_out_to'])?$_POST['doc_out_to']:'';	
		
		$where = " 1=1 and doc_date between '$tglawal'  and '$tglakhir' ";
		
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "no_invoice" ) {
						$searchString = $k->data;
						$where .= " and no_invoice like  '%".$searchString."%'"; 
					} else if ( $k->field == "tgl_invoice" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[tgl_invoice],126)  =  '$searchString'"; 
					} else if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					}  else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					}  else if ( $k->field == "doc_no" ) {
						$searchString = $k->data;
						$where .= " and doc_no like  '%".$searchString."%'"; 
					}  else if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					}  else if ( $k->field == "car" ) {
						$searchString = $k->data;
						$where .= " and car like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_bahanpenolong_outAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_bahanpenolong_outcountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_bp_out_dtl']=$r->id_bp_out_dtl; 
			$responce->rows[$i]['container_number']=$r->container_number; 
			$responce->rows[$i]['no_invoice']=$r->no_invoice; 
			$responce->rows[$i]['tgl_invoice']=$r->tgl_invoice;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['qty']=$r->qty;
			$responce->rows[$i]['qty_out']=$r->qty_out;
			$responce->rows[$i]['uom']=$r->uom;
			$responce->rows[$i]['doc_no']=$r->doc_no;
			$responce->rows[$i]['doc_date']=$r->doc_date;
			$responce->rows[$i]['doc_out_to']=$r->doc_out_to;
			$responce->rows[$i]['filename']=$r->filename;
			$responce->rows[$i]['car']=$r->car;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			
			$responce->rows[$i]['approved_date']=$r->approved_date;
			$responce->rows[$i]['price']=$r->price;
			$responce->rows[$i]['status_data']=$r->status_data;
			$responce->rows[$i]['kode_buyer']=$r->kode_buyer;
			$responce->rows[$i]['nama_buyer']=$r->nama_buyer;
				
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function data_bahanpenolong_out_ct(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_bp_out_dtl'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		$tglawal = isset($_POST['tglawal'])?$_POST['tglawal']:date('Y-m-d');	
		$tglakhir = isset($_POST['tglakhir'])?$_POST['tglakhir']:date('Y-m-d');	
		$doc_out_to = isset($_POST['doc_out_to'])?$_POST['doc_out_to']:'';	
		
		$where = " 1=1 and doc_date between '$tglawal'  and '$tglakhir' and doc_out_to=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "no_invoice" ) {
						$searchString = $k->data;
						$where .= " and no_invoice like  '%".$searchString."%'"; 
					} else if ( $k->field == "tgl_invoice" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[tgl_invoice],126)  =  '$searchString'"; 
					} else if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					}  else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					}  else if ( $k->field == "doc_no" ) {
						$searchString = $k->data;
						$where .= " and doc_no like  '%".$searchString."%'"; 
					}  else if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					}  else if ( $k->field == "car" ) {
						$searchString = $k->data;
						$where .= " and car like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_bahanpenolong_outAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_bahanpenolong_outcountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_bp_out_dtl']=$r->id_bp_out_dtl; 
			$responce->rows[$i]['container_number']=$r->container_number; 
			$responce->rows[$i]['no_invoice']=$r->no_invoice; 
			$responce->rows[$i]['tgl_invoice']=$r->tgl_invoice;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['qty']=$r->qty;
			$responce->rows[$i]['qty_out']=$r->qty_out;
			$responce->rows[$i]['uom']=$r->uom;
			$responce->rows[$i]['doc_no']=$r->doc_no;
			$responce->rows[$i]['doc_date']=$r->doc_date;
			$responce->rows[$i]['doc_out_to']=$r->doc_out_to;
			$responce->rows[$i]['filename']=$r->filename;
			$responce->rows[$i]['car']=$r->car;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			
			$responce->rows[$i]['approved_date']=$r->approved_date;
			$responce->rows[$i]['price']=$r->price;
			$responce->rows[$i]['status_data']=$r->status_data;
			$responce->rows[$i]['kode_buyer']=$r->kode_buyer;
			$responce->rows[$i]['nama_buyer']=$r->nama_buyer;	
				
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function view_bahanpenolong_out_update(){
		$id_bp_out_dtl = (isset($_POST['id_bp_out_dtl']) && !empty($_POST['id_bp_out_dtl']))?$_POST['id_bp_out_dtl']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $part_no = (isset($_POST['part_no']) && !empty($_POST['part_no']))?$_POST['part_no']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $part_name = (isset($_POST['part_name']) && !empty($_POST['part_name']))?$_POST['part_name']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $qty = (isset($_POST['qty']) && !empty($_POST['qty']))?$_POST['qty']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $status_data = (isset($_POST['status_data']) && !empty($_POST['status_data']))?$_POST['status_data']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $no_invoice = (isset($_POST['no_invoice']) && !empty($_POST['no_invoice']))?$_POST['no_invoice']:'';
	    $tgl_invoice = (isset($_POST['tgl_invoice']) && !empty($_POST['tgl_invoice']))?$_POST['tgl_invoice']:'';
	    
		
		$data["id_bp_out_dtl"] = $id_bp_out_dtl;
		$data["part_no"] = $part_no; 
		$data["part_name"] = $part_name; 
		$data["qty"] = $qty; 
		$data["status_data"] = $status_data; 
		$data["no_invoice"] = $no_invoice; 
		$data["tgl_invoice"] = $tgl_invoice; 
		$this->load->view('settings/view_bahanpenolong_out_update', $data);
			
		
		
	}
	
	function update_bahanpenolong_out(){
		$part_no  = (isset($_POST['txt_bp_partno_out']) && !empty($_POST['txt_bp_partno_out']))?trim($_POST['txt_bp_partno_out']):die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$part_name  = (isset($_POST['txt_bp_partname_out']) && !empty($_POST['txt_bp_partname_out']))?trim($_POST['txt_bp_partname_out']):die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$qty  = (isset($_POST['txt_bp_update_qty_out']) && !empty($_POST['txt_bp_update_qty_out']))?trim($_POST['txt_bp_update_qty_out']):die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$status_data  = (isset($_POST['txt_bp_update_status_out']) && !empty($_POST['txt_bp_update_status_out']))?trim($_POST['txt_bp_update_status_out']):die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$idx  = (isset($_POST['hdn_bp_id_bp_out_dtl']) && !empty($_POST['hdn_bp_id_bp_out_dtl']))?trim($_POST['hdn_bp_id_bp_out_dtl']):die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$command  = (isset($_POST['command']) && !empty($_POST['command']))?trim($_POST['command']):die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
	
		$qry = $this->db->query("
			declare @command varchar(50) = '$command'
			BEGIN TRY
				if @command = 'UPDATE'
				begin
					update tbl_bahanpenolong_out set
					part_no = '$part_no'
					,part_name = '$part_name'
					,qty = $qty
					,status_data = '$status_data'
					where id_bp_out_dtl = $idx
				end
				
				if @command = 'INSERT'
				begin
					SELECT 
					'06 ' AS status
					,'SILAHKAN UPLOAD ULANG MENGGUNAKAN EXCEL UNTUK DATA YANG DI TAMBAHKAN' AS description;
					
				end
				
				if @command = 'DELETE'
				begin
					delete tbl_bahanpenolong_out where id_bp_out_dtl = $idx
					
				end
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description;
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
		
	}
	
	function view_bahanpenolong_out_update_ct(){
		$id_bp_out_dtl = (isset($_POST['id_bp_out_dtl']) && !empty($_POST['id_bp_out_dtl']))?$_POST['id_bp_out_dtl']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $part_no = (isset($_POST['part_no']) && !empty($_POST['part_no']))?$_POST['part_no']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $part_name = (isset($_POST['part_name']) && !empty($_POST['part_name']))?$_POST['part_name']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $qty = (isset($_POST['qty']) && !empty($_POST['qty']))?$_POST['qty']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $status_data = (isset($_POST['status_data']) && !empty($_POST['status_data']))?$_POST['status_data']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $no_invoice = (isset($_POST['no_invoice']) && !empty($_POST['no_invoice']))?$_POST['no_invoice']:'';
	    $tgl_invoice = (isset($_POST['tgl_invoice']) && !empty($_POST['tgl_invoice']))?$_POST['tgl_invoice']:'';
	    
		
		$data["id_bp_out_dtl"] = $id_bp_out_dtl;
		$data["part_no"] = $part_no; 
		$data["part_name"] = $part_name; 
		$data["qty"] = $qty; 
		$data["status_data"] = $status_data; 
		$data["no_invoice"] = $no_invoice; 
		$data["tgl_invoice"] = $tgl_invoice; 
		$this->load->view('settings/view_bahanpenolong_out_update_ct', $data);
			
		
		
	}
	
	
	function view_bahanpenolong_stockopname(){
		$this->load->view('settings/view_bahanpenolong_stockopname');
	
	}
	
	
  
	function view_bahanpenolong_mutasi(){
		$this->load->view('settings/view_bahanpenolong_mutasi');
	
	}
	
	function view_bahanpenolong_stockopname_upload(){
		$this->load->view('settings/view_bahanpenolong_stockopname_upload');
	
	}
		
	function load_laporan_per_part(){
  
		$search = isset($_POST['_search'])?$_POST['_search']:false;
		$searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
		$searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
		$filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
		$limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
		$sidx = isset($_POST['sidx'])?$_POST['sidx']:'part_no'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'asc'; // get the direction	
		
			
		$tglawal = (isset($_POST['tglawal']) && !empty($_POST['tglawal']))?$_POST['tglawal']:Date('Y-m-d');
		$tglakhir = (isset($_POST['tglakhir']) && !empty($_POST['tglakhir']))?$_POST['tglakhir']:Date('Y-m-d');
		
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like '%".$searchString."%'"; 
					} else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_report_per_part_all($limit,$page,$sidx,$sord, $where, $tglawal, $tglakhir);
		$count = $this->mdl_settings->data_report_per_part_CountAll($where, $tglawal, $tglakhir );
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
		if ($page > $total_pages) $page=$total_pages;
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){
						
			$responce->rows[$i]['part_no']=$r['part_no']; 
			$responce->rows[$i]['part_name']=$r['part_name']; 
			$responce->rows[$i]['stock_awal']=$r['stock_awal'];
			$responce->rows[$i]['qty_in']=$r['qty_in'];
			$responce->rows[$i]['qty_out']=$r['qty_out'];
			$responce->rows[$i]['sisa_by_date']=$r['sisa_by_date'];
			$responce->rows[$i]['unit']= 'PCE';//$r['unit'];
			$responce->rows[$i]['stock_opname']=$r['stock_opname'];
			$responce->rows[$i]['selisih']=$r['selisih'];
			$i++;
		}
		echo json_encode($responce);
	
  
	
  }		
	function view_bahanpenolong_data_out_upload(){
		$this->load->view('settings/view_bahanpenolong_data_out_upload');
		
	}
	
	
	function view_bahanpenolong_memo(){
		
		$this->load->view('settings/view_bahanpenolong_memo');
		
	}
	
	function autocomplete_supplier(){
		$namasupplier = isset($_GET['name_startsWith'])?$_GET['name_startsWith']:'';
		$where = " (supplier_code like '%$namasupplier%' or supplier_name like '%$namasupplier%' ) " ;
		$q = $this->db->query("
			select
			
			[id]
		  ,[supplier_code]
		  ,[supplier_name]
		  ,[supplier_address]
		  ,[supplier_address1]
		  ,[supplier_country]
		  ,[base_price]
		  ,[copper_base_reff]
		  ,[subgct]
		  ,[subcode_as400]
		  ,[NPWP]
		,[NOIJIN]
		,[NOKONTRAK]
		,[TGLIJIN]
		,[TGLKONTRAK]	
			from
			tbl_data_supplier where $where
		
		");
        $i=0;
		$responce = '';
		foreach($q->result() as $r ){
			$responce[$i]['id']=$r->id; 
			$responce[$i]['subcode_as400']=$r->subcode_as400; 
			$responce[$i]['supplier_name']=$r->supplier_name; 
			$responce[$i]['NPWP']=$r->NPWP;  
			$i++;
		}
		echo json_encode($responce);
	}
	
	function autocomplete_barang(){
		$namasupplier = isset($_GET['name_startsWith'])?$_GET['name_startsWith']:'';
		$where = " (part_no like '%$namasupplier%' or part_name like '%$namasupplier%' ) " ;
		$q = $this->db->query("
			select
			
		dbo.tbl_data_bahan_penolong.part_no,
dbo.tbl_data_bahan_penolong.part_name,
dbo.tbl_data_bahan_penolong.part_name_customs,
dbo.tbl_data_bahan_penolong.hs_code,
dbo.tbl_data_bahan_penolong.kode_barang,
dbo.tbl_data_bahan_penolong.uom
			from
			tbl_data_bahan_penolong where $where
		
		");
        $i=0;
		$responce = '';
        foreach($q->result() as $r){
			$responce[$i]['part_no']=$r->part_no; 
			$responce[$i]['part_name']=$r->part_name; 
			$responce[$i]['part_name_customs']=$r->part_name_customs; 
$responce[$i]['hs_code']=$r->hs_code;  
$responce[$i]['kode_barang']=$r->kode_barang;  		
$responce[$i]['uom']=$r->uom;  			
			$i++;
		}
		echo json_encode($responce);
		
		
	}
	
	
	function autocomplete_kode_scrap(){
		$part_no = isset($_GET['part_no'])?$_GET['part_no']:'';
		$where = " (part_no like '%$part_no%' or part_name like '%$part_no%' ) " ;
			
		$q = $this->db->query("
			select
				dbo.tbl_scrap_data.part_no,
				dbo.tbl_scrap_data.part_name,
				dbo.tbl_scrap_data.part_name_customs,
				dbo.tbl_scrap_data.hs_code,
				dbo.tbl_scrap_data.kode_barang,
				dbo.tbl_scrap_data.bm
			from
			tbl_scrap_data where $where
		
		");
        $i=0;
		$responce = '';
        foreach($q->result() as $r){
			$responce[$i]['part_no']=$r->part_no; 
			$responce[$i]['part_name']=$r->part_name; 
			$responce[$i]['part_name_customs']=$r->part_name_customs; 
			$responce[$i]['hs_code']=$r->hs_code;  
			$responce[$i]['kode_barang']=$r->kode_barang;  		
			$responce[$i]['bm']=$r->bm;  			
			$i++;
		}
		echo json_encode($responce);
		
		
	}
	
	
	function data_bahanpenolong_memo_Allx(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_memo'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		$fill = isset($_POST['fill'])?$_POST['fill']:'0';
		if($fill == 'EXIM' ){
			$status_data = isset($_POST['status_data'])?$_POST['status_data']:'0';
			$TIPEOUT = isset($_POST['TIPEOUT'])?$_POST['TIPEOUT']:'0';
			$where = " status_data = '$status_data' "; 
			if ($TIPEOUT == 'NONSCRAP'){
					$where .= " AND tipe_out <> 'SCRAP' "; 
			} else if ($TIPEOUT == 'SCRAP'){
				$where .= " AND tipe_out = 'SCRAP' "; 
			} 
		} else if ($fill == 'SCRAP' ){
			$status_data = isset($_POST['status_data'])?$_POST['status_data']:'NEW';
			$where = " tipe_out = 'SCRAP' and status_data='$status_data' ";			
		}	
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "nomor_memo" ) {
						$searchString = $k->data;
						$where .= " and nomor_memo like '%".$searchString."%'"; 
					}  else if ( $k->field == "car" ) {
						$searchString = $k->data;
						$where .= " and car like  '%".$searchString."%'"; 
					}  else if ( $k->field == "kode_pembeli" ) {
						$searchString = $k->data;
						$where .= " and kode_pembeli like  '%".$searchString."%'"; 
					} else if ( $k->field == "nama_pembeli" ) {
						$searchString = $k->data;
						$where .= " and nama_pembeli like  '%".$searchString."%'"; 
					} else if ( $k->field == "tipe_out" ) {
						$searchString = $k->data;
						$where .= " and tipe_out like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_bahanpenolong_memo_All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_bahanpenolong_memo_CountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){
			$responce->rows[$i]['id_memo']=$r->id_memo;
			$responce->rows[$i]['nomor_memo']=$r->nomor_memo;
			$responce->rows[$i]['tgl_memo']=$r->tgl_memo;
			$responce->rows[$i]['npwp_pembeli']=$r->npwp_pembeli;
			$responce->rows[$i]['kode_pembeli']=$r->kode_pembeli;
			$responce->rows[$i]['harga_penyerahan']=$r->harga_penyerahan;
			$responce->rows[$i]['id_ceisa_hdr']=$r->id_ceisa_hdr;
			$responce->rows[$i]['bc_no']=$r->bc_no;
			$responce->rows[$i]['tgl_bc']=$r->tgl_bc;;
			$responce->rows[$i]['car']=$r->car;
			$responce->rows[$i]['nama_pembeli']=$r->nama_pembeli;
			$responce->rows[$i]['typedok']=$r->typedok;
			$responce->rows[$i]['tipe_out']=$r->tipe_out;
			$responce->rows[$i]['kdval']=$r->kdval;
			$responce->rows[$i]['ndpbm']=$r->ndpbm;
			$responce->rows[$i]['bruto']=$r->bruto;
			$responce->rows[$i]['status_data']=$r->status_data;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			$i++;
		}
		echo json_encode($responce);
		
	
	}
	
	function data_bahanpenolong_memo_scrap(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_bp_out_dtl'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		
		$fill = isset($_POST['fill'])?$_POST['fill']:'0';
		if($fill == 'SCRAP' ){
			$id_memo_bp = isset($_POST['id_memo_bp'])?$_POST['id_memo_bp']:'0';
			$where = " id_memo_bp = '$id_memo_bp' "; 
		}
		 
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and dbo.tbl_bahanpenolong_out.part_no like '%".$searchString."%'"; 
					}  else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and dbo.tbl_bahanpenolong_out.part_name like  '%".$searchString."%'"; 
					}  else if ( $k->field == "kode_scrap" ) {
						$searchString = $k->data;
						$where .= " and dbo.tbl_bahanpenolong_memo_scrap.kode_scrap like  '%".$searchString."%'"; 
					} else if ( $k->field == "nama_scrap" ) {
						$searchString = $k->data;
						$where .= " and dbo.tbl_bahanpenolong_memo_scrap.nama_scrap like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_bahanpenolong_memo_scrap_All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_bahanpenolong_memo_scrap_CountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){
			$responce->rows[$i]['id_bp_out_dtl']=$r->id_bp_out_dtl;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['qty']=$r->qty;
			$responce->rows[$i]['uom']=$r->uom;
			$responce->rows[$i]['price']=$r->price;
			$responce->rows[$i]['id_memo_bp']=$r->id_memo_bp;
			$responce->rows[$i]['jmkemas_scrap']=$r->jmkemas_scrap;
			$responce->rows[$i]['jnkemas_scrap']=$r->jnkemas_scrap;
			$responce->rows[$i]['kode_scrap']=$r->kode_scrap;
			$responce->rows[$i]['nama_scrap']=$r->nama_scrap;
			$responce->rows[$i]['qty_scrap']=$r->qty_scrap;
			$responce->rows[$i]['bruto_scrap']=$r->bruto_scrap;
			$responce->rows[$i]['netto_scrap']=$r->netto_scrap;
			
			$responce->rows[$i]['harga_scrap']=$r->harga_scrap;
			$i++;
		}
		echo json_encode($responce);
		
	
	}
	
	function view_bahanpenolong_memo_update(){
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$id_memo='';
		$nomor_memo = '';
		$tanggal_memo = '';
		$tipe_out = '';
		$harga_penyerahan = '';
		$bruto = '';
		$kode_pembeli = '';
		$kdval = '';
		$npwp_pembeli = '';
		$nama_pembeli = '';
		if ($command == 'UPDATE'){
			$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
			$qry = $this->db->query("
				select * from tbl_bahanpenolong_memo 
				where id_memo = $id_memo
			
			");	
			
			foreach ($qry->result() as $r ){
				$id_memo=$r->id_memo;
				$nomor_memo=$r->nomor_memo;
				$tanggal_memo=$r->tgl_memo;
				$tipe_out=$r->tipe_out;
				$harga_penyerahan=$r->harga_penyerahan;
				$kode_pembeli=$r->kode_pembeli;
				$kdval=$r->kdval;
				$npwp_pembeli=$r->npwp_pembeli;
				$nama_pembeli=$r->nama_pembeli;
				$bruto=$r->bruto;
			}
			
		}
		$data['command'] = $command;
		$data['id_memo'] = $id_memo;
		$data['nomor_memo'] = $nomor_memo;
		$data['tanggal_memo'] = $tanggal_memo;
		$data['tipe_out'] = $tipe_out;
		$data['harga_penyerahan'] = $harga_penyerahan;
		$data['kode_pembeli'] = $kode_pembeli;
		$data['kdval'] = $kdval;
		$data['npwp_pembeli'] = $npwp_pembeli;
		$data['nama_pembeli'] = $nama_pembeli;
		$data['bruto'] = $bruto;
		$this->load->view('settings/view_bahanpenolong_memo_update', $data);
		
	}
	
	function view_bahanpenolong_memo_update_view(){
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$id_memo='';
		$nomor_memo = '';
		$tanggal_memo = '';
		$tipe_out = '';
		$harga_penyerahan = '';
		$bruto = '';
		$kode_pembeli = '';
		$kdval = '';
		$npwp_pembeli = '';
		$nama_pembeli = '';
		if ($command == 'UPDATE'){
			$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
			$qry = $this->db->query("
				select * from tbl_bahanpenolong_memo 
				where id_memo = $id_memo
			
			");	
			
			foreach ($qry->result() as $r ){
				$id_memo=$r->id_memo;
				$nomor_memo=$r->nomor_memo;
				$tanggal_memo=$r->tgl_memo;
				$tipe_out=$r->tipe_out;
				$harga_penyerahan=$r->harga_penyerahan;
				$kode_pembeli=$r->kode_pembeli;
				$kdval=$r->kdval;
				$npwp_pembeli=$r->npwp_pembeli;
				$nama_pembeli=$r->nama_pembeli;
				$bruto=$r->bruto;
			}
			
		}
		$data['command'] = $command;
		$data['id_memo'] = $id_memo;
		$data['nomor_memo'] = $nomor_memo;
		$data['tanggal_memo'] = $tanggal_memo;
		$data['tipe_out'] = $tipe_out;
		$data['harga_penyerahan'] = $harga_penyerahan;
		$data['kode_pembeli'] = $kode_pembeli;
		$data['kdval'] = $kdval;
		$data['npwp_pembeli'] = $npwp_pembeli;
		$data['nama_pembeli'] = $nama_pembeli;
		$data['bruto'] = $bruto;
		$this->load->view('settings/view_bahanpenolong_memo_update_view', $data);
		
	}
	
	function update_memo_bahanpenolong(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:'0';
		$nomor_memo = (isset($_POST['nomor_memo']) && !empty($_POST['nomor_memo']))?$_POST['nomor_memo']:die('{"sts":"ERROR","desc":" Param  NOMOR MEMO Tidak Ditemukan"}');
		$tanggal_memo = (isset($_POST['tanggal_memo']) && !empty($_POST['tanggal_memo']))?$_POST['tanggal_memo']:die('{"sts":"ERROR","desc":" Param  TGL MEMO Tidak Ditemukan"}');
		$tipe_out = (isset($_POST['tipe_out']) && !empty($_POST['tipe_out']))?$_POST['tipe_out']:die('{"sts":"ERROR","desc":" Param  TIPE OUT Tidak Ditemukan"}');
		$harga_penyerahan = (isset($_POST['harga_penyerahan']) && !empty($_POST['harga_penyerahan']))?$_POST['harga_penyerahan']:die('{"sts":"ERROR","desc":" Param  HARGA PENYERAHAN Tidak Ditemukan"}');
		$bruto = (isset($_POST['bruto']) && !empty($_POST['bruto']))?$_POST['bruto']:die('{"sts":"ERROR","desc":" Param  BRUTO Tidak Ditemukan"}');
		$kode_pembeli = (isset($_POST['kode_pembeli']) && !empty($_POST['kode_pembeli']))?$_POST['kode_pembeli']:die('{"sts":"ERROR","desc":" Param  KD PEMBELI Tidak Ditemukan"}');
		$kdval = (isset($_POST['kdval']) && !empty($_POST['kdval']))?$_POST['kdval']:die('{"sts":"ERROR","desc":" Param   KDVAL Tidak Ditemukan"}');
		
		
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		
		
		$qry = $this->db->query("
			declare @command varchar(19) = '$command'
			if (select count(*) from tbl_data_supplier where subcode_as400 = '$kode_pembeli' )	= 0
			begin	
				SELECT 
					'06' AS status
					,' DATA SUPPLIER TIDAK DITEMUKAN ' AS description
					,'' as id_memo
				 return
			end
			declare @supplier_name varchar(100), @NPWP varchar(100), @id_memo bigint
			select 
			top 1
				@supplier_name=supplier_name
				,@NPWP=NPWP
			from tbl_data_supplier
			where subcode_as400 = '$kode_pembeli' 
			BEGIN TRY
				
				if @command = 'CREATE'
				begin
					insert into tbl_bahanpenolong_memo (
						dbo.tbl_bahanpenolong_memo.nomor_memo,
			dbo.tbl_bahanpenolong_memo.tgl_memo,
			dbo.tbl_bahanpenolong_memo.npwp_pembeli,
			dbo.tbl_bahanpenolong_memo.kode_pembeli,
			dbo.tbl_bahanpenolong_memo.harga_penyerahan,
			dbo.tbl_bahanpenolong_memo.create_date,
			dbo.tbl_bahanpenolong_memo.create_by,
			dbo.tbl_bahanpenolong_memo.update_date,
			dbo.tbl_bahanpenolong_memo.update_by,
			dbo.tbl_bahanpenolong_memo.tipe_out,
			dbo.tbl_bahanpenolong_memo.status_data,
			dbo.tbl_bahanpenolong_memo.nama_pembeli,
			dbo.tbl_bahanpenolong_memo.kdval,
			dbo.tbl_bahanpenolong_memo.bruto	
					
					
					) VALUES (
					'$nomor_memo'
					,'$tanggal_memo'
					,@NPWP
					,'$kode_pembeli'
					,$harga_penyerahan
					,GETDATE()
					,'$username'
					,GETDATE()
					,'$username'
					,'$tipe_out'
					,'NEW'
					,@supplier_name
					,'$kdval'
					,$bruto
					
					)
				set @id_memo = SCOPE_IDENTITY() 	
				end
				
				if @command = 'UPDATE'
				begin
					if (select status_data from tbl_bahanpenolong_memo where id_memo=$id_memo) <> 'NEW'
					begin
						set @id_memo = $id_memo
						SELECT 
						'00' AS status
						,' DATA SUDAH PROSES EXIM, BATALKAN DAHULU' AS description
						,CONVERT(varchar, @id_memo) as id_memo
						
						return
					
					end
					
					update tbl_bahanpenolong_memo set  
					dbo.tbl_bahanpenolong_memo.nomor_memo = '$nomor_memo',
					dbo.tbl_bahanpenolong_memo.tgl_memo = '$tanggal_memo',
					dbo.tbl_bahanpenolong_memo.npwp_pembeli = @NPWP,
					dbo.tbl_bahanpenolong_memo.kode_pembeli = '$kode_pembeli',
					dbo.tbl_bahanpenolong_memo.harga_penyerahan = $harga_penyerahan,
					dbo.tbl_bahanpenolong_memo.update_date = GETDATE(),
					dbo.tbl_bahanpenolong_memo.update_by = '$username',
					dbo.tbl_bahanpenolong_memo.nama_pembeli = @supplier_name,
					dbo.tbl_bahanpenolong_memo.kdval = '$kdval',
					dbo.tbl_bahanpenolong_memo.bruto = '$bruto'	
					where id_memo = $id_memo
					
					set @id_memo = $id_memo
				
				end
				if @command = 'DELETE'
				begin
					if (select status_data from tbl_bahanpenolong_memo where id_memo=$id_memo) <> 'NEW'
					begin
						set @id_memo = $id_memo
						SELECT 
						'00' AS status
						,' DATA SUDAH PROSES EXIM, BATALKAN DAHULU' AS description
						,CONVERT(varchar, $id_memo) as id_memo
						
						return
					
					end
					delete from tbl_bahanpenolong_memo where id_memo = 	$id_memo
					delete from tbl_bahanpenolong_out  where id_memo_bp =  $id_memo and doc_out_to = 3	
				end
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
				,CONVERT(varchar, @id_memo) as id_memo
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ', 'id_memo' => $row['id_memo']);
		 }  
		 echo json_encode($responce);
		
		
	}
	
	function update_memo_bahanpenolong_dtl(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param  id_memoTidak Ditemukan"}');
		$part_no = (isset($_POST['part_no']) && !empty($_POST['part_no']))?$_POST['part_no']:die('{"sts":"ERROR","desc":" Param  part_no Tidak Ditemukan"}');
		$part_name = (isset($_POST['part_name']) && !empty($_POST['part_name']))?$_POST['part_name']:die('{"sts":"ERROR","desc":" Param  part_name Tidak Ditemukan"}');
		$hs_code = (isset($_POST['hs_code']) && !empty($_POST['hs_code']))?$_POST['hs_code']:die('{"sts":"ERROR","desc":" Param  hs_code Tidak Ditemukan"}');
		$uom = (isset($_POST['uom']) && !empty($_POST['uom']))?$_POST['uom']:die('{"sts":"ERROR","desc":" Param  HARGA uom Tidak Ditemukan"}');
		$qty = (isset($_POST['qty']) && !empty($_POST['qty']))?$_POST['qty']:die('{"sts":"ERROR","desc":" Param  qty Tidak Ditemukan"}');
		$price = (isset($_POST['price']) && !empty($_POST['price']))?$_POST['price']:die('{"sts":"ERROR","desc":" Param  price Tidak Ditemukan"}');
		$jmkemas = (isset($_POST['jmkemas']) && !empty($_POST['jmkemas']))?$_POST['jmkemas']:'0';
		$jnkemas = (isset($_POST['jnkemas']) && !empty($_POST['jnkemas']))?$_POST['jnkemas']:'';
		$netto = (isset($_POST['netto']) && !empty($_POST['netto']))?$_POST['netto']:die('{"sts":"ERROR","desc":" Param   netto Tidak Ditemukan"}');
		$id_bp_out_dtl = (isset($_POST['id_bp_out_dtl']) && !empty($_POST['id_bp_out_dtl']))?$_POST['id_bp_out_dtl']:'0';
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		
		
		$qry = $this->db->query("
			declare @command varchar(19) = '$command'
			declare @id_memo bigint = $id_memo
			if (select count(*) from tbl_data_bahan_penolong where part_no = '$part_no' )	= 0
			begin	
				SELECT 
					'06' AS status
					,' DATA BARANG TIDAK DITEMUKAN ' AS description
					,'' as id_bp_out_dtl
					,'' as nilinv
				 return
			end
			declare @id_bp_out_dtl bigint, @nomor_memo varchar(100), @tgl_memo date
			select 
				@nomor_memo = nomor_memo
				,@tgl_memo = tgl_memo
			from tbl_bahanpenolong_memo where id_memo = $id_memo
			
			if (select status_data from tbl_bahanpenolong_memo where id_memo=$id_memo) <> 'NEW'
			begin
				set @id_memo = $id_memo
				SELECT 
				'00' AS status
				,' DATA SUDAH PROSES EXIM, BATALKAN DAHULU' AS description
				,CONVERT(varchar, $id_bp_out_dtl) as id_bp_out_dtl
				,'' as nilinv
				
				return
			
			end
			

			BEGIN TRY
				
				if @command = 'CREATE'
				begin
					insert into tbl_bahanpenolong_out (
						
						dbo.tbl_bahanpenolong_out.part_no,
						dbo.tbl_bahanpenolong_out.part_name,
						dbo.tbl_bahanpenolong_out.qty,
						dbo.tbl_bahanpenolong_out.qty_out,
						dbo.tbl_bahanpenolong_out.uom,
						dbo.tbl_bahanpenolong_out.doc_no,
						dbo.tbl_bahanpenolong_out.doc_date,
						dbo.tbl_bahanpenolong_out.doc_out_to,
						dbo.tbl_bahanpenolong_out.price,
						dbo.tbl_bahanpenolong_out.status_data,
						dbo.tbl_bahanpenolong_out.id_memo_bp,
						dbo.tbl_bahanpenolong_out.hs_kode,
						dbo.tbl_bahanpenolong_out.jmkemas,
						dbo.tbl_bahanpenolong_out.jnkemas,
						dbo.tbl_bahanpenolong_out.netto
					
					
					) VALUES (
						'$part_no'
						,'$part_name'
						,$qty
						,$qty
						,'$uom'
						,@nomor_memo
						,@tgl_memo
						,3
						,$price
						,'NEW'
						,$id_memo
						,'$hs_code'
						,$jmkemas
						,'$jnkemas'
						,$netto
					)
				set @id_bp_out_dtl = SCOPE_IDENTITY() 	
				end
				
				if @command = 'UPDATE'
				begin
					update tbl_bahanpenolong_out set 
						dbo.tbl_bahanpenolong_out.part_no='$part_no'
						,dbo.tbl_bahanpenolong_out.part_name='$part_name'
						,dbo.tbl_bahanpenolong_out.qty=$qty
						,dbo.tbl_bahanpenolong_out.qty_out=$qty
						,dbo.tbl_bahanpenolong_out.uom='$uom'
						,dbo.tbl_bahanpenolong_out.price=$price
						,dbo.tbl_bahanpenolong_out.hs_kode='$hs_code'
						,dbo.tbl_bahanpenolong_out.jmkemas=$jmkemas
						,dbo.tbl_bahanpenolong_out.jnkemas='$jnkemas'
						,dbo.tbl_bahanpenolong_out.netto=$netto
					where id_memo_bp =  $id_memo and id_bp_out_dtl = $id_bp_out_dtl and doc_out_to = 3
				end
				
				if @command = 'DELETE'
				begin
					delete from tbl_bahanpenolong_out where id_memo_bp =  $id_memo and id_bp_out_dtl = $id_bp_out_dtl and doc_out_to = 3
				end
				declare @nilinv decimal(38,4)
				set @nilinv = (select round(sum(qty * price), 2) from dbo.tbl_bahanpenolong_out where id_memo_bp =  $id_memo and doc_out_to = 3)
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
				,CONVERT(varchar, @id_bp_out_dtl) as id_bp_out_dtl
				,CONVERT(varchar, @nilinv) as nilinv
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ', 'id_bp_out_dtl' => $row['id_bp_out_dtl'], 'nilinv' => $row['nilinv']);
		 }  
		 echo json_encode($responce);
		
		
	}
	
	
	function update_memo_exim(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param  id_memoTidak Ditemukan"}');
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		$status_data = (isset($_POST['status_data']) && !empty($_POST['status_data']))?$_POST['status_data']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		
		
		$qry = $this->db->query("
			
			
			BEGIN TRY
				update tbl_bahanpenolong_memo set
				status_data = '$status_data'
				where id_memo = $id_memo
				
				if '$status_data' =  'PROSESEXIM'
				begin
					update tbl_bahanpenolong_out set
					status_data = 'APPROVED'
					where id_memo_bp = $id_memo and doc_out_to = 3
				end	 
				if '$status_data' =  'NEW'
				begin
					update tbl_bahanpenolong_out set
					status_data = 'NEW'
					where id_memo_bp = $id_memo and doc_out_to = 3
				end	 
				
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
				,CONVERT(varchar, $id_memo) as id_memo
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ', 'id_memo' => $row['id_memo']);
		 }  
		 echo json_encode($responce);
		
		
	}
	
	function data_bahanpenolong_out_memo(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_bp_out_dtl'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		$doc_out_to = isset($_POST['doc_out_to'])?$_POST['doc_out_to']:die();
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:'0';
		$where = " doc_out_to=3 and  id_memo_bp=$id_memo ";
		
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "no_invoice" ) {
						$searchString = $k->data;
						$where .= " and no_invoice like  '%".$searchString."%'"; 
					} else if ( $k->field == "tgl_invoice" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[tgl_invoice],126)  =  '$searchString'"; 
					} else if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					}  else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					}  else if ( $k->field == "doc_no" ) {
						$searchString = $k->data;
						$where .= " and doc_no like  '%".$searchString."%'"; 
					}  else if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					}  else if ( $k->field == "car" ) {
						$searchString = $k->data;
						$where .= " and car like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_bahanpenolong_outAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_bahanpenolong_outcountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_bp_out_dtl']=$r->id_bp_out_dtl;
			$responce->rows[$i]['container_number']=$r->container_number;
			$responce->rows[$i]['no_invoice']=$r->no_invoice;
			$responce->rows[$i]['tgl_invoice']=$r->tgl_invoice;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['qty']=$r->qty;
			$responce->rows[$i]['qty_out']=$r->qty_out;
			$responce->rows[$i]['uom']=$r->uom;
			$responce->rows[$i]['doc_no']=$r->doc_no;
			$responce->rows[$i]['doc_date']=$r->doc_date;
			$responce->rows[$i]['doc_out_to']=$r->doc_out_to;
			$responce->rows[$i]['filename']=$r->filename;
			$responce->rows[$i]['car']=$r->car;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			$responce->rows[$i]['approved_date']=$r->approved_date;
			$responce->rows[$i]['price']=$r->price;
			$responce->rows[$i]['status_data']=$r->status_data;
			$responce->rows[$i]['kode_buyer']=$r->kode_buyer;
			$responce->rows[$i]['nama_buyer']=$r->nama_buyer;
			$responce->rows[$i]['id_memo_bp']=$r->id_memo_bp;
			$responce->rows[$i]['bruto']=$r->bruto;
			$responce->rows[$i]['hs_kode']=$r->hs_kode;
			$responce->rows[$i]['jmkemas']=$r->jmkemas;
			$responce->rows[$i]['jnkemas']=$r->jnkemas;
			$responce->rows[$i]['netto']=$r->netto;
			$responce->rows[$i]['hargaxqty']=(float)$r->qty * (float)$r->price;	
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function view_bahanpenolong_memo_exim_bc27(){
		$data['bruto'] = '';
		$this->load->view('settings/view_bahanpenolong_memo_exim_bc27', $data);
		
	}
	function view_bahanpenolong_memo_exim_bc25(){
		$data['bruto'] = '';
		$this->load->view('settings/view_bahanpenolong_memo_exim_bc25', $data);
		
	}
	
	function view_bahanpenolong_memo_scrap(){
		$data['bruto'] = '';
		$this->load->view('settings/view_bahanpenolong_memo_scrap', $data);
		
	}
	function view_bahanpenolong_memo_exim_bc41(){
		$data['bruto'] = '';
		$this->load->view('settings/view_bahanpenolong_memo_exim_bc41', $data);
		
	}
	
	function view_bahanpenolong_memo_exim_bc261(){
		$data['bruto'] = '';
		$this->load->view('settings/view_bahanpenolong_memo_exim_bc261', $data);
		
	}
	
	function update_memo_scrap_bahanpenolong(){
		$id_memo_bp = (isset($_POST['id_memo_bp']) && !empty($_POST['id_memo_bp']))?$_POST['id_memo_bp']:die('{"sts":"ERROR","desc":" Param  id_memo Tidak Ditemukan"}');
		$id_bp_out_dtl = (isset($_POST['id_bp_out_dtl']) && !empty($_POST['id_bp_out_dtl']))?$_POST['id_bp_out_dtl']:die('{"sts":"ERROR","desc":" Param  id_bp_out_dtl Tidak Ditemukan"}');
		$part_no = (isset($_POST['part_no']) && !empty($_POST['part_no']))?$_POST['part_no']:die('{"sts":"ERROR","desc":" Param  part_no Tidak Ditemukan"}');
		$part_name = (isset($_POST['part_name']) && !empty($_POST['part_name']))?$_POST['part_name']:die('{"sts":"ERROR","desc":" Param  part_name Tidak Ditemukan"}');
		$qty = (isset($_POST['qty_scrap']) && !empty($_POST['qty_scrap']))?$_POST['qty_scrap']:die('{"sts":"ERROR","desc":" Param  qty Tidak Ditemukan"}');
		$jmkemas = (isset($_POST['jmkemas_scrap']) && !empty($_POST['jmkemas_scrap']))?$_POST['jmkemas_scrap']:die('{"sts":"ERROR","desc":" Param  jmkemas Tidak Ditemukan"}');
		$jnkemas = (isset($_POST['jnkemas_scrap']) && !empty($_POST['jnkemas_scrap']))?$_POST['jnkemas_scrap']:die('{"sts":"ERROR","desc":" Param  jnkemas Tidak Ditemukan"}');
		$netto_scrap = (isset($_POST['netto_scrap']) && !empty($_POST['netto_scrap']))?$_POST['netto_scrap']:die('{"sts":"ERROR","desc":" Param  netto_scrap Tidak Ditemukan"}');
		$bruto_scrap = (isset($_POST['bruto_scrap']) && !empty($_POST['bruto_scrap']))?$_POST['bruto_scrap']:die('{"sts":"ERROR","desc":" Param  bruto_scrap Tidak Ditemukan"}');
		$harga_scrap = (isset($_POST['harga_scrap']) && !empty($_POST['harga_scrap']))?$_POST['harga_scrap']:die('{"sts":"ERROR","desc":" Param  harga_scrap Tidak Ditemukan"}');
		
	
		$username = $this->session->userdata('DX_username');
		
		$q = $this->db->query("
			BEGIN TRY
				BEGIN TRANSACTION
			if (select count(*) from tbl_bahanpenolong_memo_scrap where id_memo = $id_memo_bp and id_bp_out_dtl= $id_bp_out_dtl) = 0
			begin
				
				insert into tbl_bahanpenolong_memo_scrap (
						
						dbo.tbl_bahanpenolong_memo_scrap.id_memo,
						dbo.tbl_bahanpenolong_memo_scrap.id_bp_out_dtl,
						dbo.tbl_bahanpenolong_memo_scrap.kode_scrap,
						dbo.tbl_bahanpenolong_memo_scrap.nama_scrap,
						dbo.tbl_bahanpenolong_memo_scrap.qty_scrap,
						dbo.tbl_bahanpenolong_memo_scrap.satuan,
						dbo.tbl_bahanpenolong_memo_scrap.bruto_scrap,
						dbo.tbl_bahanpenolong_memo_scrap.harga_scrap,
						dbo.tbl_bahanpenolong_memo_scrap.jmkemas_scrap,
						dbo.tbl_bahanpenolong_memo_scrap.jnkemas_scrap,
						dbo.tbl_bahanpenolong_memo_scrap.netto_scrap
											
					
					) VALUES (
						$id_memo_bp
						,$id_bp_out_dtl
						,'$part_no'
						,'$part_name'
						,$qty
						,'KGM'
						,$bruto_scrap
						,$harga_scrap 
						,$jmkemas
						,'$jnkemas'
						,$netto_scrap
						
					)
			end	else 
			begin
				update tbl_bahanpenolong_memo_scrap set 
				dbo.tbl_bahanpenolong_memo_scrap.id_memo = $id_memo_bp	
				,dbo.tbl_bahanpenolong_memo_scrap.id_bp_out_dtl = $id_bp_out_dtl	
				,dbo.tbl_bahanpenolong_memo_scrap.kode_scrap = '$part_no'	
				,dbo.tbl_bahanpenolong_memo_scrap.nama_scrap = '$part_name'	
				,dbo.tbl_bahanpenolong_memo_scrap.qty_scrap = $qty	
				,dbo.tbl_bahanpenolong_memo_scrap.satuan = 'KGM'	
				,dbo.tbl_bahanpenolong_memo_scrap.bruto_scrap = $bruto_scrap	
				,dbo.tbl_bahanpenolong_memo_scrap.harga_scrap = $harga_scrap 	
				,dbo.tbl_bahanpenolong_memo_scrap.jmkemas_scrap = $jmkemas	
				,dbo.tbl_bahanpenolong_memo_scrap.jnkemas_scrap = '$jnkemas'	
				,dbo.tbl_bahanpenolong_memo_scrap.netto_scrap = $netto_scrap	
				where id_memo = $id_memo_bp and id_bp_out_dtl= $id_bp_out_dtl

			end
			COMMIT
			END TRY
			BEGIN CATCH
				-- Whoops, there was an error
				IF @@TRANCOUNT > 0
				 ROLLBACK
		-- Raise an error with the details of the exception
			DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
			Set @ErrMsg = ERROR_MESSAGE()
			set @ErrSeverity = ERROR_SEVERITY()
			select @ErrMsg as status,@ErrSeverity as description
			RAISERROR(@ErrMsg, @ErrSeverity, 1)
			END CATCH 	
			
			SELECT 
				'00' AS status
				,' SUKSES' AS description
				
					
		
		");
		
		
		$rs = $q->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description']);
		 }  
		 echo json_encode($responce);
		
		
	}
	
	function downloadcsvst_mutasi_perpart(){
		ini_set('memory_limit', '1024M');
		
		
		$tglawal = (isset($_GET['tglawal']) && !empty($_GET['tglawal']))?$_GET['tglawal']:die('{"sts":"ERROR","desc":" idhdrbcst Param Tidak Ditemukan"}');
		$tglakhir = (isset($_GET['tglakhir']) && !empty($_GET['tglakhir']))?$_GET['tglakhir']:die('{"sts":"ERROR","desc":" idhdrbcst Param Tidak Ditemukan"}');
		
		
		$this->db->query("
		
			SET ANSI_NULLS ON;  
			SET ANSI_WARNINGS ON;
		
		");
		
		 $qry = $this->db->query("
			select * from [f_mutasi_bp]('$tglawal','$tglakhir','BP') 
			-- where qty_saldoawal + qty_in + qty_out + saldo_akhir <> 0
		 ");
		
		
		include_once ( APPPATH."libraries/PHPExcel.php");	
		$phpExcel = new PHPExcel();
		
		$phpExcel->setActiveSheetIndex(0);
		$phpExcel->getActiveSheet()->setTitle('Stock');
		$phpExcel->getActiveSheet()->setCellValue('A1', 'PERIODE: ' . $tglawal . ' S/D ' . $tglakhir); 
		$phpExcel->getActiveSheet()->setCellValue('A2', 'PART NO'); 
		$phpExcel->getActiveSheet()->setCellValue('B2', 'PART NAME CUSTOMS');
		$phpExcel->getActiveSheet()->setCellValue('C2', 'SALDO AWAL');
		$phpExcel->getActiveSheet()->setCellValue('D2', 'PEMASUKAN');
		$phpExcel->getActiveSheet()->setCellValue('E2', 'PENGELUARAN');
		$phpExcel->getActiveSheet()->setCellValue('F2', 'SALDO AKHIR');
		$phpExcel->getActiveSheet()->setCellValue('G2', 'STO');
		$phpExcel->getActiveSheet()->setCellValue('H2', 'ADJUSTMENT');
		$counter=3;
		foreach ($qry->result() as $row){
			$phpExcel->getActiveSheet()->setCellValueExplicit("A".$counter, $row->part_no, PHPExcel_Cell_DataType::TYPE_STRING); 
			$phpExcel->getActiveSheet()->setCellValueExplicit("B".$counter, $row->part_name, PHPExcel_Cell_DataType::TYPE_STRING); 
			$phpExcel->getActiveSheet()->setCellValue("C".$counter, $row->stock_awal); 
			$phpExcel->getActiveSheet()->setCellValue("D".$counter, $row->qty_in); 
			$phpExcel->getActiveSheet()->setCellValue("E".$counter, $row->qty_out); 
			$phpExcel->getActiveSheet()->setCellValue("F".$counter, $row->sisa_by_date); 
			$phpExcel->getActiveSheet()->setCellValue("G".$counter, $row->stock_opname); 
			$phpExcel->getActiveSheet()->setCellValue("H".$counter, $row->adj); 
			
			$counter = $counter+1;
		}
		
		
		
		$filename='mutasi_perpart'. date('Y-m-d') .'.xls';
		header('Content-Type: application/vnd.ms-excel'); 
		header('Content-Disposition: attachment;filename="'.$filename.'"'); 
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($phpExcel, 'Excel5');
		$objWriter->save('php://output');
		
		die();
		/* 
		$data1 = array("PART NO| PART NAME CUSTOMS| SALDO AWAL| PEMASUKAN| PENGELUARAN| SALDO AKHIR");
		$kode_brg = "";
		foreach ($rs as $row){
			if(is_numeric($row['kodebarang'])){
				$kode_brg = '"' . $row['kodebarang'] . '"';
			} else {
				$kode_brg = $row['kodebarang'];
			}
			$data1[] = $kode_brg . "|" . $row['namabarang'] . "|" .  $row['qty_saldoawal'] . "|" . $row['qty_in'] . "|" . $row['qty_out'] . "|"  .  $row['saldo_akhir'] ;
		}
		//$result = array_merge($data, $data1);
		$result = $data1;		
		header('Content-Type: application/excel');
		header('Content-Disposition: attachment; filename="datainout.csv"');
		
		$fp = fopen('php://output', 'w');
		foreach ( $result as $line ) {
			$val = explode("|", $line);
			fputcsv($fp, $val);
		}
		fclose($fp);
		*/
	}
	
 }
 
 
 /*  function loaddatax(){; 
		$def_col= array();    
		$spt='dbo.sp_data_penolong'; 
		$def_col['rID']=array("db" => "rID" ,"sc" => "rID","ctype"=>"int", "bypassvalue"=>"");
		$def_col['r1']=array("db" => "r1" ,"sc" => "r1","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r2']=array("db" => "r2" ,"sc" => "r2","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r3']=array("db" => "r3" ,"sc" => "r3","ctype"=>"date", "bypassvalue"=>"");
		$def_col['r4']=array("db" => "r4" ,"sc" => "r4","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r5']=array("db" => "r5" ,"sc" => "r5","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r6']=array("db" => "r6" ,"sc" => "r6","ctype"=>"int", "bypassvalue"=>"");
		$def_col['r7']=array("db" => "r7" ,"sc" => "r7","ctype"=>"int", "bypassvalue"=>"");
		$def_col['r8']=array("db" => "r8" ,"sc" => "r8","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r9']=array("db" => "r9" ,"sc" => "r9","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r10']=array("db" => "r10" ,"sc" => "r10","ctype"=>"date", "bypassvalue"=>"");
		$def_col['r11']=array("db" => "r11" ,"sc" => "r11","ctype"=>"int", "bypassvalue"=>"");
		$def_col['r12']=array("db" => "r12" ,"sc" => "r12","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r13']=array("db" => "r13" ,"sc" => "r13","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r14']=array("db" => "r14" ,"sc" => "r14","ctype"=>"date", "bypassvalue"=>"");
		$def_col['r15']=array("db" => "r15" ,"sc" => "r15","ctype"=>"text", "bypassvalue"=>"");
		$def_col['r16']=array("db" => "r16" ,"sc" => "r16","ctype"=>"date", "bypassvalue"=>"");
		$def_col['r17']=array("db" => "r17" ,"sc" => "r17","ctype"=>"text", "bypassvalue"=>"");
		
 		$search = isset($_POST['_search'])?$_POST['_search']:false; 
		$searchField = isset($_POST['searchField'])?$_POST['searchField']:''; 
		$searchString = isset($_POST['searchString'])?$_POST['searchString']:''; 
		$filters =  isset($_POST['filters'])?$_POST['filters']:''; 
	 	 
        $page = isset($_POST['page'])?$_POST['page']:1; // get the requested page 
		$limit = isset($_POST['rows'])?$_POST['rows']:10; // get how many rows we want to have into the grid 
		$sidx = isset($_POST['sidx'])?$_POST['sidx']:'rID'; // get index row - i.e. user click to sort 
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction 
		
		$rstart = isset($_POST['rstart'])?$_POST['rstart']:date('Ymd');		
		$rend = isset($_POST['rend'])?$_POST['rend']:date('Ymd');	
		
		if ($sord == 'asc') { $sord = '0'; } else if ($sord == 'desc') { $sord = '1'; } 
 		 
		if (array_key_exists($sidx, $def_col)) {  
				$fsidx=$def_col[$sidx];
				$sidx=$fsidx['db'];
		}else{
				$sidx='rID'; //DEFAULT SORT KALU GA ADA
		}
        $sidx=$sidx.'='. $sord;
		  
		$xmldoc =  XMLbasic($spt); 
		paramViewJSON($xmldoc, $limit, $page,  $sidx, $sord); 
  	//	AddField($xmldoc ,'ms_type_id',$ms_type_id); 
		AddField($xmldoc ,'rstart',$rstart); 
		AddField($xmldoc ,'rend',$rend); 
		 
        if ($search == 'true'){ 
            if (!empty($filters)){ 
				$array = json_decode($filters); 
                foreach($array->rules as $arr=>$k){ 
						$fcr=$def_col[$k->field]; 
	 					if ($fcr != null) 
						{ 
							if ($fcr['ctype']=='int'){ 
								$searchString = $k->data; 
								if ($searchString!=$fcr['bypassvalue'])  
									addSearchNum($xmldoc,$fcr['sc'],$searchString,'2','1');  
			 					  
							} 
							elseif ($fcr['ctype']=='text'){ 
					        	$searchString = $k->data; 
								if ($searchString!=$fcr['bypassvalue']) 
							     addSearchText($xmldoc,$fcr['sc'],'1','1',$searchString); 
							}  
							elseif ($fcr['ctype']=='date'){ 
								$searchString = $k->data; 
								if (trim($searchString) != '' ){ 
									$dateArray=explode('/',$searchString);  
									$searchString = $dateArray[2].$dateArray[1].$dateArray[0]; 
								} 
								 addSearchDate($xmldoc,$fcr['sc'],$searchString,'1','1'); 
							}  
						} 
                 } 
             } 
	   }  
  
  
		$str = $xmldoc->saveXML();   
		//print_r($str); die();
		wh_exec_sp_json($xmldoc, $spt,$sts,$des,$rows,$detail);  
			print_r($des); die();
  		echo $rows; 
	} */
	