<?php
Class CT_uploadbrg 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->helper(array('url', 'form'));
	    $this->load->library(array('session', 'encrypt'));
		$this->load->model("pasi_upload/mdl_upload", 'pasi_mdl_upload');
		$this->db_pasi =$this->load->database('pasi', TRUE);
	}
	function index(){

		$this->load->view('pasi_uploadmd/view_uploadbrg');
	}
	function view_uploadbrgdialog(){
	    $data['test'] = 'halo'; 
		$this->load->view('pasi_uploadmd/view_uploadbrgdialog',$data);
	}
	function upload_file_brg(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_brg';
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'MASTER_DATA';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'masterdata/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 500;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  //$config['allowed_types'] = '*.xls';
		
		  $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'];

				$file_name 	= $data['file_name'];
				
				$param_name = 'brg';
				$newfile=$apppath.'masterdata/logs/'.$data['file_name'];
				
				//echo "exec('cekfileupload @fileupload=''$myFile'',@username=''$username'',@filename=''$file_name'',@param=''$param_name''')";
				//die();
				
				$qry = $this->db_pasi->query("
				BEGIN TRY
					exec('sp_cek_file_upload @fileupload=''$myFile'',@username=''$username'',@filename=''$file_name'',@param=''$param_name''')
				END TRY
				BEGIN CATCH
					SELECT 
					'06' AS STATUS
					,ERROR_MESSAGE() AS DESCRIPTION;
				END CATCH
				
				");
				$rs = $qry->result_array();
				//$r = $qry->result();		
				//var_dump($rs);die();
				//'Data Standard Wire dan Tube tidak sesuai' 
				$status = '';
				
				foreach ($rs as $row){
					$status = $row['STATUS'];
					$deskripsi = $row['DESCRIPTION'];
				} 
				if ($status == '00') {
					$status = "Succes";
					$msg = $deskripsi;				
				} else {
					copy($myFile, $newfile);
					unlink($data['full_path']);
					$status = "Error";
					$msg = $deskripsi;		
				}
			 }
			 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 loaddatabrg(){
		$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_upload_brg'; // 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 == "status" ) {
						$searchString = $k->data;
						$where .= " and status  like  '%".$searchString."%'";
					} else if ( $k->field == "upload_by" ) {
						$searchString = $k->data;
						$where .= " and upload_by like  '%".$searchString."%'"; 
					}  else if ( $k->field == "upload_date" ) {
						$searchString = $k->data;
						$where .= " and upload_date =  '$searchString'";
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->pasi_mdl_upload->uploadbrg_all($limit,$start,$sidx,$sord, $where);
        $count = $this->pasi_mdl_upload->uploadbrg_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_upload_brg']=$r->id_upload_brg; 
			$responce->rows[$i]['file_name']=$r->file_name; 
			$responce->rows[$i]['file_path']=$r->file_path; 
			$responce->rows[$i]['status']=$r->status;
			$responce->rows[$i]['upload_by']=$r->upload_by;
			$responce->rows[$i]['upload_date']=$r->upload_date;
			
			$i++;
		}
		echo json_encode($responce);	
	}
	function deletefilebrg(){
		$file_name = (isset($_POST['file_name']) && !empty($_POST['file_name']))?$_POST['file_name']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_upload_brg = (isset($_POST['id_upload_brg']) && !empty($_POST['id_upload_brg']))?$_POST['id_upload_brg']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		
		$apppath = $this->config->item('APP_upload_path');
		
		$path=$apppath.'masterdata/'.$file_name;
		$pathnew=$apppath.'masterdata/logs/'.$file_name;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		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();
		}
		$param_name = 'brg';
		$qry = $this->db_pasi->query("
			BEGIN TRY
				exec('updatestatusdeletexls @file_name=''$file_name'',@id_upload=$id_upload_brg,@username=''$username'',@param=''$param_name''')
			END TRY
			BEGIN CATCH
				SELECT 
					'06' AS STATUS
					,'Data Master tidak sesuai' AS DESCRIPTION;
				END CATCH
				
				");
		$rs = $qry->result_array();
		//$r = $qry->result();		
		//var_dump($rs);die();
		foreach ($rs as $row){
			$status = $row['STATUS'];
			$deskripsi = $row['DESCRIPTION'];
		} 
		echo json_encode(array('status' => $status, 'desc' => $deskripsi));	
	}
	
}

?>