<?php

  /**
   * select_assignee helper
   *
   * @package activeCollab.frameworks.assignees
   * @subpackage helpers
   */
  
  /**
   * Render select assignee select box
   * 
   * Parameters:
   * 
   * - parent - Parent object
   * - user - User who'll be using the form
   *
   * @param array $params
   * @param Smarty $smarty
   * @return string
   */
  function smarty_function_select_assignee($params, &$smarty) {
    $parent = array_required_var($params, 'parent', true, 'IAssignees');
    $user = array_required_var($params, 'user', true, 'IUser');
    
    $value = array_var($params, 'value', null, true);
    
    if(empty($params['id'])) {
      $params['id'] = HTML::uniqueId('select_assignee');
    } // if
    
    if(isset($params['class'])) {
      $params['class'] .= ' select_assignee';
    } else {
      $params['class'] = 'select_assignee';
    } // if

    $grouped = $parent->assignees()->getAvailableUsersForSelect($user);

    // prepare assignee's information in case he's archived/trashed/deleted
    if ($value !== null) {
      $assignee = Users::getForSelectByConditions(array("id = ?", $value));

      if (is_foreachable($assignee)) {
        $assignee_company = key($assignee);
        $assignee_id = key($assignee[$assignee_company]);
        $assignee_display_name = $assignee[$assignee_company][$assignee_id];
      } // if
    } else {
      $assignee = null;
    } // if
    
    $options = array();
    if(is_foreachable($grouped)) {

      // put assignee's company to the list if he's the only one visible in it
      if (is_foreachable($assignee) && !array_key_exists($assignee_company, $grouped)) {
        $grouped[$assignee_company][$assignee_id] = $assignee_display_name;
      } // if

      foreach($grouped as $group_name => $users) {
        $group_options = array();

        // push assignee into the list if he doesn't exist in visible users list
        if (is_foreachable($assignee) && $group_name == $assignee_company && !array_key_exists($assignee_id, $users)) {
          $users[$assignee_id] = $assignee_display_name;
        } // if
        
        foreach($users as $user_id => $user_display) {
          $group_options[] = HTML::optionForSelect($user_display, $user_id, $user_id == $value);
        } // foreach
        
        $options[] = HTML::optionGroup($group_name, $group_options);
      } // foreach
    } // if
    
    return array_var($params, 'optional', true, true) ?
      HTML::optionalSelect($params['name'], $options, $params, lang('Nobody')) :  
      HTML::select($params['name'], $options, $params);
  } // smarty_function_select_assignee