<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Discrepancy File handling
 *    
*/


require_once('sabreQMS.files.inc');


function discrepancy_add_file_form($form, $form_state, $discrepancy_id) {
	
	drupal_add_js( drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.drfiles.js');
	
	// get the dr_no
	$sql = "SELECT dr_no FROM {qms_discrepancy_log} d WHERE discrepancy_id = :did";
	$result = db_query($sql, array(':did' => $discrepancy_id));
	$dr_no = $result->fetchField();
										
	$form['dr_no_display'] = array(
		'#markup' => '<div>' . $dr_no . '</div><hr />',
	);
	
	// storage field for the discrepancy_id  -- hidden
	$form['discrepancy_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $discrepancy_id,
		'#attributes' => array('style' => array('display:none')),
	);
	
	// storage field for the dr_no  -- hidden
	$form['dr_no'] = array(
		'#type' => 'textfield',
		'#default_value' => $dr_no,
		'#attributes' => array('style' => array('display:none')),
	);
	
	$form['fs_files']['file_input_markup1'] = array(
		'#markup' =>'<table class="qms-file-input-table" style="width:95%"><tr><td class="qms-file-input-col1">',
	);
	
	
	$form['fs_files']['file_upload1'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
		'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #1'),
	);
	
	$form['fs_files']['clear_link1'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file1',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr><tr><td class="qms-file-input-col1">',			
	);
	

	$form['fs_files']['file_upload2'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
		'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #2'),
	);
	
	$form['fs_files']['clear_link2'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file2',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr><tr><td class="qms-file-input-col1">',			
	);
	

	$form['fs_files']['file_upload3'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
		'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #3'),
	);		
	
	$form['fs_files']['clear_link3'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file3',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr><tr><td class="qms-file-input-col1">',			
	);
		
	
	$form['fs_files']['file_upload4'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
		'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #4'),
	);
	
	$form['fs_files']['clear_link4'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file4',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr><tr><td class="qms-file-input-col1">',			
	);
	
	$form['fs_files']['file_upload5'] = array(
		'#type' => 'managed_file',
		'#progress_indicator' => 'bar',
		'#upload_validators' => array('file_validate_extensions' => array(QMS_VALID_FILE_UPLOAD_EXTENSIONS)),
		'#size' => 45,
		'#maxlength' => 255,
		'#title' => t('Attach File #5'),
	);		
	
	$form['fs_files']['clear_link5'] = array(
		'#markup' => l(t('Clear'), '', array('attributes' => array('id' => 'qms-clear-file5',
																																'class' => array('qms-clear-file')) ) ),
		'#prefix' => '</td><td class="qms-file-input-col2 ">',
		'#suffix' => '</td></tr></table>',			
	);
	
	
	
	$form['actions'] = array('#type' => 'actions');
	$form['actions']['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Submit',
		'#attributes' => array('id' => 'qms-file-btn-submit'),
	);
	
	$form['actions']['cancel'] = array(
		'#markup' => '&nbsp;&nbsp;&nbsp;' . l(t('Cancel'), 'discrepancy/edit/' . $discrepancy_id),
	);
	
	return $form;
}

/*
 *	discrepancy_add_file_form_submit()
 *
 *  implements hook_form_submit()
 */
function discrepancy_add_file_form_submit($form, $form_state) {
	
	/*
	 * private file directory handling by....http://www.beacon9.ca/labs/drupal-7-private-files-module
	 * create subdirectory in private file area specific to this discrepancy
	 * all files for this discrepancy will be physically stored in that directory with links
	 * entered in the database
	 */
	
	$discrepancy_id = (int) $form_state['values']['discrepancy_id'];
	$dr_no = $form_state['values']['dr_no'];
	
	
	// store files here
	// the directory name for each set of DR files is the DR No
	$dest_dir = _get_discrepancy_file_upload_directory($dr_no);
	
	//$file_list = array('file_upload1', 'file_upload2', 'file_upload3', 'file_upload4', 'file_upload5');
	$file_id_list = array(
			isset($form_state['values']['file_upload1']) ? $form_state['values']['file_upload1'] : 0, 
			isset($form_state['values']['file_upload2']) ? $form_state['values']['file_upload2'] : 0, 
			isset($form_state['values']['file_upload3']) ? $form_state['values']['file_upload3'] : 0, 
			isset($form_state['values']['file_upload4']) ? $form_state['values']['file_upload4'] : 0, 
			isset($form_state['values']['file_upload5']) ? $form_state['values']['file_upload5'] : 0, 
	);
	
	$error_files = array();
	$added = 0;
	$msg = '';

	if ( _attach_files_ajax($file_id_list, $dest_dir, 'qms_discrepancy_files', 'discrepancy_id', 
											$discrepancy_id, $error_files, $added ) ) {
		
		if ( $added ) {								
			$num_rows = db_update('qms_discrepancy_log')
						->fields(array('files_attached' => 1))
						->condition('discrepancy_id', $discrepancy_id)
						->execute();
		}			
		$msg = 'Files for ' . $dr_no . ' have been successfully uploaded.';
	}
	else {
		$msg = 'Oops!  An error occurred while attempting to add files.  ';
		$msg .= _list_files('Unable to attach: ', $error_files);
	}
	drupal_set_message(t($msg));		
	drupal_goto('discrepancy/edit/' . $discrepancy_id);  
}




/*
 *	discrepancy_file_download()
 *
 *  implements hook_file_download()
 */

function discrepancy_file_download($file_id) {
	
	if ( user_access('add discrepancy files') == FALSE &&
				user_access('administer sabreQMS') == FALSE ) {
		drupal_set_message(t('Unauthorized access.  Unable to access file.'));
		return;
	}

	$drfile = array();
	
	$sql = "SELECT f.file_uri, f.file_name, d.discrepancy_id, d.dr_no " .
				 "FROM {qms_discrepancy_files} f, {qms_discrepancy_log} d " .
					"WHERE f.discrepancy_id = d.discrepancy_id AND f.file_id = :fid";
	$results = db_query($sql, array(':fid' => $file_id));
	if ( !$results->rowCount() ) {
		drupal_set_message(t('Oops!  Something went wrong.  Unable to find file.'));
		return;		
	}
	$drfile = $results->fetchObject();
	
	// use the local file path, not the file URI which is saved in the table

	$base_file_path = variable_get('file_private_path', 'sites/default/files/private' ) . '/';
	$file_path = $base_file_path . $drfile->dr_no . '/' . $drfile->file_name;
	
	_st_return_requested_file($file_path);
}


/*
 *	discrepancy_file_delete_callback()
 *
 *  AJAX call from the browser, deletes file by file_id
 */

function discrepancy_file_delete_callback($file_id) {
	
	$file_rec = (object) Null;
	
	$delete = (user_access('administer sabreQMS') || user_access('delete discrepancy files'));
	
	if ( $delete ) {	

		// find the file the user wants to delete
		$sql = "SELECT file_uri, discrepancy_id FROM {qms_discrepancy_files} WHERE file_id = :fid";				
		$result = db_query($sql, array(':fid' => $file_id));
		
		if ( $result->rowCount() ) {
			
			$file_rec = $result->fetchObject();
			
			// how many files are linked to this discrepancy
			$result = db_query("SELECT file_id FROM {qms_discrepancy_files} WHERE discrepancy_id = :did",
													array(':did' => $file_rec->discrepancy_id));
			if ( $result->rowCount() <= 1) {
				// after we delete this file, there will be 
				// no more files attached this discrepancy, delete the dr's files dir and unset record flag
				$num_rows = db_update('qms_discrepancy_log')
							->fields(array(
												'files_attached' => 0,
												'updated_date' => time(),
											))
							->condition('discrepancy_id', $file_rec->discrepancy_id)
							->execute();
			}
			
			_delete_attached_file($file_rec->file_uri);  
			
			$num_rows = db_delete('qms_discrepancy_files')
											->condition('file_id', $file_id)
											->execute();						
		}
	}
	
  $content = _get_discrepancy_files_table($file_rec->discrepancy_id);
	die($content);
}


/*
 *	discrepancy_files_table_refresh_callback()
 *
 *	refreshes and reformats the files table
 */

function discrepancy_files_table_refresh_callback() {
	
	$discrepancy_id = (int)$_POST['discrepancy_id'];
	$content = _get_discrepancy_files_table($file_rec->discrepancy_id);
	die($content);
}


/*
 *	_get_discrepancy_files_table()
 *
 *	refreshes and reformats the files table
 */

function _get_discrepancy_files_table($discrepancy_id, $view_only = False)  {
	
	$content = '';
	
	$files = _get_discrepancy_files($discrepancy_id);		
	
	if ( $view_only && !count($files) ) {
		// there are no files and it's view only, return nothing
		return $content;
	}
		
	$admin = user_access('administer sabreQMS');
	$delete = user_access('delete discrepancy files');
	
	$table_rows = array();
	$table_headers = array(array('data' => 'Files', 'class' => 'qms-files-tbl-col1'),
												 array('data' => 'Uploaded By', 'class' => 'qms-files-tbl-col2'),
												);

	if ( !$view_only ) {
		// this only applies to editing 
		// new discrepancies will always have an Options col
		
		if ( $discrepancy_id && ( $admin || $delete ) )  {  
			$table_headers[] = array('data' => 'Options', 'class' => 'qms-files-tbl-col3');
		}
	}
		
	$i = 0;	
	foreach ( $files as $f ) {	
		$table_rows[] = array( 
      'data' => array( 
            l( t($f->file_name), 
               "discrepancy/file/download/" . $f->file_id, 
               array('attributes' => array('target'=>'_blank')) ), 
						$f->name . ' - ' . _st_format_date($f->uploaded_timestamp, 'short'),
			) );		
		if ( !$view_only && ($admin || $delete) ) {
			// admin can edit/delete comments, all done through ajax calls
			$table_rows[$i]['data'][] =  l( t('Delete'), "discrepancy/file/delete/" . $f->file_id, 
																			array('attributes' => array('class' => 'qms-discrepancy-file-delete') ) );
		}
		$i++;
	}	
	
	if ( $i == 0 ) {
			$table_rows = array('data' => array('None', ''));
			if ( $discrepancy_id && ( $admin || $delete ) )   {
				$table_rows['data'][] = '';
			}
	}							
	
	
	// refresh table
	$content = '<div id="qms-files-tbl-div">';
	$content .= theme( 'table', array(
		'header' => $table_headers,
		'rows' => $table_rows,
	));
	$content .= '</div>';
		
	return $content;
}


/*
 * _get_discrepancy_files($discrepancy_id)
 */
function _get_discrepancy_files($discrepancy_id) {
	
	if ( !$discrepancy_id ) {
		return array();
	}
	
	$sql = "SELECT f.file_id, u.name, f.uploaded_timestamp, f.file_uri, f.file_name 
					FROM {qms_discrepancy_files} f, {users} u WHERE f.discrepancy_id = :did 
					AND  f.user_id = u.uid  ORDER BY f.file_id";
	return db_query($sql, array(':did' => $discrepancy_id))->fetchAll();		
}


/*
 * _get_discrepancy_file_upload_directory($dr_no)
 * Returns the name of what the file upload directory should be for this discrepancy
 * Function exists to standardize the upload directory format
 */

function _get_discrepancy_file_upload_directory($dr_no) {
	return 'private://' . $dr_no;  
}



