<?php
// $Id$


require_once('sabreQMS.files.inc');

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

function shift_log_add_file_form($form, $form_state, $shift_log_id) {
	
	drupal_add_js( drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.shiftlogfiles.js');
	
	// get the shift log info
	$sql = "SELECT datetime, employee_user_id FROM {qms_shift_log} s WHERE shift_log_id = :sid";
	$result = db_query($sql, array(':sid' => $shift_log_id));
	$shift_log = $result->fetchObject();
	
	$sl_title = _st_format_date($shift_log->datetime, 'short') . ' shift log entry by ' . 
							_get_user_name($shift_log->employee_user_id);
										
	$form['sl_display'] = array(
		'#markup' => '<div>' . $sl_title . '</div><hr />',
	);
	
	// storage field for the shift_log_id  -- hidden
	$form['shift_log_id'] = array(
		'#type' => 'textfield',
		'#default_value' => $shift_log_id,
		'#attributes' => array('class' => array('qms-hidden-field')),
	);
	
	// storage field for the shift log display  -- hidden
	$form['shift_log_title'] = array(
		'#type' => 'textfield',
		'#default_value' => $sl_title,
		'#attributes' => array('class' => array('qms-hidden-field')),
	);
	
	
	
	$form['fs_files'] = array(
		'#type' => 'fieldset',
		'#title' => t('Files To Attach'),
		'#collapsible' => False,
	);
	
	$form['fs_files']['file_input_markup1'] = array(
		'#markup' =>'<table class="qms-file-input-table"><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'),
		'#attributes' => array( 'id' => 'qms-file-upload2',
														'class' => array('qms-file-upload-input')),
		'#prefix' => '<tr><td class="qms-file-input-col1">',
		'#suffix' => '</td>',
	);
	
	$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'), 'shiftlog/edit/' . $shift_log_id),
	);
	
	return $form;
}

/*
 *	shift_log_add_file_form_submit()
 *
 *  implements hook_form_submit()
 */
function shift_log_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 shift_log
	 * all files for this shift_log will be physically stored in that directory with links
	 * entered in the database
	 */
	
	$shift_log_id = (int) $form_state['values']['shift_log_id'];
	$sl_title = $form_state['values']['shift_log_title'];
	
	// store files here
	// shift logs do not have unique display report numbers so we key by the table id
	$dest_dir = _get_shift_log_file_upload_directory($shift_log_id); 
	
	//$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_shift_log_files', 'shift_log_id', 
											$shift_log_id, $error_files, $added) ) {
		if ( $added )	 {									
			$num_rows = db_update('qms_shift_log')
						->fields(array('files_attached' => 1))
						->condition('shift_log_id', $shift_log_id)
						->execute();
		}			
		$msg = 'Files for the shift log entry 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));
		
	// if we're adding files through shift log edit this route, we have permissions 
	drupal_goto('shiftlog/edit/' . $shift_log_id);  
}




/*
 *	shift_log_file_download()
 *
 *  implements hook_file_download()
 */

function shift_log_file_download($file_id) {
	
	if ( user_access('search view reports') == FALSE ) {
		drupal_set_message(t('Unauthorized access.  Unable to access file.'));
		return;
	}

	$sql = "SELECT shift_log_id, file_uri, file_name 
					FROM {qms_shift_log_files} WHERE 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;		
	}
	$file_rec = $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 . 'SL' . $file_rec->shift_log_id . '/' . $file_rec->file_name;
	
	_st_return_requested_file($file_path);
}


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

function shift_log_file_delete_callback($file_id) {
	
	$file_rec = (object) Null;
	
	if ( user_access('administer sabreQMS') ) {	
		
		// find the file the user wants to delete
		$sql = "SELECT file_uri, shift_log_id FROM {qms_shift_log_files} f 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 shift log?
			$result = db_query("SELECT file_id FROM {qms_shift_log_files} WHERE shift_log_id = :sid",
														array(':sid' => $file_rec->shift_log_id));
														
			if ( $result->rowCount() <= 1 ) {
				// after we delete this file, there will be 
				// no more files attached to this shift log, delete the shiftlog's files dir and unset record flag
				
				$num_rows = db_update('qms_shift_log')
							->fields(array(
												'files_attached' => 0,
												'updated_date' => time(),
											))
							->condition('shift_log_id', $file_rec->shift_log_id)
							->execute();						
			}	
			
			_delete_attached_file($file_rec->file_uri);  
			
			// delete the shift log file from the db
			$num_rows = db_delete('qms_shift_log_files')
												->condition('file_id', $file_id)
												->execute();										
		}
	}
	
  $content = _get_shift_log_files_table($file_rec->shift_log_id);
	die($content);
}


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

function _get_shift_log_files_table($shift_log_id) {
	
	$bAdmin = user_access('administer sabreQMS');
	
	$table_headers = array(array('data' => 'Files', 'class' => 'qms-files-tbl-col1'),
												 array('data' => 'Uploaded By', 'class' => 'qms-files-tbl-col2'),
												);
	$table_rows = array();

	if ( $bAdmin  ) {
		$table_headers[] = array('data' => 'Options');
	}
	
	$results = _get_shift_log_files($shift_log_id);	
	
	$i = 0;	
	foreach ( $results as $f ) {	
		$table_rows[] = array( 
      'data' => array( 
          l( t($f->file_name), 
             "shiftlog/file/download/" . $f->file_id, 
             array('attributes' => array('target'=>'_blank')) ), 
						$f->name . ' - ' . _st_format_date($f->uploaded_timestamp, 'short'),
      ) );		
		if ( $bAdmin ) {
			// admin can edit/delete comments, all done through ajax calls
			$table_rows[$i]['data'][] =  l( t('Delete'), "shiftlog/file/delete/" . $f->file_id);
		}
		$i++;
	}	
	
	if ( $i == 0 ) {
			$table_rows = array('data' => array('None', ''));
			if ( $bAdmin ) {
				$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_shift_log_files($shift_log_id)
 */
function _get_shift_log_files($shift_log_id) {
	
	$sql = "SELECT f.file_id, u.name, f.uploaded_timestamp, f.file_uri, f.file_name
					FROM {qms_shift_log_files} f, {users} u WHERE f.shift_log_id = :sid 
					AND  f.user_id = u.uid  ORDER BY f.file_id";
	return db_query($sql, array(':sid' => $shift_log_id))->fetchAll();		
}

/*
 * _get_shift_log_file_upload_directory($shift_log_id)
 * Returns the name of what the file upload directory should be for this shift_log
 * Function exists to standardize the upload directory format
 * the directory name for each set of shift log files is 'SL' + shift_log_id
 */

function _get_shift_log_file_upload_directory($shift_log_id) {
	return 'private://' . 'SL' . $shift_log_id;  
}

