<?php
/**
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Trouble Call Log search function handling
 *    
*/

require_once('sabreQMS.troublecalllist.inc');

/*
 *	search_trouble_calls()
 *
 */

function search_trouble_calls() {
	
	if ( user_access('search view logs') == False ) {
		drupal_set_message(t('Unauthorized:  Permission is required'));
    return;
  }

	drupal_add_library('system','ui.dialog');
	drupal_add_library('system','ui.datepicker');
	drupal_add_library('system','ui.position');
  
	// this doesn't seem to load consistently unless specified here
  drupal_add_js('misc/tableheader.js');   
	drupal_add_js('misc/tableselect.js');   
	
	// see http://digitalbush.com/projects/masked-input-plugin/
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/vendor/jquery.maskedinput-1.3.1.min.js');
	drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
	
	drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.searchtroublecalls.js');

	$trouble_call_search_form = '';
	$trouble_call_search_results = '';
	$form_cache_name = QMS_TROUBLECALL_SEARCH_FORM;
	$search_results = new SearchResultsTable('TC');
	
	global $user;
	$user_is_customer_id = _user_is_customer($user->uid);

	if( $user_is_customer_id ) {
    $form_elems = drupal_get_form('trouble_call_search_form', $user_is_customer_id);
		$trouble_call_search_form = render($form_elems);
	}
	else {
		$form_cache = cache_get($form_cache_name);
		if ( isset($form_cache->data) && ($form_cache->data <> '') ) {
			$trouble_call_search_form = $form_cache->data;
		}
		else {
			// search results not in cache, create empty div for ajax to populate after search
			// search results will get populated to cache after ajax call
      $form_elems = drupal_get_form('trouble_call_search_form');
			$trouble_call_search_form = render($form_elems);
		
			// maintains cache entry for the form for 20 min before refresh (time in seconds)
			// not tied to any one user, can be shared in the database by multiple users
			cache_set($form_cache_name, $trouble_call_search_form, 'cache', time() + QMS_CACHE_TIMEOUT);			
		}
	}
	
	// determine cache name
	$results_cache_name = _get_qms_cache_name(QMS_TROUBLECALL_SEARCH_RESULTS);
	$selected_cache_name = _get_qms_cache_name(QMS_TROUBLECALL_SELECTED);
	
	$results_cache = cache_get($results_cache_name);
	if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
		$search_results = $results_cache->data;
		_check_if_selected($selected_cache_name, $search_results);
    
    $form_elems = drupal_get_form('results_list_form', $search_results);
		$trouble_call_search_results = render($form_elems);
	}
	else {
		// search results not in cache, create empty div for ajax to populate after search
		// search results will get populated to cache after ajax call
		$trouble_call_search_results = '<form id="results-list-form"></form>';
		
		// don't cache the empty form object
		//cache_set($results_cache_name, $trouble_call_search_results, 'cache', time() + QMS_CACHE_TIMEOUT);			
	}
	
	$content = $trouble_call_search_form . $trouble_call_search_results;
	
	return $content;
}

/*
 *	trouble_call_search_form()
 *
 *  overloads:  hook_form()
 *  search form for shift logs
 */
function trouble_call_search_form($form, $form_state, $user_is_customer_id = 0) {
	
	
	//------------ BUILD SEARCH FORM ------------------
	global $customer_list;
	global $chapter_list;
	global $tech_list;
	global $simulator_list;
	global $action_list;
	$trouble_cause_list = new TroubleCauseList();
	global $base_url;
	
	$form['search'] = array(
		'#type' => 'fieldset',
		'#title' => t('Search'),
		'#collapsible' => True,
		'#collapsed' => False,
		'#attributes' => array('id' => array('qms-search-div')),
	);
	
	$form['search']['tc_no'] = array(
		'#type' => 'textfield',
		'#title' => t('TC No.'),
		'#default_value' => 'TC',
		'#size' => 15,
		'#attributes' => array('id' => 'qms-search-tc-no'),
		'#prefix' => '<table class="qms-plain-table" style="width:100%"><tr><td class="qms-search-col1" rowspan="3">',
	);
	
	$form['search']['tech'] = array(
		'#type' => 'select',
		'#title' => t('Technician/Instructor'),
		'#options' => $tech_list->getAll(TechnicianList::INCL_ALL,
                                     TechnicianList::INCL_UNASSIGNED),
		'#default_value' => 0,
		'#attributes' => array('class' => array('qms-select'),
													'id' => 'qms-search-tech'),
	);
	
	$form['search']['customer'] = array(
		'#type' => 'select',
		'#title' => t('Customer'),
		'#options' => $customer_list->getAll(CustomerList::INCL_ALL),
		'#default_value' => $user_is_customer_id,
		'#disabled' => ($user_is_customer_id > 0),
		'#attributes' => array('class' => array('qms-select'),
														'id' => 'qms-search-customer'),
	);
	
	
	$form['search']['simulator'] = array(
		'#type' => 'select',
		'#title' => t('Simulator'),
		'#options' => $simulator_list->getAll(SimulatorList::INCL_ALL),
		'#default_value' => 0,
		'#attributes' => array('class' => array('qms-select'),
														'id' => 'qms-search-simulator'),
	);
	
	$form['search']['trouble_cause'] = array(
		'#type' => 'select',
		'#title' => t('Cause'),
		'#options' => $trouble_cause_list->get(TroubleCauseList::INCL_ALL),
		'#default_value' => 0,
		'#attributes' => array('class' => array('qms-select'),
													 'id' => 'qms-search-trouble-cause'),
		'#suffix' => '</td>',
	);	
	
		
	//-----------------------------------------
	
	$form['search']['search_date_label'] = array(
		'#type' => 'markup',
		'#markup' => '<label style="padding-bottom:8px">Search Date Range for open or closed reports</label>',
		'#prefix' => '<td colspan="3">',
		'#suffix' => '</td></tr>',
	);
	
	
	$form['search']['open'] = array(
		'#type' => 'checkbox',
		'#title' => t('Open'),
		'#default_value' => 0,
		'#attributes' => array('id' => 'qms-search-open'),
		'#prefix' => '<tr><td class="qms-search-col2">',
	);
	
	$form['search']['closed'] = array(
		'#type' => 'checkbox',
		'#title' => t('Closed'),
		'#default_value' => 0,
		'#attributes' => array('id' => 'qms-search-closed'),
		'#suffix' => '</td>',
	);
	
		
	$form['search']['from_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('From Date'),
		'#size' => 10,
		'#date_format' => 'm-d-Y',					
		//'#default_value' => date('Y-m-d'),   	
		'#attributes' => array('style' => array('float:left', 'width:50px'),
														'id' => 'qms-search-from-date',
														'class' => array('qms-date-picker')),
		'#prefix' => '<td class="qms-search-col3">',
		'#suffix' => '</td>',
	);
	
	$form['search']['to_date'] = array(
		'#type' => 'date_popup',
		'#title' => t('To Date'),
		'#size' => 10,
		//'#default_value' => date('Y-m-d'),
		'#date_format' => 'm-d-Y',
		'#attributes' => array('style' => array('float:left', 'clear:right', 'width:50px'),
														'id' => 'qms-search-to-date',
															'class' => array('qms-date-picker')),
		'#prefix' => '<td class="qms-search-col4" >',
		'#suffix' => '<br /><br /></td></tr>',
	);
	
	//------------------------------------------
	
	
	$form['search']['trouble_text'] = array(
		'#type' => 'textfield',
		'#title' => t('Trouble Call Text'),
		'#size' => 48,
		'#default_value' => '',
		'#attributes' => array('id' => 'qms-search-trouble-text'),
		'#prefix' => '<tr><td colspan="3">',
	);
	
	$form['search']['corrective_action'] = array(
		'#type' => 'select',
		'#title' => t('Corrective Action'),
		'#options' => $action_list->getList(CorrectiveActionList::TC,
                                        CorrectiveActionList::INCL_ALL),
		'#default_value' =>  0,
		'#attributes' => array('id' => 'qms-search-corrective-action',
													 'class' => array('qms-corrective-actions-select')),
		'#suffix' => '</td></tr></table>',
	);	
	
	
	//--------------------------------------------
	// Adds a simple submit button that refreshes the form and clears its contents 
	// -- this is the default behavior for forms.
	$form['search']['actions'] = array('#type' => 'actions');
	$form['search']['actions']['submit'] = array(
		'#type' => 'button',
		'#value' => 'Search',
		'#attributes' => array('id' => 'qms-search-btn-submit',
                           'style' => 'font-weight:bolder;',
														'qms-url' => url('search/troublecalls/search') ),

	);
	global $base_url;
  $form['search']['actions']['clear'] = array(
		'#type' => 'button',
		'#value' => t('Clear'),
		'#attributes' => array('id' => 'qms-search-btn-clear',
                           'class' => array('qms-btn-extra'),
													 'qms-url' => url('search/troublecalls/clear') ),
    '#suffix' => '<span class="qms-waiting"><img class="qms-waiting-img" src="' . 
                  $base_url . QMS_IMAGES_DIR . 'waiting.gif" /></span>',
	);
	
	// storage area for dynamic dialog element
	$form['popup_dialog'] = array(
		'#markup' => '<div id="qms-message-box"></div>',
	);
	

	return $form;
}


/**
 * trouble_call_search_form_callback()
 * displays the search results, first page only
 * Has to be a separate handler from pager & sort link callback
 * This is the callback that gets called when the Search button is clicked
 *
 */
function trouble_call_search_form_callback() {
	
	$search = (object) NULL;
	
	$search->tc_no = trim($_POST['tc_no']);
	$search->tech_id = (int)$_POST['tech'];
	$search->simulator_id = (int)$_POST['simulator'];
	$search->customer_id = (int)$_POST['customer'];
	$search->trouble_cause_code = (int)$_POST['cause'];
	$search->open = (int)$_POST['open'];
	$search->closed = (int)$_POST['closed'];
	$search->from_date = trim($_POST['from_date']);
	$search->to_date = trim($_POST['to_date']);
	$search->trouble_text = trim($_POST['trouble_text']);
	$search->corrective_action_id = (int)$_POST['corrective_action'];
	
	
	// cache the latest search key
	// determine cache name, always use it specific to this user + session
	// set key cache to expire in 30 minutes
	$key_cache_name =  _get_qms_cache_name(QMS_TROUBLECALL_SEARCH_KEY);
	$selected_cache_name =  _get_qms_cache_name(QMS_TROUBLECALL_SELECTED);
	
	// cache the search parameters
	cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);		
	
	// this is a new search, clear the old search results list selections
	cache_clear_all($selected_cache_name, 'cache', TRUE); 
	
	$search_results = new SearchResultsTable('TC');

	_get_trouble_call_search_results($search, $search_results);
  $form_elems = drupal_get_form('results_list_form', $search_results);
	$content = render($form_elems);
	die($content);			// always die as this is an ajax callback (we only want a partial page render)
}

/**
 * trouble_call_pager_callback()
 * displays the search results, first page only
 * Has to be a separate handler from pager & sort link callback
 * This is the callback that gets called when the Search button is clicked
 *
 */

function trouble_call_pager_callback() {
	
	$search = (object) NULL;
	
	// determine the key cache
	$key_cache_name =  _get_qms_cache_name(QMS_TROUBLECALL_SEARCH_KEY);
	
	$key_cache = cache_get($key_cache_name);
	if ( isset($key_cache->data) && ($key_cache->data <> '') ) {
		$search = $key_cache->data;
	}
	else {
		// search key not in cache, get it from POST
		// though, this should never happen... should always be in cache
		$search->tc_no = trim($_POST['tc_no']);
		$search->tech_id = (int)$_POST['tech'];
		$search->simulator_id = (int)$_POST['simulator'];
		$search->customer_id = (int)$_POST['customer'];
		$search->trouble_cause_code = (int)$_POST['cause'];
		$search->open = (int)$_POST['open'];
		$search->closed = (int)$_POST['closed'];
		$search->from_date = trim($_POST['from_date']);
		$search->to_date = trim($_POST['to_date']);
		$search->trouble_text = trim($_POST['trouble_text']);
		$search->corrective_action_id = (int)$_POST['corrective_action'];
		
		// cache the latest search key, expire it in 30min
		cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);		
		
	}
	
	// get the previous SearchResultsTable object
	$search_results = new SearchResultsTable('TC');
	
	_get_trouble_call_search_results($search, $search_results);
  $form_elems = drupal_get_form('results_list_form', $search_results);
	$content = render($form_elems);
	die($content);
}

/*
 * trouble_call_results_callback()
 * 
 * Clears the search results cache
 *
 */
function trouble_call_clear_results_callback() {
	
	// Clear the cache 
	
	// determine cache name
	$results_cache_name = _get_qms_cache_name(QMS_TROUBLECALL_SEARCH_RESULTS);
	$key_cache_name =  _get_qms_cache_name(QMS_TROUBLECALL_SEARCH_KEY);
	$selected_cache_name =  _get_qms_cache_name(QMS_TROUBLECALL_SELECTED);
	
	cache_clear_all($results_cache_name, 'cache', TRUE); 
	cache_clear_all($key_cache_name, 'cache', TRUE); 
	cache_clear_all($selected_cache_name, 'cache', TRUE); 
	
	$content = '<form id="results-list-form"></form>';
	
	// this is an ajax callback.  Need to return + die or it renders a full page
	// we only want a piece of a page
	
	die($content);  
}


