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

	$delete_app_files = TRUE;
	global $file_upload_report;
	
if (checklogin($userID, "index.php")) {
	print_header();
	
	echo '
		<CENTER><A HREF="../apps/index.php">Go Back to Upload Page</A></CENTER>
		<br><br>
		';

	$spacer = '&nbsp; &nbsp; &nbsp; &nbsp;';
	$dataset_id = scrub_white_list($_POST['dataset_id'], 'NUMBERONLY');
	$audit_file_name = '';

	if ( ($_FILES["file"]["size"] < FILE_SIZE_LIMIT) && ($_FILES["file"]["size"] > 0) && ( 51 > strlen($_FILES['file']['name']))) {
	
		if ($_FILES["file"]["error"] > 0) {
			$msg = "Return Code: " . $_FILES["file"]["error"] . "<br />";
			$file_upload_report = $file_upload_report . $msg;
			echo $msg;
    		} else {

			$file_name = scrub_white_list($_FILES['file']['name'], 'FILE');
			$tmp_name  = $_FILES['file']['tmp_name'];
			$file_size = $_FILES['file']['size'];
			$file_type = $_FILES['file']['type'];

			$_SESSION['uniq_id'] = uniqid();
			$_SESSION['zip_file'] = $file_name;
			
			if ('Yes' == $process_file) {
			
				$tmp_work_dir = $file_upload_path . $_SESSION['uniq_id'] . '/';
			} else {
				$tmp_work_dir = $file_upload_path;
			}
			$tmp_work_unzip_dir = $tmp_work_dir . 'unzip/';
			
			$msg = '
				<table width=755 align="center">
				<tr class="va-section-header" width="550">
					<td colspan=2>&nbsp; File Validation </td>
				</tr>
				<tr>
					<td>
			';
			$msg = $msg . '<br><b>Step 1. File Upload </b><br><br>';
			$msg = $msg . 'File name: ' . $file_name . '<br />';
			$msg = $msg . 'File type: ' . $file_type . '<br />';
			$msg = $msg . 'File size: ' . ($file_size / 1024) . ' Kb<br />';
			
			$file_upload_report = $file_upload_report . $msg;
			echo $msg;

			if ( 'Yes' == $process_file && file_exists($tmp_work_dir . $file_name)) {
				$msg = $tmp_work_dir . $file_name . ' already exists. ';
				$file_upload_report = $file_upload_report . $msg;
				echo $msg;

			} else if ('Yes' == $process_file && !mkdir($tmp_work_dir, $tmp_dir_perm)) {
				$msg = 'mkdir failed for the path: '. $tmp_work_dir;
				$file_upload_report = $file_upload_report . $msg;
				echo $msg;

			} else {

				if ('Yes' == $process_file) {

				}
					if (!mkdir($tmp_work_unzip_dir, 0700)) {
                                		$msg = '<br> Creating work directory failed for the path: '. $tmp_work_unzip_dir . '<br>';
                                		$file_upload_report = $file_upload_report . $msg;
                                		echo $msg;
                        		}
                        		
                        		move_uploaded_file($tmp_name, $tmp_work_unzip_dir . $file_name);
                        		
                        		$msg = '<br><b>Step 2. Open file </b><br>';
                        		$file_upload_report = $file_upload_report . $msg;
                        		echo $msg;

					$validation_result = array();
					$validation_result['error']['error_count'] = 0;
					$validation_result['error']['rej_count'] = 0;
					$validation_result['error']['ack_count'] = 0;
					$validation_result['error']['error_msg'] = array();

					if (is_dir($tmp_work_unzip_dir)) {
						
						if ($dh = opendir($tmp_work_unzip_dir)) {
							$num = 0;
							$valid_file_count = 0;
							while ( ($file = readdir($dh)) !== false ) {
								if ( !(('.' == $file) || ('..' == $file)) ) {
									$num++;
									
									$msg = "File : $file <br>";
									$file_upload_report = $file_upload_report . $msg;
									echo $msg;
									
									$new_file_name =  strtolower (str_replace('_', '', $file));
									$validation_result["$new_file_name"]['rej_msg'] = array();
									$validation_result["$new_file_name"]['ack_msg'] = array();
									$validation_result["$new_file_name"]['error_msg'] = array();
									$file_names[0] = $file;
									
								}
							}
							closedir($dh);
						}
					}
					
					$valid_file_name_count = $valid_file_count = 1;
					
					if ($valid_file_name_count != $valid_file_count){
						
						for ($i=0; $i < $valid_file_name_count; $i++) {
							if ( empty($file_names[$i]) ) {
								$msg = '<br><font color="red"><b>Error: ' . $valid_file_names[$i] . ' file is missing. Please check and re-upload. ' . $valid_file_count . '</b></font>';
								$file_upload_report = $file_upload_report . $msg;
								echo $msg;
							}
						}
						
						delete_app_files($tmp_work_dir);
						
						if ( isset($_SESSION['uniq_id']) ) { 
							
						}
						
						if ( isset($_SESSION['zip_file']) ) { 
							
						}
						
						$msg = '<br><br><A HREF="apps/index.php">Return to Main Menu</A>';
						echo $msg;
			
						print_footer();
						Exit("Error: Missing required files.");
					}
					
					$msg = '<br><br><b>Step 3. Validate File</b><br>';
					$file_upload_report = $file_upload_report . $msg;
					echo $msg;
					
					
					for ($i=0; $i < $valid_file_name_count; $i++) {
					
						$num = $i + 1;
										
						$file_validator = new FileValidator($valid_file_names);
						$validation_result = $file_validator->validate($file_names[$i], $tmp_work_unzip_dir, $validation_result);
						
					}
				
					$tot_err_cnt = $validation_result['error']['error_count'];
					$tot_rej_cnt = $validation_result['error']['rej_count'];
					$tot_ack_cnt = $validation_result['error']['ack_count'];
					
					$msg = '<br><br>' . $spacer . '<b>[ Validation Result Summary ]</b><br>';
					$file_upload_report = $file_upload_report . $msg;
					echo $msg;
					
					$message = 'File validated: ' . $file_name;
					audit_log($userID, $message);
					
					if ( 0 == $tot_err_cnt && 0 == $tot_rej_cnt && 0 == $tot_ack_cnt ) {
						$msg = $spacer . '<b><font color=blue>No issues found. Click the button below to process uploaded data files. </font></b><br>';
						$file_upload_report = $file_upload_report . $msg;
						echo $msg;
						print_ajax_header();
						print_ajax_form($dataset_id);
						$delete_app_files = FALSE;
						
					} else {
						
						if ( 0 != $tot_err_cnt ) {
							$msg = $spacer . '<b><font color=red>' . $tot_err_cnt . ' file error(s) found.</font></b> File upload is rejected and removed from the server.<br>';
							$file_upload_report = $file_upload_report . $msg;
							echo $msg;
							
						}
						
						if ( 0 != $tot_rej_cnt ) {
							$msg = $spacer . '<b><font color=red>' . $tot_rej_cnt . ' rejection error(s) found.</font></b> File upload is rejected and removed from the server.<br>';
							$file_upload_report = $file_upload_report . $msg;
							echo $msg;
							
						}
						
						if ( 0 != $tot_ack_cnt ) {
							$msg = $spacer . '<b><font color=green>' . $tot_ack_cnt . ' acknowledgement error(s) found.</font></b><br>';
							$file_upload_report = $file_upload_report . $msg;
							echo $msg;
							
							if ( 0 == $tot_rej_cnt &&  0 == $tot_err_cnt) {
								$msg = $spacer . 'File upload requires your acknowledgement of these issues.';
								$file_upload_report = $file_upload_report . $msg;
								echo $msg;
								
								print_ajax_header();
								print_ajax_form($dataset_id);
								
								$delete_app_files = FALSE;
								
							}
						}
						
					}
										
      			}
    		}
  	} else {
  		if ( 50 < strlen($_FILES['file']['name'])) {
  			$msg = '<font color="red">File name is too long. Please make the file name shorter. (upto 50 chars)</font><br>' . $_FILES["file"]["name"];
  			$file_upload_report = $file_upload_report . $msg;
			echo $msg;
  		} else {
  			$msg = '<font color="red">Invalid file. Please check the correct file is selected. </font>' . $_FILES["file"]["type"];
  			$file_upload_report = $file_upload_report . $msg;
  			echo $msg;
  		}	
  		print_footer();
  		exit;
  	}	

  	if ($delete_app_files) {
  		delete_app_files($tmp_work_dir);
  	}
  	
  	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 "<p><b><font color=blue>NOTE:  To avoid error in upload, change field name 'commitment status' to 'parole date' <br> &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; with length of 8 and (format: YYYYMMDD), blanks allowed.</font></b><br>";
	
	echo '
		<br><CENTER><A HREF="../apps/index.php">Go Back to Upload Page</A> | <A HREF="javascript:window.print()">Print Page</A></CENTER>
		<br><br>
		
		';
	$headers = "To: $app_ra_email\n" . "From: Veterans Re-Entry Search Service <noreply@domain>\n" . "MIME-Version: 1.0\n" . "Content-type: text/html; charset=iso-8859-1";
	$html_msg = '<html><body>' . $file_upload_report . '</body></html>';
	mail("$app_ra_email", 'VRSS error report: ' . SERVER_ENV, $html_msg, $headers);
	capture_upload_report($userID,$file_upload_report);	

	print_footer();

}	
?>


