<?php
// $Id$

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

//require_once('sabreQMS.utils.inc');
require_once('sabreQMS.shiftloglist.inc');

/*
 *	search_shift_logs()
 *
 */

function search_shift_logs() {

  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_js('misc/tableselect.js');	// this doesn't seem to load consistently unless specified here
  drupal_add_js(drupal_get_path('module', 'sabreTools') . '/js/sabreTools.lib.js');
  drupal_add_js(drupal_get_path('module', 'sabreQMS') . '/js/sabreQMS.searchshiftlogs.js');

  $shiftlog_search_form = '';
  $shiftlog_search_results = '';
  $form_cache_name = QMS_SHIFTLOG_SEARCH_FORM;
  $sl_search_results = new SearchResultsTable('SL');

  global $user;
  $user_is_customer_id = _user_is_customer($user->uid);

  if( $user_is_customer_id ) {
    $form_elems = drupal_get_form('shift_log_search_form');
    $shiftlog_search_form = render($form_elems);
  }
  else {
    $form_cache = cache_get($form_cache_name);
    if ( isset($form_cache->data) && ($form_cache->data <> '') ) {
      $shiftlog_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('shift_log_search_form');
      $shiftlog_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, $shiftlog_search_form, 'cache', time() + QMS_CACHE_TIMEOUT);
    }
  }

  // determine cache name
  $results_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SEARCH_RESULTS);
  $selected_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SELECTED);

  $results_cache = cache_get($results_cache_name);
  if ( isset($results_cache->data) && ($results_cache->data <> '') ) {
    $sl_search_results = $results_cache->data;
    _check_if_selected($selected_cache_name, $sl_search_results);

    // need to force this or pager/sort picks up the wrong path
    $_GET['q'] = 'search/shiftlog/pager';

    $form_elems = drupal_get_form('results_list_form', $sl_search_results);
    $shiftlog_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
    $shiftlog_search_results = '<form id="results-list-form"></form>';

    // don't cache the empty form object
    //cache_set($results_cache_name, $shiftlog_search_results, 'cache', time() + QMS_CACHE_TIMEOUT);
  }

  $content = $shiftlog_search_form . $shiftlog_search_results;

  return $content;
}

/*
 *	shift_log_search_form()
 *
 *  overloads:  hook_form()
 *  search form for shift logs
 */
function shift_log_search_form($form, $form_state) {

  global $simulator_list;
  global $tech_list;

  //------------ BUILD SEARCH FORM ------------------

  $form['search'] = array(
    '#type' => 'fieldset',
    '#title' => t('Search'),
    '#collapsible' => True,
    '#collapsed' => False,
    '#attributes' => array('id' => 'qms-search-div'),
  );

  $form['search']['tech'] = array(
    '#type' => 'select',
    '#title' => t('Technician/Instructor'),
    '#options' => $tech_list->getAll(TechnicianList::INCL_ALL),
    '#default_value' => 0,
    '#attributes' => array('class' => array('qms-select'),
                          'id' => 'qms-search-tech'),
    '#prefix' => '<table class="qms-plain-table"><tr style="vertical-align:bottom"><td class="qms-search-sl-col1">',
  );

  $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>',
  );

  $form['search']['from_date'] = array(
    '#type' => 'date_popup',
    '#title' => t('From Date'),
    '#size' => 10,
    '#date_format' => 'm-d-Y',
    '#default_value' => '',
    '#date_year_range' => '-5:+0',
    '#attributes' => array('style' => array('float:left', 'width:50px'),
                            'id' => 'qms-search-from-date',
                            'class' => array('qms-date-picker')),
    '#prefix' => '<td class="qms-search-sl-col2">',
    '#suffix' => '</td>',
  );

  $form['search']['to_date'] = array(
    '#type' => 'date_popup',
    '#title' => t('To Date'),
    '#size' => 10,
    '#default_value' => '',
    '#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-sl-col3">',
    '#suffix' => '</td></tr>',
  );

  // Comment Text
  $form['search']['comment_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Comment Text'),
    '#size' => 80,
    '#default_value' => '',
    '#attributes' => array('id' => 'qms-search-comment-text'),
    '#prefix' => '<tr><td colspan="3">',
    '#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/shiftlog/search') ),
/*
    // NOT using Drupal AJAX on the submit button.
    // Need to allow jQuery .live("click") for this button as the form gets cached for performance

      '#ajax' => array(
      'callback' => 'shift_log_search_form_callback',
      'wrapper' => 'qms-search-results-div',
      'method' => 'replace',
      'prevent' => 'click',
      'keypress' => TRUE,
    ),
*/
  );

  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/shiftlog/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;
}


/**
 * shift_log_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 shift_log_search_form_callback() {

  $search = (object) NULL;

  $search->tech_id = (int)$_POST['tech'];
  $search->simulator_id = (int)$_POST['simulator'];
  $search->from_date = trim($_POST['from_date']);
  $search->to_date = trim($_POST['to_date']);
  $search->comment_text = trim($_POST['comment_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_SHIFTLOG_SEARCH_KEY);
  $selected_cache_name =  _get_qms_cache_name(QMS_SHIFTLOG_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);

  $sl_search_results = new SearchResultsTable('SL');

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

/**
 * shift_log_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 shift_log_pager_callback() {

  $search = (object) NULL;

  // determine the key cache
  $key_cache_name =  _get_qms_cache_name(QMS_SHIFTLOG_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->tech_id = (int)$_POST['tech'];
    $search->simulator_id = (int)$_POST['simulator'];
    $search->from_date = trim($_POST['from_date']);
    $search->to_date = trim($_POST['to_date']);
    $search->comment_text = trim($_POST['comment_text']);

    // 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
  $sl_search_results = new SearchResultsTable('SL');

  _get_shift_log_search_list($search, $sl_search_results);
  $form_elems = drupal_get_form('results_list_form', $sl_search_results);
  $content = render($form_elems);
  die($content);
}

/*
 * shift_log_results_callback()
 *
 * Clears the search results cache
 *
 */
function shift_log_clear_results_callback() {

  // Clear the cache

  // determine cache name
  $results_cache_name = _get_qms_cache_name(QMS_SHIFTLOG_SEARCH_RESULTS);
  $key_cache_name =  _get_qms_cache_name(QMS_SHIFTLOG_SEARCH_KEY);
  $selected_cache_name =  _get_qms_cache_name(QMS_SHIFTLOG_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);
}
