<?php
// $Id$

/**
 *		@file
 *		sabreQMS Module for plugin to Drupal 7 Framework
 *
 *		Vendor Search List functions
 *
*/


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

function _get_vendor_results_table_header($admin=False) {
  $table_header = array(
    'vendor_code' => array( 'data' => 'Code', 'field' => 'code', 'sort' => 'asc', 'class' => array('qms-vendor-results-code') ),
    'vendor_name' => array( 'data' => 'Name', 'field' => 'name', 'sort' => 'asc', 'class' => array('qms-vendor-results-name') ),
    'vendor_website' => array( 'data' => 'Website', 'field' => 'website', 'sort' => '', 'class' => array('qms-vendor-results-website') ),
    'vendor_email' => array( 'data' => 'Email', 'field' => 'email_1', 'sort' => '', 'class' => array('qms-vendor-results-email') ),
    'vendor_phone' => array( 'data' => 'Phone', 'field' => 'phone_1', 'sort' => '', 'class' => array('qms-vendor-results-phone') ),
    //'admin' => array( 'data' => 'Admin', 'class' => array('qms-results-admin')),
  );
  if ( $admin ) {
    $table_header['admin'] = array( 'data' => 'Admin', 'class' => array('qms-results-admin'));
  }

  return $table_header;
}


/*
 * _get_vendor_search_list()
 * display the search results
 * This function gets called by vendor_search_form_callback() and vendor_pager_callback()
 * also gets called after a delete submit to refresh the cache ($bRefresh = True), but does not return anything
 *
 */

function _get_vendor_search_list($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');

  global $user;


  $num_per_page =  QMS_RECORDS_PER_PAGE;
  $table_header = array();

  if ( $search_results == Null ) {
    $search_results = new SearchResultsTable('VE');
  }
  if ( !$search_results->hasHeader() ) {
    $table_header = _get_vendor_results_table_header($bAdmin);
    $search_results->setHeader($table_header);
  }
  else {
    $table_header = $search_results->getHeader();
  }

  // get the selected cache, if anything has been stored
  $saved_selected_text = '';
  $selected_cache_name = _get_qms_cache_name(QMS_VENDOR_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_vendors',
    'table_alias' => 'v',
    'table_header' => $table_header,
    'pager_path' => 'search/vendor/pager',
    'order' => QMS_VENDOR_DEFAULT_SORT_COLUMN,
    'order_default' => 'Date',
    'sort' => QMS_VENDOR_DEFAULT_SORT,
    'sort_default' => 'desc',
    'variable' => True,
  );

  $query = _st_setup_paged_search($search_init);


  //--------- search query -----------


  // filter vendors to the customer
  $user_is_customer_id = _user_is_customer($user->uid);

  if ($user_is_customer_id) {
    $query->leftJoin('qms_vendor_customers', 'vc', 'v.vendor_id = vc.vendor_id');
    $query->leftJoin('qms_customers_users', 'cu', 'vc.customer_id = cu.customer_id');
    $query->condition(cu.user_id, $user_is_customer_id);

    $query->leftJoin('qms_employees', 'e', 'cu.user_id = e.user_id');
    $query->leftJoin('users', 'u', 'cu.user_id = u.uid');
  }

  if (!empty($search->code)) {
    $query->condition('v.code', $search->code.'%', 'LIKE');
  }
  if (!empty($search->name)) {
    $query->condition('v.name', '%'.$search->name.'%', 'LIKE');
  }
  if (!empty($search->note)) {
    //---------------------- Keyword Seaching --------------
		// Combo Keyword and Exact Phrase Matching ( ex:  keyword "exact phrase" )
		_st_add_keyword_search_condition($query, 'v.note', $search->note);		
  }
  if (!empty($search->city)) {
    $query->condition('v.city', '%'.$search->city.'%', 'LIKE');
  }
  if (!empty($search->state)) {
    $query->condition('v.state_province', $search->state);
  }
  if (!empty($search->zip)) {
    $query->condition('v.zip_postal', $search->zip.'%', 'LIKE');
  }
  //watchdog(QMS_APP, '_get_vendor_search_list(): ' . var_export($search True), array(), WATCHDOG_DEBUG);


  $q2 = $query->fields('v', array(
                        'vendor_id', 'code', 'name',
                        'address_line_1', 'address_line_2', 'address_line_3',
                        'city', 'state_province', 'zip_postal', 'country',
                        'phone_1', 'phone_2', 'phone_3',
                        'email_1', 'email_2', 'website',
                        'tax_id', 'duns_id'
                      ) );

  if ($user_is_customer_id) {
    $q2 = $query->fields('e', array('full_name'))
                ->fields('u', array('name'));
  }

  // determine if items were selected or not
  if ( strlen($saved_selected_text) ) {
    $list = explode(",", $saved_selected_text);
    $query->addExpression("IF( v.vendor_id IN(:sel_list), :y, :n )", "selected",
                                array(':sel_list' => $list, ':y' => 1, ':n' => 0));
  }
  $max_count = 0;
  $result = _st_execute_paged_search($query, $max_count);


  $i = 0;
  $table_rows = array();
  $selected_list = array();


  foreach ($result as $row) {
    //$comment_cleaned = trim(strip_tags(_st_convert_symbols($row->comment, ENT_QUOTES, 'UTF-8')));

    // set the id into the array index which is linked to the tableselect's checkbox
    $table_rows[$row->vendor_id] = array(
      'vendor_code' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => $row->code,
          '#href' => ('vendor/view/' . $row->vendor_id),
          '#options' => array('query' => array('destination' => 'search/vendor')),
        ),
      ),
      'vendor_name' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => $row->name,
          '#href' => ('vendor/view/' . $row->vendor_id),
          '#options' => array('query' => array('destination' => 'search/vendor')),
        ),
      ),
      'vendor_website' => array('data' => $row->website, 'class' => ''),
      'vendor_email' => array('data' => $row->email_1, 'class' => ''),
      'vendor_phone' => array('data' => $row->phone_1, 'class' => ''),
    );

    if ( $bAdmin ) {
      // don't allow for the column to exist if user is not an admin, otherwise we get an empty column
      $table_rows[$row->vendor_id]['admin'] = array(
        'data' => _get_results_table_options('vendor', $row->vendor_id, $bAdmin, 'search/vendor'),
        'class' => array('qms-results-admin'),
      );

    }

    if ( strlen($saved_selected_text) ) {
      $selected_list[$row->vendor_id] = $row->selected;
    }


    $i++;
  }

  $pager = theme('pager', array('tags' => array(), 'quantity' => $num_per_page));
  $search_results->setPager($pager);
  $search_results->setResults($table_rows);
  $search_results->setSelected($selected_list);

  // Save to cache
  // cache the $search_results object
  // 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
  $results_cache_name = _get_qms_cache_name(QMS_VENDOR_SEARCH_RESULTS);
  cache_set($results_cache_name, $search_results, 'cache', time() + QMS_CACHE_TIMEOUT);

  return $table_rows;



  /*
  if ( $i == 0 ) {
    $table_rows[] = array('data' => array('None', '', '', '', '') );
  }

  $content = '<div id="qms-search-results-div">';

  $content .= theme( 'table', array(
    'header' => $table_header,
    'rows' => $table_rows,
  ));

  //Append pager:  http://api.drupal.org/api/drupal/includes--pager.inc/function/theme_pager
  $content .= theme('pager', array('tags' => array(), 'quantity' => $num_per_page));
  $content .= '</div>';

  // Save to cache
  // determine cache name, linked to user id and session id, expires in 30min
  global $user;
  $results_cache_name = 'QMS_vendor_search_results_' . $user->uid . '_' . $user->sid;

  $vendor_search_results = $content;
  cache_set($results_cache_name, $vendor_search_results, 'cache', time() + (30*60));

  //refreshing cache after an edit or delete, don't return anything here
  if ( $bRefresh ) {
    return;
  }

  // All calls to this function are standard AJAX calls return $content and die
  die($content);
  */
}
