<?php
class CT_stockopname extends CI_Controller{
	function __construct()
	{
	  parent::__construct();
		if (!$this->dx_auth->is_logged_in()) {
			redirect('');  
			die(); 
		}
		
		$uid = $this->session->userdata('DX_user_id');
		$uname = $this->session->userdata('DX_username');
		
		if(!permissionAuth(2) && $uid != RID){ 
			header('HTTP/1.1 401 Unauthorize');die('noaccess');
		} 
		
		$this->load->helper(array('url', 'form'));
	    $this->load->library(array('session', 'encrypt'));
		$this->load->model("settings/mdl_settings", 'mdl_settings');
		$this->load->model("inventory/mdl_inventory", 'mdl_inventory');
		
	}

	function index(){
	//   $data['query'] = $this->incomingitemAll->getAll();
	//$this->load->view('daily/input',$data);

		$this->load->view('inventory/view_stockopname');
	}
	function loaddatastokopname(){
		$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	
		
		$typebahan = (isset($_POST['typebahanx']) && !empty($_POST['typebahanx']))?$_POST['typebahanx']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
			
		$where = " 1=1 and typebahan='$typebahan' ";
		
		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_opname" ) {
						$searchString = $k->data;
						$where .= " and date_stock_opname = '$searchString'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_inventory->stok_opname_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_inventory->stok_opname_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_opname']=$r->id_stock_opname; 
			$responce->rows[$i]['date_stock_opname']=$r->date_stock_opname; 
			$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);
	
	
	}
	
	//-- stock opname proses
	function view_stockopname_bahanbaku(){
	
		$this->load->view('inventory/view_stockopname_bahanbaku');
	
	}
	
	function data_uploadstockopnamebahanbaku(){
		$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_stockopname_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 and tipe='STORM' ";
		
		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],103)  =  '$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_inventory->upload_stobahanbakuAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_inventory->upload_stobahanbakucountAll($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_stockopname_upload']=$r->id_stockopname_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$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;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function upload_file_stockopnamebahanbaku(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_stockopnamebahanbaku';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'STORM';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'inventory/stock_opname/bahan_baku/';
		  $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();
			 
			  // print_r($data);
			  // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'inventory/stock_opname/bahan_baku/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//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_stockopname] @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'];
				 }  
				//  echo json_encode($responce);
				 // $stmt = " exec('[spuload_stockawal_fg]') ";
				 // $qry = mssql_query($stmt); 
				 // $row = mssql_fetch_array($qry); 
				 // var_dump($row);die();
						 
				
				
				
				$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 deletefile_stockopnamebahanbaku(){
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_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');
		
		$path=$apppath.'inventory/stock_opname/bahan_baku/'.$filename;
		$pathnew=$apppath.'inventory/stock_opname/bahan_baku/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_stockopname] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_stockopname_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 cek_data_opname_bahanbaku(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'inventory/stock_opname/bahan_baku/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_stockopname_bahanbaku(){
	
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$typebahan = 'RM';
		/* echo "exec('spi_stock_awal @filename=''$filename'', @id_stockawal_upload=$id_stockawal_upload, @tipe=''$tipe'',  @username=''$username''  ')";
		die(); */
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_stock_opname_rm @filename=''$filename'', @id_stockopname_upload=$id_stockopname_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);
	}
	//-- bahanbaku end
	
	function view_stockopname_finishgood(){
	
		$this->load->view('inventory/view_stockopname_finishgood');
	
	}
	
	function data_uploadstockopnamefinishgood(){
		$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_stockopname_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 and tipe='STOFG' ";
		
		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],103)  =  '$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_inventory->upload_stobahanbakuAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_inventory->upload_stobahanbakucountAll($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_stockopname_upload']=$r->id_stockopname_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$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;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function upload_file_stockopnamefinishgood(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_stockopnamefinishgood';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'STOFG';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'inventory/stock_opname/bahan_jadi/';
		  $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();
			 
			  // print_r($data);
			  // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'inventory/stock_opname/bahan_jadi/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//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_stockopname] @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'];
				 }  
				//  echo json_encode($responce);
				 // $stmt = " exec('[spuload_stockawal_fg]') ";
				 // $qry = mssql_query($stmt); 
				 // $row = mssql_fetch_array($qry); 
				 // var_dump($row);die();
						 
				
				
				
				$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 deletefile_stockopnamefinishgood(){
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_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');
		
		$path=$apppath.'inventory/stock_opname/bahan_jadi/'.$filename;
		$pathnew=$apppath.'inventory/stock_opname/bahan_jadi/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_stockopname] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_stockopname_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 cek_data_opname_finishgood(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'inventory/stock_opname/bahan_jadi/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_stockopname_finishgood(){
	
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$typebahan = 'FG';
		/* echo "exec('spi_stock_awal @filename=''$filename'', @id_stockawal_upload=$id_stockawal_upload, @tipe=''$tipe'',  @username=''$username''  ')";
		die(); */
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_stock_opname_rm @filename=''$filename'', @id_stockopname_upload=$id_stockopname_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);
	}
	
	//--scrap
	function view_stockopname_sisa_scrap(){
	
		$this->load->view('inventory/view_stockopname_sisa_scrap');
	
	}
	
	function data_uploadstockopnamesisa_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_stockopname_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 and tipe='STOSS' ";
		
		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],103)  =  '$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_inventory->upload_stobahanbakuAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_inventory->upload_stobahanbakucountAll($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_stockopname_upload']=$r->id_stockopname_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$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;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function upload_file_stockopnamesisa_scrap(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_stockopnamesisa_scrap';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'STOSS';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'inventory/stock_opname/bahan_sisa_scrap/';
		  $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();
			 
			  // print_r($data);
			  // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'inventory/stock_opname/bahan_sisa_scrap/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//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_stockopname] @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'];
				 }  
				//  echo json_encode($responce);
				 // $stmt = " exec('[spuload_stockawal_fg]') ";
				 // $qry = mssql_query($stmt); 
				 // $row = mssql_fetch_array($qry); 
				 // var_dump($row);die();
						 
				
				
				
				$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 deletefile_stockopnamesisa_scrap(){
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_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');
		
		$path=$apppath.'inventory/stock_opname/bahan_sisa_scrap/'.$filename;
		$pathnew=$apppath.'inventory/stock_opname/bahan_sisa_scrap/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_stockopname] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_stockopname_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 cek_data_opname_sisa_scrap(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'inventory/stock_opname/bahan_sisa_scrap/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_stockopname_sisa_scrap(){
	
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$typebahan = 'SS';
		/* echo "exec('spi_stock_awal @filename=''$filename'', @id_stockawal_upload=$id_stockawal_upload, @tipe=''$tipe'',  @username=''$username''  ')";
		die(); */
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_stock_opname_rm @filename=''$filename'', @id_stockopname_upload=$id_stockopname_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);
	}
	
	//peralatan kantor
	
	function view_stockopname_mpk(){
		$this->load->view('inventory/view_stockopname_mpk');
	
	}
	
	function data_uploadstockopnamempk(){
		$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_stockopname_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 and tipe='STOMPK' ";
		
		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],103)  =  '$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_inventory->upload_stobahanbakuAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_inventory->upload_stobahanbakucountAll($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_stockopname_upload']=$r->id_stockopname_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$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;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function upload_file_stockopnamempk(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_stockopnamempk';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'STOMPK';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'inventory/stock_opname/bahan_mpk/';
		  $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();
			 
			  // print_r($data);
			  // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'inventory/stock_opname/bahan_mpk/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//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_stockopname] @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'];
				 }  
				//  echo json_encode($responce);
				 // $stmt = " exec('[spuload_stockawal_fg]') ";
				 // $qry = mssql_query($stmt); 
				 // $row = mssql_fetch_array($qry); 
				 // var_dump($row);die();
						 
				
				
				
				$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 deletefile_stockopnamempk(){
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_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');
		
		$path=$apppath.'inventory/stock_opname/bahan_mpk/'.$filename;
		$pathnew=$apppath.'inventory/stock_opname/bahan_mpk/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_stockopname] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_stockopname_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 cek_data_opname_mpk(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'inventory/stock_opname/bahan_mpk/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_stockopname_mpk(){
	
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$typebahan = 'MPK';
		/* echo "exec('spi_stock_awal @filename=''$filename'', @id_stockawal_upload=$id_stockawal_upload, @tipe=''$tipe'',  @username=''$username''  ')";
		die(); */
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_stock_opname_rm @filename=''$filename'', @id_stockopname_upload=$id_stockopname_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 delete_sto(){
		$idx  = (isset($_POST['idx']) && !empty($_POST['idx']))?trim($_POST['idx']):die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$typebahan  = (isset($_POST['typebahan']) && !empty($_POST['typebahan']))?trim($_POST['typebahan']):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("
			
			BEGIN TRY
				delete tbl_stock_opname where id_stock_opname = $idx and typebahan = '$typebahan'
			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);
		
	}	
	//----------------------------
	// end of stock mpk
	
	function data_uploadstockopnamebahanpenolong(){
		$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_stockopname_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 and tipe='STOBP' ";
		
		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],103)  =  '$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_inventory->upload_stobahanbakuAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_inventory->upload_stobahanbakucountAll($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_stockopname_upload']=$r->id_stockopname_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$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;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	
	function upload_file_stockopnamebahanpenolong(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_stockopnamebahanpenolong';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'STOBP';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'inventory/stock_opname/bahan_penolong/';
		  $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();
			 
			  // print_r($data);
			  // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'inventory/stock_opname/bahan_penolong/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//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_stockopname] @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'];
				 }  
				//  echo json_encode($responce);
				 // $stmt = " exec('[spuload_stockawal_fg]') ";
				 // $qry = mssql_query($stmt); 
				 // $row = mssql_fetch_array($qry); 
				 // var_dump($row);die();
						 
				
				
				
				$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 deletefile_stockopnamebahanpenolong(){
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_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');
		
		$path=$apppath.'inventory/stock_opname/bahan_penolong/'.$filename;
		$pathnew=$apppath.'inventory/stock_opname/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_stockopname] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_stockopname_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 cek_data_opname_bahanpenolong(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'inventory/stock_opname/bahan_penolong/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_stockopname_bahanpenolong(){
	
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$typebahan = 'BP';
		/* echo "exec('spi_stock_awal @filename=''$filename'', @id_stockawal_upload=$id_stockawal_upload, @tipe=''$tipe'',  @username=''$username''  ')";
		die(); */
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_stock_opname_rm @filename=''$filename'', @id_stockopname_upload=$id_stockopname_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);
	}
	//-- bahanpenolong end
	
	function data_uploadstockopnamealatkantor(){
		$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_stockopname_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 and tipe='STOAK' ";
		
		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],103)  =  '$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_inventory->upload_stobahanbakuAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_inventory->upload_stobahanbakucountAll($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_stockopname_upload']=$r->id_stockopname_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$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;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	
	function upload_file_stockopnamealatkantor(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_stockopnamealatkantor';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'STOAK';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'inventory/stock_opname/alat_kantor/';
		  $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();
			 
			  // print_r($data);
			  // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'inventory/stock_opname/alat_kantor/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//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_stockopname] @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'];
				 }  
				//  echo json_encode($responce);
				 // $stmt = " exec('[spuload_stockawal_fg]') ";
				 // $qry = mssql_query($stmt); 
				 // $row = mssql_fetch_array($qry); 
				 // var_dump($row);die();
						 
				
				
				
				$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 deletefile_stockopnamealatkantor(){
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_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');
		
		$path=$apppath.'inventory/stock_opname/alat_kantor/'.$filename;
		$pathnew=$apppath.'inventory/stock_opname/alat_kantor/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_stockopname] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_stockopname_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 cek_data_opname_alatkantor(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'inventory/stock_opname/alat_kantor/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_stockopname_alatkantor(){
	
		$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_stockopname_upload = (isset($_POST['id_stockopname_upload']) && !empty($_POST['id_stockopname_upload']))?$_POST['id_stockopname_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$typebahan = 'AK';
		/* echo "exec('spi_stock_awal @filename=''$filename'', @id_stockawal_upload=$id_stockawal_upload, @tipe=''$tipe'',  @username=''$username''  ')";
		die(); */
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_stock_opname_rm @filename=''$filename'', @id_stockopname_upload=$id_stockopname_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);
	}
	
	// end alat kantor
	
	
	
	
	
	

}

?>
