<?php
class CT_invoice_bc40 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("exim/mdl_invoice", 'mdl_invoice');
	}
	  
	function index(){
		$data['test'] = 'test';
		$this->load->view('invoice/view_invoice_bc40', $data);
	}
	
	function view_invoice_bc40_upload(){
	
		$this->load->view('invoice/view_invoice_bc40_upload');
	
	}
	
	function loaddata(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_invoice_uploadbc40'; // 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 date_upload  =  '$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_invoicebc40All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_invoice->upload_invoicebc40countAll($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_invoice_uploadbc40']=$r->id_invoice_uploadbc40; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']= $r->filename; //str_replace(".xls","", $r->filename);  
			$responce->rows[$i]['filename2']= str_replace(".xls","", $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 upload_file_invoicebc40(){
		$status = "";
		$msg = "";
		$file_element_name = 'userfile_invoicebc40';
		//$username = $this->session->userdata('DX_user_id');
		$username = $this->session->userdata('DX_username');
		$tipe = 'INVBC40';
	    if ($status != "error")
	    {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'invoice/bc40/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 8;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'invoice/bc40/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$file_path = $data['file_path'];	
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_invoicebc40] @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();
				 $status = "success";
				 $msg = "File successfully uploaded";
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
			
				
			 }
			 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(){
		$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_invoice_uploadbc40 = (isset($_POST['id_invoice_uploadbc40']) && !empty($_POST['id_invoice_uploadbc40']))?$_POST['id_invoice_uploadbc40']: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.'invoice/bc40/'.$filename;
		$pathnew=$apppath.'invoice/bc40/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_invoicebc40] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_invoice_uploadbc40 ')
			
			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 cekxmlfile(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('File Kosong/Tidak Ditemukan');
		
	
	}
	
	function view_invoice_bc40_view(){
		$id_invoice_uploadbc40 = (isset($_POST['id_invoice_uploadbc40']) && !empty($_POST['id_invoice_uploadbc40']))?$_POST['id_invoice_uploadbc40']:die('{"sts":"ERROR","desc":" Param id_invoice_uploadbc40 Tidak Ditemukan"}');
		$data["id_invoice_uploadbc40"]= $id_invoice_uploadbc40;
		$this->load->view('invoice/view_invoice_bc40_view', $data);
	
	}
	
	
	function data_invoice_bc40_view(){
		
		$id_invoice_uploadbc40 = (isset($_POST['id_invoice_uploadbc40']) && !empty($_POST['id_invoice_uploadbc40']))?$_POST['id_invoice_uploadbc40']:die('{"sts":"ERROR","desc":" Param id_inv_hdr Tidak Ditemukan"}');
		
		$qry = $this->db->query("
			
			select filepath, filename  from [tbl_upload_invoicebc40] where  [id_invoice_uploadbc40]=$id_invoice_uploadbc40
			
		");
		
		$rs = $qry->result_array();	
/* 		var_dump($rs);
		die(); */
		$filepath = "";
		$filename = "";
		foreach ($rs as $row){
			$filepath = $row["filepath"];
			$filename = $row["filename"];
		}  	
		
		$datafile = $filepath . $filename;
		
		if( ! $xml = simplexml_load_file($datafile) )
		{
			echo 'unable to load XML file';
			die();
		} 
		
	 
		
		$i=0;
		
		foreach($xml->children() as $child)
	    {
			foreach($child->children() as $child1)
			{
				foreach($child1->children() as $child2)
				{
					foreach($child2->children() as $key)
					{
						$j=$i+1;
						$datajson->rows[$i]['NOMER']=$j;
						$datajson->rows[$i]['TAX']=(string)$key->TAX;
						$datajson->rows[$i]['PO_NO']=(string)$key->PO_NO;
						$datajson->rows[$i]['PO_DATE']=(string)$key->PO_DATE;
						$datajson->rows[$i]['RR_NO']=(string)$key->RR_NO;
						$datajson->rows[$i]['PART_NO']=(string)$key->PART_NO;
						$datajson->rows[$i]['PART_NAME']=(string)$key->PART_NAME;
						$datajson->rows[$i]['ORDER_QTY']=(string)$key->ORDER_QTY;
						$datajson->rows[$i]['UNIT']=(string)$key->UNIT;
						$datajson->rows[$i]['PRICE_UNIT']=(string)$key->PRICE_UNIT;
						$datajson->rows[$i]['DISC_AMT']=(string)$key->DISC_AMT;
						$datajson->rows[$i]['CS_NO']=(string)$key->CS_NO;
						$datajson->rows[$i]['CF_AMOUNT']=(string)$key->CF_AMOUNT;
												
						$i++;
						
					}
					
				}
				
			}
	    } 
		echo json_encode($datajson);
		//die(); 
		
	
	}

 }