<?
	//require_once('../libs/config.php');
	include('../init.php');
	require_once('../libs/functions.php');

if (checklogin($userID, "../index.php")) {
	
	if ( 'insert' == $_GET['req'] ) {
		
		$file_id = scrub_sql(scrub_white_list($_SESSION['uniq_id'], 'ALPHANUMERICONLY'), 15);
		$user_id = scrub_sql(scrub_white_list($_SESSION['userID'], 'NUMBERONLY'), 9); 
		$zip_file_name = scrub_white_list($_SESSION['zip_file'], 'INTERNALLINK');
		$dataset_id = scrub_sql(scrub_white_list($_GET['dataset_id'], 'NUMBERONLY'), 9);
		$num_data = scrub_sql(scrub_white_list($_SESSION['num_data'], 'NUMBERONLY'), 9);
		$spacer = '&nbsp; &nbsp; &nbsp; &nbsp;';
		
		if (!is_numeric($user_id)) {
			echo 'Error. Invalid uldr: ' . $user_id;
			exit;
		}
		
		$tmp_work_dir = $file_upload_path . $file_id . '/';
		$tmp_work_unzip_dir = $tmp_work_dir . 'unzip/';
		global $db;
		echo '<br><br><b>Step 4. DB Insert </b>';
		$rs = $db->Execute("SELECT TOP 10 * FROM APP_Files ORDER BY ID ASC");
		$arr = $rs->GetArray();

		$zip_file_path = $tmp_work_unzip_dir . $zip_file_name;

		if (is_readable($zip_file_path)) {
			$fp = fopen($zip_file_path, 'r');
		} else {
			die ("<br><font color='red'>Error: File Open failed. </font>");
		}
		
		 $file_content = file_get_contents($zip_file_path) or die ("<br>File Get Contents failed.");
		$hex_file_content = scrub_sql(scrub_white_list(rtrim($file_content), 'DATA'));	//'0x'.bin2hex($file_content);
		$safe_zip_file_name = scrub_sql($zip_file_name, 50);

		fclose($fp);
		
		$sql = 'Insert Into APP_Files (file_id, user_id, cs_id, dataset_id, name, uploaded_file, num_data, file_type) Values (';
		$sql .= "'$file_id', '$user_id', '" . $_SESSION['cs_id'] . "', '$dataset_id', '$safe_zip_file_name', '$hex_file_content', '$num_data', 'CSV')";
				
		$rs_put_contents = file_put_contents('/usr/local/vrss_sql/' .  $file_id, $sql);
		
		if (FALSE == $rs_put_contents){
			$result = '<br><br>' . $spacer . '<font color="red"><b>File upload process Failed. Please contact administrator.</b></font>';
			$message = 'File upload failed ';
			audit_log($userID, $message);
		} else {
			$result = '<br><br>' . $spacer . '<font color="navy"><b>The upload was successful and the submitted file will be processed shortly.</b></font>';
			$message = 'File uploaded successfully ';
			audit_log($userID, $message);
		}
		
	} else {
		$result = 'Error. Invalid Request Type';
	}

  	if ( isset($_SESSION['uniq_id']) ) { 
		unset($_SESSION['uniq_id']);
		unset($uniq_id);
	}
	
	if ( isset($_SESSION['zip_file']) ) { 
		unset($_SESSION['zip_file']);
		unset($uniq_id);
	}
	
	echo $result;
	exit;
}
?>
