<?php
class CT_upload 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("exim/mdl_invoice", 'mdl_invoice');
		$this->load->helper('afunction');
	}
	
	function view_bc30_upload(){
		$this->load->view('exim/view_bc30_upload');
	
	}
	
	function view_bc30_upload_frm(){
		
		$this->load->view('exim/view_bc30_upload_frm');
	}
	
	function deletefile_bc30(){
		$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_bc30_upload = (isset($_POST['id_bc30_upload']) && !empty($_POST['id_bc30_upload']))?$_POST['id_bc30_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.'exim/bc30/'.$filename;
		$pathnew=$apppath.'exim/bc30/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_bc30] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_bc30_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_parths]') ";
		 // $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 upload_file_bc30(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfilebc30';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'BC30';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'exim/bc30/';
		  $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();
			 
			 // print_r($data);
			 // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'exim/bc30/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$file_path = $data['file_path'];		
				$row = 1;
				if (($handle = fopen($myFile, "r")) !== FALSE) {
					 $data = fgetcsv($handle, 1000, ",");
					 $num = count($data);
					 //var_dump($data);
					// while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
						// $num = count($data);
						// echo "$num \n";
						
					// }
					fclose($handle);
				}
				
				// echo $num.$myFile;
				// die();
				if ($num != 122){
					copy($myFile, $newfile);
					@unlink($myFile);
					echo json_encode(array('status' => 'error', 'msg' => "Data Tidak Sesuai, Mohon Cek Kembali Datanya"));
					die();
				
				}
				
				
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_bc30] @filepath=''$file_path'', @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_parths]') ";
				 // $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 data_uploadbc30(){
		$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_bc30_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_invoice->upload_bc30All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_invoice->upload_bc30countAll($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_bc30_upload']=$r->id_bc30_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;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function view_bc25_upload(){
		
		$this->load->view('exim/view_bc25_upload');
	
	
	}
	
	
	function deletefile_bc25(){
		$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_bc25_upload = (isset($_POST['id_bc25_upload']) && !empty($_POST['id_bc25_upload']))?$_POST['id_bc25_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.'exim/bc25/'.$filename;
		$pathnew=$apppath.'exim/bc25/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_bc25] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_bc25_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_parths]') ";
		 // $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 upload_file_bc25(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfilebc25';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'bc25';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'exim/bc25/';
		  $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();
			 
			 // print_r($data);
			 // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'exim/bc25/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$file_path = $data['file_path'];		
				$row = 1;
				$header = NULL;
				$data = array();
				
			    if (($handle = fopen($myFile, "r")) !== FALSE) {
					 //$data = fgetcsv($handle, 1000, ",");
					 //$num = count($data);
					 //var_dump($data);
					while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
						
						/* if(!$header){
							$header = $row; } */
												
						if ($row[0] == 'H0'){
							
							$data[] = $row;
						} else if ($row[0] == 'D0'){
						
							$data[] = $row;
						}
					 }
					fclose($handle);
				}
				
				
				$file_handle = fopen($myFile, "r");

				$i=0;
				$arr = array();
				while (!feof($file_handle)) {
				   $line = fgets($file_handle);
				   #echo $line ."<br>";
					if($i == 0){

						$line = trim($line) . " , F1 , F2 , F3, F4 ";
						$stringData = $line ."\n";
					} else {
						$stringData = $line;
					}

					$arr[$i] = $stringData;
					

					$i++;
				}


				fclose($file_handle);
				$fh = fopen($myFile, 'w') or die("can't open file");
				#print_r($arr);
				foreach ($arr as $value) {
					fwrite($fh, $value);
					#$value = $value * 2;
				}

				fclose($fh);
				//var_dump($data);
				//die();
				$num = count($data);
				
				//echo $num; die();
				if ($num != 2){
					copy($myFile, $newfile);
					@unlink($myFile);
					echo json_encode(array('status' => 'error', 'msg' => "Data Tidak Sesuai, Mohon Cek Kembali Datanya"));
					die();
				
				}
				
				
				$qry = $this->db->query("
				
					BEGIN TRY
					
					 exec('[spuload_bc25] @filepath=''$file_path'', @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_parths]') ";
				 // $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 data_uploadbc25(){
		$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_bc25_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_invoice->upload_bc25All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_invoice->upload_bc25countAll($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_bc25_upload']=$r->id_bc25_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;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	function view_bc25_upload_frm(){
		
		$this->load->view('exim/view_bc25_upload_frm');
	}
	
	function view_bc27_upload(){
		
		$this->load->view('exim/view_bc27_upload');
	}
	
	function view_bc27_upload_frm(){
		
		$this->load->view('exim/view_bc27_upload_frm');
	}
	
	function data_uploadbc27(){
		$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_bc27_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_invoice->upload_bc27All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_invoice->upload_bc27countAll($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_bc27_upload']=$r->id_bc27_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;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function deletefile_bc27(){
		$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_bc27_upload = (isset($_POST['id_bc27_upload']) && !empty($_POST['id_bc27_upload']))?$_POST['id_bc27_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.'exim/bc27/'.$filename;
		$pathnew=$apppath.'exim/bc27/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_bc27] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_bc27_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_parths]') ";
		 // $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 upload_file_bc27(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfilebc27';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'bc27';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'exim/bc27/';
		  $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();
			 
			 // print_r($data);
			 // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'exim/bc27/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$file_path = $data['file_path'];		
				$row = 1;
				if (($handle = fopen($myFile, "r")) !== FALSE) {
					 $data = fgetcsv($handle, 1000, ",");
					 $num = count($data);
					 //var_dump($data);
					// while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
						// $num = count($data);
						// echo "$num \n";
						
					// }
					fclose($handle);
				}
				
				// echo $num.$myFile;
				// die();
				if ($num != 117){
					copy($myFile, $newfile);
					@unlink($myFile);
					echo json_encode(array('status' => 'error', 'msg' => "Data Tidak Sesuai, Mohon Cek Kembali Datanya"));
					die();
				
				}
				
				
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_bc27] @filepath=''$file_path'', @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_parths]') ";
				 // $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 data_list_bc25(){
		$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_coo_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 == "file_name" ) {
						$searchString = $k->data;
						$where .= " and file_name like  '%".$searchString."%'"; 
					} else if ( $k->field == "datecreate" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[datecreate],101)  =  '$searchString'"; 
					} else if ( $k->field == "datanama" ) {
						$searchString = $k->data;
						$where .= " and datanama like  '%".$searchString."%'"; 
					}  else if ( $k->field == "datecreate" ) {
						$searchString = $k->data;
						$where .= " and datecreate like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$tipe = 'data';
		$folder = $this->config->item('bc25_folder'); 
		$ext = '*.csv';
		$records = $this->mdl_invoice->data_file_cooAll($limit,$start,$sidx,$sord, $where, $tipe, $folder,$ext);
        $count = $this->mdl_invoice->data_file_coocountAll($where, $tipe, $folder, $ext);
		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]['datanama']=$r->datanama; 
			$responce->rows[$i]['file_name']=$r->file_name; 
			$responce->rows[$i]['datanama2']= str_replace(array('.CSV','.csv','.xls','.XLS'),array('','','',''),$r->datanama); 
			$responce->rows[$i]['ukuran']=$r->ukuran; 
			$responce->rows[$i]['datecreate']=$r->datecreate; 
			
			$i++;
		}
		echo json_encode($responce);			
		
	}
	
	function proses_sync_bc25(){
		$file_name = (isset($_POST['file_name']) && !empty($_POST['file_name']))?$_POST['file_name']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datanama = (isset($_POST['datanama']) && !empty($_POST['datanama']))?$_POST['datanama']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datecreate = (isset($_POST['datecreate']) && !empty($_POST['datecreate']))?$_POST['datecreate']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$file_path_x = explode("\\",  $file_name) ;
		$file_path = str_replace('\\' . $file_path_x[count($file_path_x) - 1],'', $file_name);
		$tipe = 'bc25';
		$username = $this->session->userdata('DX_username');
		$bc25_path = $this->config->item('bc25_loader'); 
			
		$qry = $this->db->query("
			declare @res varchar(100)	
			BEGIN TRY
				set @res=(select dbo.[f_move_file]('$file_name','$bc25_path'+'\'+'$datanama')	)			
				exec('[spuload_bc25] @filepath=''$bc25_path'', @filename=''$datanama'', @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(array('sts' => $status, 'desc' => $msg));	

	}
	
	
	function data_list_bc27(){
		$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_coo_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 == "file_name" ) {
						$searchString = $k->data;
						$where .= " and file_name like  '%".$searchString."%'"; 
					} else if ( $k->field == "datecreate" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[datecreate],101)  =  '$searchString'"; 
					} else if ( $k->field == "datanama" ) {
						$searchString = $k->data;
						$where .= " and datanama like  '%".$searchString."%'"; 
					}  else if ( $k->field == "datecreate" ) {
						$searchString = $k->data;
						$where .= " and datecreate like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$tipe = 'data';
		$folder = $this->config->item('bc27_folder');
		$ext = '*.csv';
		$records = $this->mdl_invoice->data_file_cooAll($limit,$start,$sidx,$sord, $where, $tipe, $folder,$ext);
        $count = $this->mdl_invoice->data_file_coocountAll($where, $tipe, $folder, $ext);
		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]['datanama']=$r->datanama; 
			$responce->rows[$i]['file_name']=$r->file_name; 
			$responce->rows[$i]['datanama2']= str_replace(array('.CSV','.csv','.xls','.XLS'),array('','','',''),$r->datanama); 
			$responce->rows[$i]['ukuran']=$r->ukuran; 
			$responce->rows[$i]['datecreate']=$r->datecreate; 
			
			$i++;
		}
		echo json_encode($responce);			
		
	}
	
	function proses_sync_bc27(){
		$file_name = (isset($_POST['file_name']) && !empty($_POST['file_name']))?$_POST['file_name']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datanama = (isset($_POST['datanama']) && !empty($_POST['datanama']))?$_POST['datanama']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datecreate = (isset($_POST['datecreate']) && !empty($_POST['datecreate']))?$_POST['datecreate']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$file_path_x = explode("\\",  $file_name) ;
		$file_path = str_replace('\\' . $file_path_x[count($file_path_x) - 1],'', $file_name);
		$tipe = 'bc27';
		$username = $this->session->userdata('DX_username');
		$bc27_path = $this->config->item('bc27_loader'); 
			
		$qry = $this->db->query("
			declare @res varchar(100)	
			BEGIN TRY
				set @res=(select dbo.[f_move_file]('$file_name','$bc27_path'+'\'+'$datanama')	)			
				exec('[spuload_bc27] @filepath=''$bc27_path'', @filename=''$datanama'', @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(array('sts' => $status, 'desc' => $msg));	

	}
	
	
	function data_list_bc30(){
		$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_coo_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 == "file_name" ) {
						$searchString = $k->data;
						$where .= " and file_name like  '%".$searchString."%'"; 
					} else if ( $k->field == "datecreate" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[datecreate],101)  =  '$searchString'"; 
					} else if ( $k->field == "datanama" ) {
						$searchString = $k->data;
						$where .= " and datanama like  '%".$searchString."%'"; 
					}  else if ( $k->field == "datecreate" ) {
						$searchString = $k->data;
						$where .= " and datecreate like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$tipe = 'data';
		$folder = $this->config->item('bc30_folder');
		$ext = '*.csv';
		$records = $this->mdl_invoice->data_file_cooAll($limit,$start,$sidx,$sord, $where, $tipe, $folder,$ext);
        $count = $this->mdl_invoice->data_file_coocountAll($where, $tipe, $folder, $ext);
		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]['datanama']=$r->datanama; 
			$responce->rows[$i]['file_name']=$r->file_name; 
			$responce->rows[$i]['datanama2']= str_replace(array('.CSV','.csv','.xls','.XLS'),array('','','',''),$r->datanama); 
			$responce->rows[$i]['ukuran']=$r->ukuran; 
			$responce->rows[$i]['datecreate']=$r->datecreate; 
			
			$i++;
		}
		echo json_encode($responce);			
		
	}
	
	function proses_sync_bc30(){
		$file_name = (isset($_POST['file_name']) && !empty($_POST['file_name']))?$_POST['file_name']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datanama = (isset($_POST['datanama']) && !empty($_POST['datanama']))?$_POST['datanama']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datecreate = (isset($_POST['datecreate']) && !empty($_POST['datecreate']))?$_POST['datecreate']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$file_name_ori = $file_name;
		
		$file_path_x = explode("\\",  $file_name) ;
		$file_path = str_replace('\\' . $file_path_x[count($file_path_x) - 1],'', $file_name);
		$tipe = 'bc30';
		$username = $this->session->userdata('DX_username');
		$bc30_path = $this->config->item('bc30_loader'); 
		
		if (strpos($file_name,' ') > 0){
			$file_name = str_replace(' ','_',$file_name);
			$datanama = str_replace(' ','_',$datanama);
			rename($file_name_ori, str_replace(' ','_',$file_name))  ;
		}
			
		$qry = $this->db->query("
			declare @res varchar(100)	
			BEGIN TRY
				set @res=(select dbo.[f_move_file]('$file_name','$bc30_path'+'\'+'$datanama')	)			
				exec('[spuload_bc30] @filepath=''$bc30_path'', @filename=''$datanama'', @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(array('sts' => $status, 'desc' => $msg));	

	}
	
	function deletefile_sync_bc30(){
		$file_name = (isset($_POST['file_name']) && !empty($_POST['file_name']))?$_POST['file_name']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datanama = (isset($_POST['datanama']) && !empty($_POST['datanama']))?$_POST['datanama']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datecreate = (isset($_POST['datecreate']) && !empty($_POST['datecreate']))?$_POST['datecreate']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$file_path_x = explode("\\",  $file_name) ;
		
		$file_path = str_replace('\\' . $file_path_x[count($file_path_x) - 1],'', $file_name);
		
		$username = $this->session->userdata('DX_username');
		
		@unlink($file_name);
		
		$status = "00";
		$msg = "Deleted";
		
		echo json_encode(array('sts' => $status, 'desc' => $msg));	
		
		
	}
	
	
	
}
?>