<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Shift Log Search List functions
 *    
*/


/*
 * _get_shift_log_results_table_header()
 * generates the headers for the search results table so it only gets called once
 *
 */

function _get_shift_log_results_table_header($admin=False) {
	$table_header = array( 
		'full_name' => array( 'data' => 'Technician', 'field' => 'full_name', 'sort' => 'asc', 'class' => array('qms-sl-results-tech') ),
		'datetime' => array( 'data' => 'Date', 'field' => 'datetime', 'sort' => 'desc', 'class' => array('qms-sl-results-datetime') ),
		'sim_name' => array( 'data' => 'Simulator', 'field' => 'sim_name', 'sort' => 'asc', 'class' => array('qms-sl-results-simulator') ),
		'comment' => array( 'data' => 'Comment', 'field' => 'comment', 'sort' => 'asc', 'class' => array('qms-sl-results-comment') ),
		//'admin' => array( 'data' => 'Admin', 'class' => array('qms-results-admin')),
	);
	if ( $admin ) {
		$table_header['admin'] = array( 'data' => 'Admin', 'class' => array('qms-results-admin'));
	}
	
	return $table_header;
}


/*
 * _get_shift_log_search_list()
 * display the search results
 * This function gets called by shift_log_search_form_callback() and shift_log_pager_callback()
 * also gets called after a delete submit to refresh the cache ($bRefresh = True), but does not return anything
 *
 */

function _get_shift_log_search_list($search,	$sl_search_results = Null) {
	
	if ( user_access('search view reports') == FALSE ) {
		drupal_set_message(t('Unauthorized:  User authentication required'));
    return;
  }

	$bAdmin = user_access('administer sabreQMS');	
	

	$num_per_page =  QMS_RECORDS_PER_PAGE;  
	$table_header = array();
	
	if ( $sl_search_results == Null ) {
		$sl_search_results = new SearchResultsTable('SL');
	}
	if ( !$sl_search_results->hasHeader() ) {
		$table_header = _get_shift_log_results_table_header($bAdmin);
		$sl_search_results->setHeader($table_header);
	}
	else {
		$table_header = $sl_search_results->getHeader();
	}
	
	// get the selected cache, if anything has been stored
	$saved_selected_text = '';
	$selected_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SELECTED);

	$selected_cache = cache_get($selected_cache_name);
	if ( isset($selected_cache->data) && ($selected_cache->data <> '') ) {
		$saved_selected_text = $selected_cache->data;
	}
	
	$search_init = array(
		'table_name' => 'qms_shift_log',
		'table_alias' => 'l',
		'table_header' => $table_header,
		'pager_path' => 'search/shiftlog/pager',
		'order' => QMS_SHIFTLOG_DEFAULT_SORT_COLUMN,
		'order_default' => 'Date',
		'sort' => QMS_SHIFTLOG_DEFAULT_SORT,
		'sort_default' => 'desc',
		'variable' => True,
	);
	
	$query = _st_setup_paged_search($search_init);
	
  
  global $simulator_list;
	global $user;
	$user_is_customer_id = _user_is_customer($user->uid);
	
	
	//--------- Date filtering -----------
	
	//  Date opened
	if (strlen($search->from_date) > 0) {
		$search->from_date .= " 00:00:00";	 // append time segment in UTC format
		$query->condition('datetime', _st_format_timestamp($search->from_date), '>=');
	}
	if (strlen($search->to_date) > 0) {
		$search->to_date .= " 23:59:59";		// append time segment in UTC format
		$query->condition('datetime', _st_format_timestamp($search->to_date), '<=');
	}
	
	// tech		
	if ( $search->tech_id > 0 ) {
		//query->innerJoin('qms_employees', 'e', 'e.user_id = l.employee_user_id AND e.user_id = :uid',
		//									array(':uid' => $search->tech_id) );	
		$query->condition('employee_user_id', $search->tech_id);
	}
	$query->leftJoin('qms_employees', 'e', 'e.user_id = l.employee_user_id');
	$query->leftJoin('users', 'u', 'u.uid = l.employee_user_id');
	
	
  // simulators  
  $query->innerJoin('qms_simulators', 's', 's.simulator_id = l.simulator_id');
	if ( $search->simulator_id ) {
		$query->condition('l.simulator_id', $search->simulator_id);
	}
  else {
    // ALL SIMS SEARCH - ignore the sims that have been turned off for ALL searches
    $query->condition('s.include_all_searches', 1);
  }
	
	// customer-user?
	if ( $user_is_customer_id ) {
		// add filter to limit results to those related to this customer
		$query->condition('s.customer_id', $user_is_customer_id);
	}	
	
	
	// commment text		
	if ( $search->comment_text <> '' ) {
		
		//---------------------- Keyword Seaching --------------
		// Combo Keyword and Exact Phrase Matching ( ex:  keyword "exact phrase" )
		_st_add_keyword_search_condition($query, 'comment', $search->comment_text);		
	}	

	
	$q2 = $query->fields('l', array('shift_log_id', 'simulator_id', 
                        'datetime', 'comment', 'files_attached') )
							//->fields('s', array('sim_name', 'active'))
							->fields('e', array('full_name'))
							->fields('u', array('name'));
						
	// determine if items were selected or not		
	if ( strlen($saved_selected_text) ) {
		$list = explode(",", $saved_selected_text);
		$query->addExpression("IF( l.shift_log_id IN(:sel_list), :y, :n )", "selected", 
																array(':sel_list' => $list, ':y' => 1, ':n' => 0));	
	}				
	$max_count = 0;				
	$result = _st_execute_paged_search($query, $max_count);
	
	
	$i = 0;
	$table_rows = array();
	$selected_list = array();
	
	global $base_url;
	$has_files = '';
	$show_file_icon = '<span>&nbsp;<img class="qms-files-attached" src="' . $base_url . QMS_IMAGES_DIR . 'files_attached.png' . '" /></span>';
	
	
	foreach ($result as $row) {
		$comment_cleaned = trim(strip_tags(_st_convert_symbols($row->comment, ENT_QUOTES, 'UTF-8')));
		
		if ( $row->files_attached ) {
			$has_files = $show_file_icon;
		}
		else {
			$has_files = '';
		}
		
		// set the id into the array index which is linked to the tableselect's checkbox
		$table_rows[$row->shift_log_id] = array(
			'full_name' => ( (strlen($row->full_name) > 0) ? check_plain($row->full_name) : check_plain($row->name) . "*"),
			'datetime' => array(
				'data' => array(
					'#type' => 'link',
					'#title' => _st_format_date($row->datetime, 'short'),
					'#href' => ('shiftlog/view/' . $row->shift_log_id),
					'#options' => array('query' => array('destination' => 'search/shiftlog')),
				),
			),			
			'sim_name' => $simulator_list->getName($row->simulator_id),
			'comment' => '<span>' . ((strlen($comment_cleaned) > 40) ? 
							substr($comment_cleaned, 0, 39) . '...' : $comment_cleaned) . $has_files .  '</span>',
		);
		
		if ( $bAdmin ) {
			// don't allow for the column to exist if user is not an admin, otherwise we get an empty column
			$table_rows[$row->shift_log_id]['admin'] = array(
				'data' => _get_results_table_options('shiftlog', $row->shift_log_id, $bAdmin, 'search/shiftlog'), 
				'class' => array('qms-results-admin'),
			);
			
		}
		
		if ( strlen($saved_selected_text) ) {
			$selected_list[$row->shift_log_id] = $row->selected;
		}
		
		
		$i++;
	}
	
	$pager = theme('pager', array('tags' => array(), 'quantity' => $num_per_page));
	$sl_search_results->setPager($pager);
	$sl_search_results->setResults($table_rows);
	$sl_search_results->setSelected($selected_list);
	
	// Save to cache
	// cache the $sl_search_results object
	// cache the nested table array structure without rendering
	// rendering has to be done each time the results are displayed or the checkbox selections won't work
	$results_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SEARCH_RESULTS);
	cache_set($results_cache_name, $sl_search_results, 'cache', time() + QMS_CACHE_TIMEOUT);
	
	return $table_rows;

	
	
	/*
	if ( $i == 0 ) {
		$table_rows[] = array('data' => array('None', '', '', '', '') );
	}
	
	$content = '<div id="qms-search-results-div">';
	
	$content .= theme( 'table', array(
		'header' => $table_header,
		'rows' => $table_rows,
	));
	
	//Append pager:  http://api.drupal.org/api/drupal/includes--pager.inc/function/theme_pager
	$content .= theme('pager', array('tags' => array(), 'quantity' => $num_per_page));
	$content .= '</div>';
	
	// Save to cache
	// determine cache name, linked to user id and session id, expires in 30min
	global $user;
	$results_cache_name = 'QMS_shiftlog_search_results_' . $user->uid . '_' . $user->sid;
	
	$shiftlog_search_results = $content;
	cache_set($results_cache_name, $shiftlog_search_results, 'cache', time() + (30*60));
	
	//refreshing cache after an edit or delete, don't return anything here
	if ( $bRefresh ) {  
		return;
	}
	
	// All calls to this function are standard AJAX calls return $content and die
	die($content);
	*/
}





