<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Utility functions
 *
*/



// ------- utility functions -------



/*
 *		_get_results_table_options()
 *
 *		creates the edit & view options links in ajaxed results tables where permissions allow
 */


function _get_results_table_options($table, $id, $allow_edit = False, $destination = '') {

  $links = '&nbsp;';

  if ( $allow_edit == True )
  {
    $links .= l( t('Edit'), "$table/edit/$id",
                     array('attributes' => array('class' => array($table . '-edit'),
                          'query' => array('destination' => $destination),
                ) ));
  }

  return $links;
}



function _get_dew_table_options($id, $allow_edit = False) {
/* Handling VIEW as a link from the DR No
  $links = l( t('View'), "discrepancy/dew_view/$id",
         array('attributes' => array('class' => 'discrepancy-view') ) );
  $links .= "&nbsp;&nbsp;";
  $links .= l( t('Print'), "$table/print/$id",
         array('attributes' => array('class' => 'discrepancy-print') ) );
*/
  $links = '';
  if ( $allow_edit == True ) {
    //$links .= "&nbsp;&nbsp;";
    // last parameter sets the return route after the discrepancy report view has been closed
    // from here returns to the discrepancy early warning page

    $links .= l( t('Edit'), "discrepancy/edit/" . $id,
           array('attributes' => array('class' => array('discrepancy-edit'),
                                       'query' => array(
                                          'destination' => 'reports/discrepancy_early_warning'
                                        ) ) ));
  }
  return $links;
}

/*
 *	_check_if_selected()
 *
 *  This function fills the gap for when a search is made, then specific reports are selected, but
 *  done so after the results were cached so the selections were not cached with them
 *  selections have their own cache, but need to be retrieved and processed against the current
 *  results list to determine if the items should be checked or not in the display.
 *  This function needs to be called before the drupal_get_form(xxxxxxxxxxxxx_results_list_form)
 *
 */
function _check_if_selected($selected_cache_name, $search_results) {

  // check if any selections have been made after last search was made

  $selected_cache = cache_get($selected_cache_name);
  if ( isset($selected_cache->data) && ($selected_cache->data <> '') ) {
    $saved_selected_text = $selected_cache->data;

    if ( strlen($saved_selected_text) ) {
      $saved_selected_list = explode(",", $saved_selected_text);
      $mark_list = array();

      // check if any of the current dr results exists in the saved selection list
      $id_list = $search_results->getResultIds();
      foreach ($id_list as $id) {
        //$found = array_search((string)$id, $saved_selected_list);
        if ( False === array_search((string)$id, $saved_selected_list) ) {
          $mark_list[$id] = False;
        }
        else {
          $mark_list[$id] = True;
        }
      }
      $search_results->setSelected($mark_list);
    }
  }
  else {
    // turn off selections
    $mark_list = array();
    $search_results->setSelected($mark_list);
  }
}

/*
 * result_list_selection_callback()
 *
 * saves the selected items in a search results list to a "selected" cache
 */

function result_list_selection_callback($report_type) {
  $selected_text = $_POST['selected'];
  $unselected_text = $_POST['unselected'];

  // determine the selected dr cache
  global $user;

  $saved_selected_text = '';
  $saved_selected_list = array();
  $selected_cache_name = _get_qms_cache_name($report_type);

  $selected_cache = cache_get($selected_cache_name);
  if ( isset($selected_cache->data) && ($selected_cache->data <> '') ) {
    $saved_selected_text = $selected_cache->data;
    $saved_selected_list = explode(",", $saved_selected_text);
  }


  if ( strlen($selected_text) ) {
    // take the text list (comma-separated) and separate it into an array of dr ids
    $selected_list = explode(",", $selected_text);

    if ( count($saved_selected_list) ) {
      // if there is a selected dr list in the cache,
      // merge the new selections into the stored selections
      // then remove the duplicate ids from the array
      $tmp_list = array_merge($saved_selected_list, $selected_list);
      $saved_selected_list = array_unique($tmp_list, SORT_NUMERIC);
    }
    else {
      // there are no saved selections in the cache, current selections are the new list
      // no need to merge or remove duplicates
      $saved_selected_list = $selected_list;
    }
  }

  if ( strlen($unselected_text) ) {
    $unselected_list = explode(",", $unselected_text);

    if ( count($saved_selected_list) ) {
      // if there is a saved selected dr list in the cache,
      // remove the unselected ids from the list
      $saved_selected_list = array_diff($saved_selected_list, $unselected_list);
    }
    // if there isn't a saved selected list, disregard the unselected items
  }

  if ( count($saved_selected_list) ) {
    // store in cache
    $saved_selected_text = join(",", $saved_selected_list);

    // cache the latest search key
    cache_set($selected_cache_name, $saved_selected_text, 'cache', time() + QMS_CACHE_TIMEOUT);
  }
  else {
    cache_clear_all($selected_cache_name, 'cache', TRUE);
  }

  die($saved_selected_text);
}

/*
 * results_list_form()
 * builds the search results table (tableselect) only
 * made generic for discrepancies, engineering log, and shiftlog
 *
 */

function results_list_form($form, $form_state, $search_results) {

  $report_url = "";
  $selection_url = "";
  $return_url = '';

  switch ($search_results->getType()) {
    case 'DR':
      $report_url = url('reports/discrepancies/selected');
      $selection_url = url('search/discrepancy/selection');
      $return_url = 'search/discrepancies';
      break;
    case 'ENG':
      $report_url = url('reports/engineering/selected');
      $selection_url = url('search/engineering/selection');
      $return_url = 'search/engineering';
      break;
    case 'SL':
      $report_url = url('reports/shiftlog/selected');
      $selection_url = url('search/shiftlog/selection');
      $return_url = 'search/shiftlog';
      break;
    case 'TC':
      $report_url = url('reports/troublecalls/selected');
      $selection_url = url('search/troublecalls/selection');
      $return_url = 'search/troublecalls';
      break;
    case 'QTG':
      $report_url = url('reports/qtg/selected');
      $selection_url = url('search/qtg/selection');
      $return_url = 'search/qtg';
      break;
    case 'VE':
      $report_url = url('reports/vendors/selected');
      $selection_url = url('search/vendors/selection');
      $return_url = 'search/vendors';
      break;
  }

  //Build the tableselect
  $form['results'] = array(
    '#type' => 'container',
  );

  $form['results']['create_report'] = array(
    '#markup' => l( t('Create Report'), '',
                    array('attributes' => array('id' => 'qms-btn-create-report',
                                                'qms-url' => $report_url ),
                          'query' => array('destination' => $return_url) ) ),
  );

  $form['results']['pager_top'] = array(
    '#type' => 'item',
    '#markup' => $search_results->getPager(),
  );

  $form['results']['result_list'] = array(
    '#type' => 'tableselect',
    '#header' => $search_results->getHeader(),
    '#options' => $search_results->getResults(),
    '#js_select' => True,
    '#multiple' => True,
    '#advanced_select' => True,
    '#empty' => t('None'),
    '#sticky' => True,
    //'#default_value' => $search_results->getSelected(),
    '#attributes' => array('id' => 'qms-results-table',
                            'qms-url' => $selection_url,
                            'summary' => 'table displays search result data'),
  );

  // do this here since it causes problems if the #default_value is set with an empty array
  if ( $search_results->getSelectedCount() ) {
      $form['results']['result_list']['#default_value'] = $search_results->getSelected();
  }

  $form['results']['pager_bottom'] = array(
    '#type' => 'item',
    '#markup' => $search_results->getPager(),
  );

  //$form['text_popup'] = array(
    //'#markup' => '<div id="qms-text-popup"></div>',
  //);


  return $form;
}

/*
 * _get_cache_name()
 * constructs the cache name for user/session specific caches
 * for forms, just echos the const name
 *
 */

function _get_qms_cache_name($cache_name_const) {

  $name = '';

  switch ($cache_name_const) {
    // this group is the shared cache across all QMS users
    case QMS_DISCREPANCY_SEARCH_FORM:
    case QMS_TROUBLECALL_SEARCH_FORM:
    case QMS_SHIFTLOG_SEARCH_FORM:
    case QMS_ENGINEERING_SEARCH_FORM:
    case QMS_SIMULATORDOWNTIME_SEARCH_FORM:
    case QMS_PUNCHCLOCKEVENT_SEARCH_FORM:
    case QMS_QTG_SEARCH_FORM:
    case QMS_VENDOR_SEARCH_FORM:
    case QMS_TECHNICIAN_LIST:
    case QMS_CUSTOMER_LIST:
    case QMS_SIMULATOR_LIST:
    case QMS_ATACHAPTER_LIST:
    case QMS_LOAD_UPDATED_LIST:
    case QMS_TROUBLE_CAUSE_LIST:
    case QMS_CORRECTIVE_ACTION_LIST:
      $name = $cache_name_const;
      break;
    default:		// this is to handle user-specific cache, such as searches
      global $user;
      $name = $cache_name_const . '_' . $user->uid . '_' . $user->sid;
  }
  return $name;
}

function _clear_qms_cache($cache_name_const) {
  switch ($cache_name_const) {
    case QMS_DISCREPANCY_SEARCH_FORM:
    case QMS_TROUBLECALL_SEARCH_FORM:
    case QMS_SHIFTLOG_SEARCH_FORM:
    case QMS_ENGINEERING_SEARCH_FORM:
    case QMS_SIMULATORDOWNTIME_SEARCH_FORM:
    case QMS_PUNCHCLOCKEVENT_SEARCH_FORM:
    case QMS_QTG_SEARCH_FORM:
    case QMS_VENDOR_SEARCH_FORM:
    case QMS_TECHNICIAN_LIST:
    case QMS_CUSTOMER_LIST:
    case QMS_SIMULATOR_LIST:
    case QMS_ATACHAPTER_LIST:
    case QMS_LOAD_UPDATED_LIST:
    case QMS_TROUBLE_CAUSE_LIST:
    case QMS_CORRECTIVE_ACTION_LIST:
      $name = $cache_name_const;
      break;
    default:
      global $user;
      $name = $cache_name_const . '_' . $user->uid . '_' . $user->sid;
  }
  cache_clear_all($name, 'cache', TRUE);
}


/*
 * _get_user_name()
 *
 *	returns:  returns in this order of priority
 *						(1) qms_employees.full_name, if found
 *						(2) user.name, if found
 *  					(3) empty string, if (1) or (2) not found or user_id=0
 *
 */
function _get_user_name($user_id) {

  if ( (int)$user_id == 0 ) {
    return '[unassigned]';
  }

  $user_is_customer_id = _user_is_customer($user_id);

  if ( $user_is_customer_id ) {
    $sql = "SELECT u.name, c.customer FROM {users} u, {qms_customers} c
            WHERE u.uid = :uid AND c.customer_id = :cid";
    $result = db_query($sql, array(':uid' => $user_id, ':cid' => $user_is_customer_id));
    if ( $result->rowCount() == 0 ) {
      return '[not found]';
    }
    $customer = $result->fetchObject();
    return $customer->name . " from " . $customer->customer;
  }
  else {
    $flag = '';
    $sql = "SELECT full_name FROM {qms_employees} WHERE user_id = :uid";
    $result = db_query($sql, array(':uid' => $user_id));
    if ( $result->rowCount() == 0 ) {
      // nothing found ?? try the users table as an alternate

      $sql = "SELECT name FROM {users} WHERE uid = :uid";
      $result = db_query($sql, array(':uid' => $user_id));

      if ( $result->rowCount() == 0 ) {
        return '[not found]';
      }
      $flag = "*";  //flag indicator that the user is NOT an employee
    }
    return ( $result->fetchField() . $flag );
  }
}

/*
 * _get_user_access_discrepancy_edit()
 *
 */
function _get_user_access_discrepancy_edit() {
  $allow = False;

  $allow = ( 	user_access('edit discrepancy') 				||
                 user_access('set discrepancy flags') 		||
                 user_access('close discrepancy') 				||
                 user_access('add discrepancy comments') ||
                user_access('edit discrepancy comments') ||
                user_access('add discrepancy parts') 		||
                user_access('edit discrepancy parts') 	||
                user_access('add discrepancy files') 		||
                user_access('delete discrepancy files') );
  return $allow;
}



/*
 *	_get_customer_emails($discrepancy_id)
 *	if this discrepancy's simulator is linked to a customer with customer-user accounts assigned,
 *	return a list of all the emails for the linked customer
 *  Formatted as:  user1@example.com, user2@example.com, user3@example.com
 */
function _get_customer_emails($discrepancy_id) {
  $emails = '';

  if ( (int)$discrepancy_id == 0 ) {
    return $emails;
  }

  $sql = "SELECT u.mail
          FROM {users} u, {qms_customers_users} cu, {qms_simulators} s, {qms_discrepancy_log} d
          WHERE u.uid = cu.user_id
          AND cu.customer_id = s.customer_id
          AND s.simulator_id = d.simulator_id
          AND d.discrepancy_id = :did";

  $results = db_query($sql, array(':did' => $discrepancy_id));

  foreach( $results as $row ) {
    $emails .= ( strlen($emails) ? (', ' . $row->mail) : $row->mail );
  }
  return $emails;
}



/*
 *
 *	_user_is_employee($user_id)
 *
 *	Returns True|False whether a user is an employee
 */
function _user_is_employee($user_id) {
  $is_employee = False;

  // check if user exists in employee table
  $sql = "SELECT user_id FROM {qms_employees} WHERE user_id = :uid";
  $result = db_query($sql, array(':uid' => $user_id));

  if ( $result->rowCount() > 0) {
    // user is an employee
    $is_employee = True;
  }

  return $is_employee;
}

/*
 *
 *	_user_is_customer($user_id)
 *
 *	Returns customer_id|False whether a user is linked to a customer record.
 */
function _user_is_customer($user_id) {
  $is_customer = 0;

  // check if user exists in customer-user table
  $sql = "SELECT customer_id FROM {qms_customers_users} WHERE user_id = :uid";
  $result = db_query($sql, array(':uid' => $user_id));

  if ( $result->rowCount() > 0) {
    // user is a customer
    $is_customer = $result->fetchField();
  }

  return $is_customer;
}

/*
 *
 *	_get_simulator_customer_name($simulator_id)
 *
 *	Returns customer name based on the simulator_id
 */
function _get_simulator_customer_name($simulator_id) {

  if ( $simulator_id == 0 ) return "";

  // check if user exists in customer-user table
  $sql = "SELECT customer FROM {qms_customers} c
          INNER JOIN {qms_simulators} s ON s.customer_id = c.customer_id
          WHERE simulator_id = :sid";
  $result = db_query($sql, array(':sid' => $simulator_id));

  if ( $result->rowCount() > 0) {
    // get the customer name
    return $result->fetchField();
  }

  return '';
}



/*
 *
 *	_user_is_inactive_customer($user_id)
 *
 *	Returns True|False whether a user is linked to a customer record.
 */
function _user_is_inactive_customer($user_id) {
  $in_active = False;

  // check if user is linked an inactive customer
  $sql = "SELECT cu.customer_id
          FROM {qms_customers} c, {qms_customers_users} cu
          WHERE cu.user_id = :uid
          AND   cu.customer_id = c.customer_id
          AND   c.active = 0";
  $result = db_query($sql, array(':uid' => $user_id));

  if ( $result->rowCount() > 0) {
    $in_active = True;
  }

  return $in_active;
}

/*
 *
 *	_get_discrepancy_simulator($discrepancy_id)
 *
 *	Returns simulator name based on the discrepancy_id
 */
function _get_discrepancy_simulator($discrepancy_id) {

  if ( $discrepancy_id == 0 ) return "";

  global $simulator_list;

  // get the simulator name for this discrepancy
  $sql = "SELECT simulator_id FROM {qms_discrepancy_log} d
          WHERE discrepancy_id = :did";
  $sim_id = db_query($sql, array(':did' => $discrepancy_id))->fetchField();

  if ( $sim_id ) {
    $simulator_list->getName($sim_id);
  }

  return '';
}

/*
 *
 *	_get_discrepancy_simulator_id($discrepancy_id)
 *
 *	Returns simulator name based on the discrepancy_id
 */
function _get_discrepancy_simulator_id($discrepancy_id) {

  if ( $discrepancy_id == 0 ) return 0;

  // get the simulator name for this discrepancy
  $sql = "SELECT simulator_id
          FROM  {qms_discrepancy_log}
          WHERE discrepancy_id = :did";
  $result = db_query($sql, array(':did' => $discrepancy_id));

  if ( $result->rowCount() > 0) {
    return $result->fetchField();
  }

  return 0;
}
