<?php

/**
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Trouble Call Search List functions
 *    
*/


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

function _get_trouble_call_results_table_header($bAdmin = True) {
	$table_header = array( 
		'tc_no' => array( 
			'data' => 'TC No.', 
			'field' => 'tc_no', 
			'sort' => 'desc', 
			'class' => array('qms-results-tcno') 
		),
		'dr_no' => array( 
			'data' => 'DR No.', 
			'field' => 'dr_no', 
			'sort' => 'desc', 
			'class' => array('qms-results-drno') 
		),
		'date_opened' => array( 
			'data' => 'Opened', 
			'field' => 'date_opened', 'sort' => 
			'desc', 
			'class' => array('qms-results-dateopened') 
		),
    /*
		'date_closed' => array( 
			'data' => 'Closed', 
			'field' => 'date_closed', 
			'sort' => 'desc', 
			'class' => array('qms-results-dateclosed') 
		),*/
		
		'full_name' => array( 
			'data' => 'Technician', 
			'field' => 'full_name', 
			'sort' => 'asc', 
			'class' => array('qms-results-tech')  
		),
		'sim_name' => array( 
			'data' => 'Simulator', 
			'field' => 'sim_name', 
			'sort' => 'asc', 
			'class' => array('qms-results-simulator') 
		),
		'trouble_cause_desc' => array( 
			'data' => 'Cause', 
			'field' => 'trouble_cause_desc', 
			'sort' => 'asc', 
			'class' => array('qms-results-troublecause')  
		),
	);	
	
	if ($bAdmin) {
		$table_header['admin'] = array( 'data' => 'Admin', 'class' => array('qms-results-admin'));
	}
	// add hidden column that gets used for the text popup display
	$table_header['trouble_text'] = array( 
		'data' => 'TC Text', 
		'field' => 'trouble_text', 
		'sort' => 'asc', 
		'class' => array('qms-hidden-field') 
	);
	
	return $table_header;
}

/*
 * _get_trouble_call_search_results()
 * display the search results
 * This function gets called by trouble_call_search_form_callback() and trouble_call_pager_callback()
 * also rebuilds the search results and cache after a delete
 *
 */

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

	$bAdmin = user_access('administer sabreQMS');
	$bAllowEdit = user_access('edit trouble call log');
  
  global $simulator_list;
						 		
	if ( Null == $search_results ) {
		$search_results = new SearchResultsTable('TC');
	}
	
	$table_header = array();
	
	if ( !$search_results->hasHeader() ) {
		$table_header = _get_trouble_call_results_table_header(($bAllowEdit || $bAdmin));
		$search_results->setHeader($table_header);
	}
	else {
		$table_header = $search_results->getHeader();
	}
	
	// get the selected dr cache, if anything has been stored
	$saved_selected_text = '';
	$selected_cache_name = _get_qms_cache_name(QMS_TROUBLECALL_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_trouble_call_log',
		'table_alias' => 'tc',
		'table_header' => $table_header,
		'pager_path' => 'search/troublecalls/pager',
		'order' => QMS_TROUBLECALL_DEFAULT_SORT_COLUMN,
		'order_default' => 'TC No.',
		'sort' => QMS_TROUBLECALL_DEFAULT_SORT,
		'sort_default' => 'desc',
		'variable' => True,
	);
	
	$query = _st_setup_paged_search($search_init);
	
	
	//------------------ Add Search Conditions ------------------------
	
	// Date filtering 
	
	//  Date opened
	if ( $search->open == 1 ) {
		if ( (strlen($search->from_date) > 0) && (strlen($search->to_date) > 0)) {
			$query->condition('tc.date_opened', _st_format_timestamp($search->from_date . " 00:00:00"), '>=');
			$query->condition('tc.date_opened', _st_format_timestamp($search->to_date . " 23:59:59"), '<=');
		}
		else if (strlen($search->from_date) > 0) {
			$query->condition('tc.date_opened', _st_format_timestamp($search->from_date . " 00:00:00"), '>=');
		}
		else if (strlen($search->to_date) > 0) {
			$query->condition('tc.date_opened', _st_format_timestamp($search->to_date . " 23:59:59"), '<=');
		}
		else {
			$query->condition('tc.date_closed', 0, '=');
		}
	}
	
	//  Date closed
	if ( $search->closed == 1 ) {
		if ( (strlen($search->from_date) > 0) && (strlen($search->to_date) > 0)) {
			$query->condition('tc.date_closed', _st_format_timestamp($search->from_date . " 00:00:00"), '>=');
			$query->condition('tc.date_closed', _st_format_timestamp($search->to_date . " 23:59:59"), '<=');
		}
		else if (strlen($search->from_date) > 0) {
			$query->condition('tc.date_closed', _st_format_timestamp($search->from_date . " 00:00:00"), '>=');
		}
		else if (strlen($search->to_date) > 0) {
			$query->condition('tc.date_closed', _st_format_timestamp($search->to_date . " 23:59:59"), '<=');
		}
		else {
			$query->condition('tc.date_closed', 0, '>');	
		}
	}
	
	// TC No
	if ( ($search->tc_no <> '') && ( $search->tc_no <> 'TC') ) {  // if only DR prefix, don't bother
		$search->tc_no .= '%';  // append wildcard for fuzzy match
		$query->condition('tc_no', $search->tc_no, 'LIKE');
	}
	
	// Trouble Text
	if ( $search->trouble_text <> '' ) {
		//---------------------- Keyword Seaching:  Trouble Text --------------
		// Combo Keyword and Exact Phrase Matching ( ex:  keyword "exact phrase" )
		_st_add_keyword_search_condition($query, 'trouble_text', $search->trouble_text);
	}
	
	// simulator -- this has to come before customer since customer is linked to DR through simulator record
	if ( $search->simulator_id > 0 ) {
    $query->condition('tc.simulator_id', $search->simulator_id);
	}
  
  $query->innerJoin('qms_simulators', 's', 's.simulator_id = tc.simulator_id');
	if ( $search->simulator_id ) {
		$query->condition('tc.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 -- simulator gets joined first.
	if ( $search->customer_id > 0 ) {
		$query->innerJoin('qms_customers', 'c', 'c.customer_id = :cid AND c.customer_id = s.customer_id',
											array(':cid' => $search->customer_id) );
	}
	/*
	else {
		$query->innerJoin('qms_customers', 'c', 'c.customer_id = s.customer_id');
	} */
	
	// tech 
	// if tech search parm > 0, search for assigned techs
	// if tech search parm == 0, do not include the tech_user_id search condition
	// if tech search parm == -1, search for tech_user_id == 0 (flag to allow for unassigned search)
	if ( $search->tech_id > 0 ) {
		$query->condition('tc.tech_user_id', $search->tech_id);
	}
	else if ( $search->tech_id < 0 )  {  // flag for unassigned tech condition
		$query->condition('tc.tech_user_id', 0, '=');
	}
	// always leftjoin employees as the tc.tech_user_id could be zero.
	$query->leftJoin('qms_employees', 'e', 'e.user_id = tc.tech_user_id');
	
	// it's possible in some cases, have a tech_user_id == 0 if tech has not yet been assigned (feature setting)
	$query->leftJoin('users', 'u', 'u.uid = tc.tech_user_id');
	
	
	// corrective_action		
	if ( $search->corrective_action_id > 0 ) {
		$query->innerJoin('qms_corrective_actions', 'a', 
											'a.action_id = tc.corrective_action_id AND a.action_id = :aid',
											array(':aid' => $search->corrective_action_id) );	
	}
	
	// linked discrepancy
	$query->leftJoin('qms_discrepancy_log', 'd', 'tc.trouble_call_id = d.from_trouble_call_id');	
	
	// trouble_cause_code		
	$query->innerJoin('qms_trouble_causes', 'tcc', 'tcc.trouble_cause_code = tc.trouble_cause_code');	
	
	if ( $search->trouble_cause_code > 0 ) {
		$query->condition('tc.trouble_cause_code', $search->trouble_cause_code);	
	}
	
	
	$query->fields('tc', array('trouble_call_id', 'tc_no', 'date_opened', 'date_closed', 'tech_user_id',
														 'simulator_id', 'trouble_text') )
							->fields('d', array('discrepancy_id', 'dr_no'))
              ->fields('tcc', array('trouble_cause_desc'))
              ->fields('e', array('full_name'))
              ->fields('u', array('name'));
							//->fields('c', array('customer'))
							//->fields('s', array('sim_name', 'active'))
              
					
	
	// determine if items were selected or not		
	if ( strlen($saved_selected_text) ) {
		$list = explode(",", $saved_selected_text);
		$query->addExpression("IF( tc.trouble_cause_id IN(:sel_list), :y, :n )", "selected", 
																array(':sel_list' => $list, ':y' => 1, ':n' => 0));	
	}				
	$max_count = 0;
	$results = _st_execute_paged_search($query, $max_count);
	
	$i = 0;
	$table_rows = array();
	$selected_list = array();
	
	global $base_url;
	
	
	foreach ($results as $row) {
		
		// the TC has been closed, only admin edit allowed despite user's edit permissions
		$bEdit = ($row->date_closed ? $bAdmin : $bAllowEdit );
		
		
		$tech_name = 
			( (0 == $row->tech_user_id) ? '[unassigned]' : 
					( strlen($row->full_name) ? $row->full_name : $row->name . "*"));
		
		
		// set the id into the array index which is linked to the tableselect's checkbox
		$table_rows[$row->trouble_call_id] = array(
			'tc_no' => array(
				'data' => array(
					'#type' => 'link',
					'#title' => $row->tc_no,
					'#href' => ('troublecall/view/' . $row->trouble_call_id),
					'#attributes' => array('class' => array('qms-tc-no')),
					'#options' => array('query' => array('destination' => 'search/troublecalls')),
				),
			),
			'dr_no' => array(
				'data' => array(
					'#type' => 'link',
					'#title' => $row->dr_no,
					'#href' => ('discrepancy/view/' . $row->discrepancy_id),
					'#attributes' => array('class' => array('qms-dr-no')),
					'#options' => array('query' => array('destination' => 'search/troublecalls')),
				),
			),
			'date_opened' => _st_format_date($row->date_opened, 'short'),
			//'date_closed' => ( $row->date_closed ? _st_format_date($row->date_closed, 'short') : ''),
			'full_name' => $tech_name,
			'sim_name' => $simulator_list->getName($row->simulator_id),
			'trouble_cause_desc' => $row->trouble_cause_desc,
		);
		
		// don't allow for the column to exist if user is not an admin, otherwise we get an empty column
		$table_rows[$row->trouble_call_id]['admin'] = array(
			'data' => _get_results_table_options('troublecall', $row->trouble_call_id, 
																						$bEdit, 'search/troublecalls'), 
			'class' => array('qms-results-admin'),
		);
		
		$table_rows[$row->trouble_call_id]['trouble_text'] = array(
			'data' => check_plain(( strlen($row->trouble_text) > 650 ) ? 
									(_st_convert_symbols(substr($row->trouble_text, 0, 650)) . '...') : 
									_st_convert_symbols($row->trouble_text)),
			'class' => 'qms-hidden-popup-text',
		);
		
		if ( strlen($saved_selected_text) ) { $selected_list[$row->trouble_call_id] = $row->selected; }

		$i++;
	}
	
	$pager = theme('pager', array('tags' => array(), 'quantity' => QMS_RECORDS_PER_PAGE));
	$search_results->setPager($pager);
	$search_results->setResults($table_rows);
	$search_results->setSelected($selected_list);
	
	//Save to cache
	$results_cache_name = _get_qms_cache_name(QMS_TROUBLECALL_SEARCH_RESULTS);
	
	// 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
	cache_set($results_cache_name, $search_results, 'cache', time() + QMS_CACHE_TIMEOUT);
	
	return $table_rows;
	
		
}
