<?php

/**
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		QTG Search Module
*/

require_once('sabreQMS.qtglist.inc');

//-------------------- QTG   ------------------------
/*
 * search_qtg() 
 * 
 */

function search_qtg() {
	
	if ( user_access('search view reports') == 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.searchqtg.js');
	
	$qtg_search_results = new SearchResultsTable('QTG');
	$qtg_search_form = '';
	$qtg_search_results = '';
	
	global $user;
	$user_is_customer_id = _user_is_customer($user->uid);

	if( $user_is_customer_id ) {
    $form_elems = drupal_get_form('qtg_search_form', $user_is_customer_id);
		$qtg_search_form = render($form_elems);
	}
	else {
		$form_cache = cache_get(QMS_QTG_SEARCH_FORM);
		if ( isset($form_cache->data) && ($form_cache->data <> '') ) {
			$qtg_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('qtg_search_form');
			$qtg_search_form = render($form_elems);
		
			//maintains cache entry for the form for 20 min before refresh (time in seconds)
			cache_set(QMS_QTG_SEARCH_FORM, $qtg_search_form, 'cache', time() + QMS_CACHE_TIMEOUT);			
		}
	}
	
	// determine cache names
	$results_cache_name = _get_qms_cache_name(QMS_QTG_SEARCH_RESULTS);
	$selected_cache_name = _get_qms_cache_name(QMS_QTG_SELECTED);
	
	
	$results_cache = cache_get($results_cache_name);
	if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
		$qtg_search_results = $results_cache->data;
		_check_if_selected($selected_cache_name, $qtg_search_results); // checks if the items in the list should be checked
		
		// need to force this or pager/sort picks up the wrong path
		$_GET['q'] = 'search/qtg/pager';
		$form_elems = drupal_get_form('results_list_form', $qtg_search_results);
		$qtg_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
		$qtg_search_results = '<form id="results-list-form"></form>';
		
		// don't cache the empty form placeholder
		//cache_set($results_cache_name, $qtg_search_results, 'cache', time() + QMS_CACHE_TIMEOUT);			
	}
		
	$content = $qtg_search_form . $qtg_search_results;
	
	return $content;
		
}

/*
 * 	qtg_search_form()
 * 	display form to get user input of search parameters
 *
 */

function qtg_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;
	global $base_url;
  
  // is QMS linked to connect to the Scheduler database ??
	//$is_linked = variable_get(SCH_QMS_LINK, 0);
  
  
	
	$form['search'] = array(
		'#type' => 'fieldset',
		'#title' => t('Search'),
		'#collapsible' => True,
		'#collapsed' => False,
		'#attributes' => array('id' => array('qms-search-div')),
	);
	
	$form['search']['qtg_no'] = array(
		'#type' => 'textfield',
		'#title' => t('QTG No.'),
		'#default_value' => '',
		'#size' => 15,
		'#attributes' => array('id' => 'qms-search-qtg-no'),
		'#prefix' => '<table class="qms-plain-table" style="width:100%">' . 
                 '<tr><td class="qms-search-col1" rowspan="3">',
	);
  
  $form['search']['test_code'] = array(
		'#type' => 'textfield',
		'#title' => t('Test Code'),
		'#default_value' => '',
		'#size' => 10,
		'#attributes' => array('id' => 'qms-search-test-code'),
	);
  
  $form['search']['plan_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Test Plan Name'),
		'#default_value' => '',
		'#size' => 20,
		'#attributes' => array('id' => 'qms-search-plan-name'),
	);
  
  $form['search']['group_name'] = array(
		'#type' => 'textfield',
		'#title' => t('Test Group Name'),
		'#default_value' => '',
		'#size' => 5,
		'#attributes' => array('id' => 'qms-search-group-name'),
	);
	
	
	$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'),
    //'#suffix' => '</td></tr>',
	);
	
		
	//-----------------------------------------
	
	$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']['note_text'] = array(
		'#type' => 'textfield',
		'#title' => t('Test Status Note Text'),
		'#size' => 50,
		'#default_value' => '',
		'#attributes' => array('id' => 'qms-search-note-text'),
		'#prefix' => '<tr><td colspan="3">',
	);
	
//	$form['search']['comment_text'] = array(
//		'#type' => 'textfield',
//		'#title' => t('Comment Text'),
//		'#size' => 50,
//		'#default_value' => '',
//		'#attributes' => array('id' => 'qms-search-comment-text'),
//		//'#suffix' => '</td></tr></table>',
//	);
  
  $form['search']['end_table'] = array(
    '#markup' => '</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' => t('Search'),
		'#attributes' => array('id' => 'qms-search-btn-submit',
                           'style' => 'font-weight:bolder;',
													 'qms-url' => url('search/qtg/search') ),
/*	DO NOT do Drupal AJAX here, being done through JQuery by the javascript file
		as we need the .live("click") function due to form caching, which won't work here with Drupal
		'#ajax' => array(
			'callback' => 'qtg_search_form_callback',
			'wrapper' => 'qms-search-results-div',
			'method' => 'replace',
			'prevent' => 'click',
			'keypress' => TRUE,
		),
*/
	);
  $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/qtg/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;
}

/**
 * qtg_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 qtg_search_form_callback() {
	
	$search = (object) NULL;
	
  $search->qtg_no = trim($_POST['qtg_no']);
	$search->test_code = trim($_POST['test_code']);
	$search->plan_name = trim($_POST['plan_name']);
	$search->group_name = trim($_POST['group_name']);
	$search->simulator_id = (int)$_POST['simulator'];
	$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->note_text = trim($_POST['note_text']);
	
	

	// 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_QTG_SEARCH_KEY);
	$selected_cache_name = _get_qms_cache_name(QMS_QTG_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); 
	
	$qtg_search_results = new SearchResultsTable('QTG');
	
	_get_qtg_search_results($search, $qtg_search_results);	
  $form_elems = drupal_get_form('results_list_form', $qtg_search_results);
	$content = render($form_elems);
	die($content);   // always die as this is an ajax callback (we only want a partial page render)
}

/**
 * qtg_pager_callback()
 * displays the search results for all subsequent pages and sorts
 * This is the callback that gets called when the Pager or Column Sort button is clicked
 *
 */

function qtg_pager_callback() {
	
	$search = (object) NULL;
	
	// determine the key cache
	$key_cache_name = _get_qms_cache_name(QMS_QTG_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 the form
		// this is a rare case. On a pager call, the search key will almost always
		// be stored in cache
    $search->qtg_no = trim($_POST['qtg_no']);
    $search->test_code = trim($_POST['test_code']);
    $search->plan_name = trim($_POST['plan_name']);
    $search->group_name = trim($_POST['group_name']);
    $search->simulator_id = (int)$_POST['simulator'];
    $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->note_text = trim($_POST['note_text']);
    
		// cache the latest search key
		cache_set($key_cache_name, $search, 'cache', time() + QMS_CACHE_TIMEOUT);		
	}
	
	// get the previous SearchResultsTable object
	$qtg_search_results = new SearchResultsTable('QTG');
			
	_get_qtg_search_results($search, $qtg_search_results);	
  $form_elems = drupal_get_form('results_list_form', $qtg_search_results);
	$content = render($form_elems);
	die($content);  // always die as this is an ajax callback (we only want a partial page render)
}

/*
 * qtg_clear_results_callback()
 * 
 * Clears the search results cache
 *
 */
function qtg_clear_results_callback() {
	
	// Clear the cache 

	// determine cache name
	$results_cache_name = _get_qms_cache_name(QMS_QTG_SEARCH_RESULTS);
	$key_cache_name = _get_qms_cache_name(QMS_QTG_SEARCH_KEY);
	$selected_cache_name = _get_qms_cache_name(QMS_QTG_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); 
	
	//just return an empty form container
	$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);  
}

