<?php

/*
 *	  CLASS:  CustomerList
 *
*/

class CustomerList {
  private $active = array();
  private $all = array();

  private $all_opt = array();
  private $select_opt = array();

  const INCL_ALL = -1;
  const NO_SELECT_OPT = -2;

  function __construct() {
    $this->init();
  }

  private function init() {
    try {
      $this->all_opt = array(0 => '- ' . t('All') . ' -');
      $this->select_opt = array(0 => '- ' . t('Select') . ' -');

      $list_cache = cache_get(QMS_CUSTOMER_LIST);
      if ( isset($list_cache->data) && ($list_cache->data <> '') ) {
        $this->active = $list_cache->data->get_active();
        $this->all = $list_cache->data->get_all();
      }
      else {
        $sql = "SELECT customer_id, customer, active FROM {qms_customers} ORDER BY customer";
        $results = db_query($sql);

        $this->all[0] = '- Select -';  // add default option
        $this->active[0] = '- Select -';

        foreach($results as $row) {
          $this->all[$row->customer_id] = $row->customer . ($row->active ? '' : '*');;
          if ( $row->active ) {
            // add only if tech user is active
            $this->active[$row->customer_id] = $row->customer;
          }
        }
        // cache the tech list object for the next time
        cache_set(QMS_CUSTOMER_LIST, $this, 'cache', time() + QMS_CACHE_TIMEOUT);
      }
    }
    catch (Exception $e) {
      watchdog('sabreQMS', 'CustomerList::init() ' . $e->getMessage(), array(), WATCHDOG_ERROR);
    }
  }

  public function get_active() {
    return $this->get(True);
  }
  public function getActive($flag = 0) {
    return $this->get(True, $flag);
  }

  public function get_all() {
    return $this->get(False);
  }
  public function getAll($flag = 0) {
    return $this->get(False, $flag);
  }

  public function get($active_only = False, $flag = 0) {

    if ($flag == self::NO_SELECT_OPT) {
      return ($active_only ? $this->active : $this->all);
    }
    if ($flag == self::INCL_ALL) {
      return $this->all_opt + ($active_only ? $this->active : $this->all);
    }
    return $this->select_opt + ($active_only ? $this->active : $this->all);
  }

  public function get_unassigned($assigned_customer_list = array()) {

    // if an $assigned_user_list is passed as a parm,
    // remove those users from the user list returned
    // returns all items in $this->all not in the $assigned_user_list

    return array_diff($this->active, $assigned_customer_list);
  }

  public function getName($id) {
    if ( $id && isset($this->all[$id])  ) {
      return $this->all[$id];
    }
    return '';
  }

  public function reload() {
    _clear_qms_cache(QMS_CUSTOMER_LIST);
    _clear_qms_cache(QMS_DISCREPANCY_SEARCH_FORM);

    unset($this->active);
    unset($this->all);
    $this->init();
  }

} // end - class CustomerList
