<?
/**
 * VoiceOne Settings/Queues/edit
 *
 * Frontend to provide access to the queue system in voiceone.
 * @package voiceone
 * @subpackage  settings_queues
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php");
  sajax_init();

  //================ XAJAX ================
	function removeAgent($id,$div_id){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract logged agents
  	$availAgents=$asterisk->getRegisteredAgent();
    //build right list
    $ret=$asterisk->getAgent($id);
  	if(is_array($ret)){
    	$v=$ret[0];
      $clientArr=getClient($v["client"]);
      //Is agent linked to an extension?
      if((is_array($clientArr))&&(is_array($clientArr[0]))){
        $client=$clientArr[0];
        $ext=$client["extension"];
        $callerid=$client["name"]." ".$client["surname"];
      	$label="$callerid <$ext>";
      }
      //Is agent linked to a virtual extension?
      else{
      	$virtualArr=getVirtualExtension($v["client"]);
        if((is_array($virtualArr))&&(is_array($virtualArr[0]))){
        	$virtual=$virtualArr[0];
          $ext=$virtual["extension"];
          $callerid=$virtual["name"]." ".$virtual["surname"];
      		$label="$callerid <$ext>";
        }
        //Is agent linked to an application?
       	else{
        	$applArr=getApplication($v["client"]);
          if((is_array($applArr))&&(is_array($applArr[0]))){
          	$appl=$applArr[0];
            $ext=$appl["extension"];
            $callerid=$appl["label"];
  					$label="$callerid <$ext>";
          }
        }
      }
    }
    //put agent in leftList
		$script=" var optObj=document.createElement('option'); ";
		$script.=" optObj.value='".$id."'; ";
		$script.=" optObj.innerText='".addslashes($label)."'; ";   //cross browser fix
    $script.=" optObj.text='".addslashes($label)."'; ";        //cross browser fix
    $script.=" document.getElementById('listLeft').appendChild(optObj); ";
    // Return the xajaxResponse object
    $objResponse->addAssign($div_id,"innerHTML","");
    $objResponse->addScript($script);
    $objResponse->addScript(" document.getElementById('alert').innerHTML=''; ");
    return $objResponse->getXML();
  }  
  function addAgent($id){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract logged agents
  	$availAgents=$asterisk->getRegisteredAgent();
    //build right list
    $ret=$asterisk->getAgent($id);
  	if(is_array($ret)){
    	$v=$ret[0];
      $clientArr=getClient($v["client"]);
      //Is agent linked to an extension?
      if((is_array($clientArr))&&(is_array($clientArr[0]))){
        $client=$clientArr[0];
        $ext=$client["extension"];
        $callerid=$client["name"]." ".$client["surname"];
        //retrieve agent status
        if((is_array($availAgents))&&(in_array($ext,$availAgents))){
          $icon="<img src=\"$relBasePath/public/img/agent_on.gif\" />";
        }else{
          $icon="<img src=\"$relBasePath/public/img/agent_off.gif\" />";
        }
      	$label="$icon  $callerid &lt;$ext&gt;";
      }
      //Is agent linked to a virtual extension?
      else{
      	$virtualArr=getVirtualExtension($v["client"]);
        if((is_array($virtualArr))&&(is_array($virtualArr[0]))){
        	$virtual=$virtualArr[0];
          $ext=$virtual["extension"];
          $callerid=$virtual["name"]." ".$virtual["surname"];
          //retrieve agent status
          if((is_array($availAgents))&&(in_array($ext,$availAgents))){
            $icon="<img src=\"$relBasePath/public/img/agent_on.gif\" />";
          }else{
            $icon="<img src=\"$relBasePath/public/img/agent_off.gif\" />";
          }
      		$label="$icon  $callerid &lt;$ext&gt;";
        }
        //Is agent linked to an application?
       	else{
        	$applArr=getApplication($v["client"]);
          if((is_array($applArr))&&(is_array($applArr[0]))){
          	$appl=$applArr[0];
            $ext=$appl["extension"];
            $callerid=$appl["label"];
            //retrieve agent status
            if((is_array($availAgents))&&(in_array($ext,$availAgents))){
              $icon="<img src=\"$relBasePath/public/img/agent_on.gif\" />";
            }else{
              $icon="<img src=\"$relBasePath/public/img/agent_off.gif\" />";
            }
  					$label="$icon  $callerid &lt;$ext&gt;";
          }
        }
      }
    }
    //create div id
    $div_id="agent_".$id."_".rand("00000000","99999999");
    //html
    ob_start();
    ?>
    	<div style="padding:0;margin:0;border:0;display:inline;" id="<?=$div_id?>">
      	<div style="float:left;width:60px;"><a href="" onclick="xajax_removeAgent('<?=$id?>','<?=$div_id?>'); return false;"><img src="<?=$relBasePath?>/public/img/trash.gif"/></a></div>
        <div style="float:left;width:250px;">
        	<?=$label?>
          <input type="hidden" id="agents[<?=$id?>]" name="agents[<?=$id?>]" value="<?=$id?>" />
        </div>
        <div style="float:left;">
        	<span style="color:#333;"><?=T_('Priority')?>: </span>
          <input style="vertical-align:middle;padding:1px;" type="text" size="2" maxlength="2" id="penalty[<?=$id?>]" name="penalty[<?=$id?>]" value="<?=$penalty?>" />
          <span class="help">(<?=T_('leave black for priority 0')?>)</span>
        </div>
        <div style="clear:both;"></div>
        <hr/>
      </div>
    <?
    $html=ob_get_contents();
  	ob_end_clean();  
    // Return the xajaxResponse object
    $objResponse->addScript(" document.getElementById('queue_empty').innerHTML=''; "); 
    $objResponse->addAppend("agent_list","innerHTML",$html);
    $objResponse->addScript(" document.getElementById('listLeft').remove(document.getElementById('listLeft').selectedIndex); ");
    $objResponse->addScript(" document.getElementById('alert').innerHTML=''; ");
    return $objResponse->getXML();
  }  
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    //extract form params
    $queue=$formData["queue"];
    $id=$queue["id"];
    $name=$queue["name"];
    $agentArr=$formData["agents"];
    $penaltyArr=$formData["penalty"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    // Retrieve all accounts
    $queueArr=$asterisk->getQueue(0);
    if(is_array($queueArr)){
      foreach($queueArr as $q){
        if($id==$q["id"]) continue;
        $qNameArr[]=$q["name"];
      }
    }
    // Check Name ((not null)&&(unique)&&(no spaces))
    $nameErr=false;
    if($name=="") {
      //name cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else if((is_array($qNameArr))&&(in_array($name,$qNameArr))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
		// Check Members (not null) and Penalty (null)or(numeric)
    $membersErr=false;
    if((!is_array($agentArr))||(count($agentArr)<1)){
      //members list cannot be null
      $errOut[]= T_("Queue's members cannot be null. Please select almost one member");
      $objResponse->addAssign("membersErr","innerHTML",$imgErr);
      $membersErr=true;
    }else if(is_array($penaltyArr)){
    	foreach($penaltyArr as $penalty){
      	if((trim($penalty)!="")&&(!is_numeric($penalty))){
     			//members list cannot be null
          $errOut[]= T_("Penalty must be numeric");
          $objResponse->addAssign("membersErr","innerHTML",$imgErr);
          $membersErr=true;   
        }
      }
    }
   	if($membersErr===false) $objResponse->addAssign("membersErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      $objResponse->addScript(" document.getElementById('mainform').submit(); ");
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();
  }
  $xajax = new xajax();
  $xajax->registerFunction("addAgent");
  $xajax->registerFunction("removeAgent");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();

  //================== POST ====================
  if(count($_POST)>0){
    $data=$_POST["queue"];
    $entry=array(
      "id" => $data["id"],
      "name" => $data["name"]
    );
    //build agents list
    if((is_array($_POST["agents"]))&&(is_array($_POST["penalty"]))){
      foreach($_POST["agents"] as $agent_id){
      	//extract penalty
      	$penalty="";
      	if(isset($_POST["penalty"][$agent_id])) $penalty=$_POST["penalty"][$agent_id];
        if(trim($penalty)=="") $penalty=0;
        //save in entry array
      	$entry["member"][]=array(
        		"id" => $agent_id,
            "penalty" => $penalty
        	);
      }
    }
    //add options to the entry
    foreach ($_POST as $k=>$v) {
      if (substr($k,0,7)=="status_") {
        $k=substr($k,7);
        if ($v=="1") {
          $o["key"]=$k;
          $o["value"]=$_POST["option_".$k];
          $options[]=$o;
        }
      }
    }
    $entry["options"]=$options;
    $ret=$asterisk->putQueue($entry);
    if ($ret>0) {
      $alert="<div class=\"AlertGood\">".T_("The queue has been modified")."</div>";
      $_GET["id"]=$ret;
    } else $alert="<div class=\"AlertBad\">".T_("The queue hasn't been modified")."</div>";
    goToMainPage($alert);
  }

  //================ PAGE LOGIC ================
  //retrieve the queue informations
  if ($_GET["id"]!="") {
    $queue=$asterisk->getQueue($_GET["id"]);
    $queueName=$queue[0]["name"];
    $queueMember=$queue[0]["member"];
    $selOptionArr=array();
    if(is_array($queue[0]["options"])){
      foreach($queue[0]["options"] as $opt){
        $selOptionArr[$opt["key"]]=$opt["value"];
      }
    }
    $title=sprintf(T_("Modify queue: %s"),$queueName );
  }else{
    $title=T_("New queue");
  }
  //Extract logged agents
  $availAgents=$asterisk->getRegisteredAgent();
  //build right list
  $agent_list="";
  $memberArr=array();
  if(is_array($queueMember)){
  	$count=0;
  	foreach($queueMember as $q){
    	$count++;
      $id=$q["id"];
      $penalty=$q["penalty"];
      $ret=$asterisk->getAgent($id);
  		if(is_array($ret)){
      	$v=$ret[0];
        $clientArr=getClient($v["client"]);
        //Is agent linked to an extension?
        if((is_array($clientArr))&&(is_array($clientArr[0]))){
          $client=$clientArr[0];
          $ext=$client["extension"];
          $callerid=$client["name"]." ".$client["surname"];
          //retrieve agent status
          if((is_array($availAgents))&&(in_array($ext,$availAgents))){
            $icon="<img src=\"$relBasePath/public/img/agent_on.gif\" />";
          }else{
            $icon="<img src=\"$relBasePath/public/img/agent_off.gif\" />";
          }
        	$label="$icon  $callerid &lt;$ext&gt;";
        }
        //Is agent linked to a virtual extension?
        else{
        	$virtualArr=getVirtualExtension($v["client"]);
          if((is_array($virtualArr))&&(is_array($virtualArr[0]))){
          	$virtual=$virtualArr[0];
            $ext=$virtual["extension"];
            $callerid=$virtual["name"]." ".$virtual["surname"];
            //retrieve agent status
            if((is_array($availAgents))&&(in_array($ext,$availAgents))){
              $icon="<img src=\"$relBasePath/public/img/agent_on.gif\" />";
            }else{
              $icon="<img src=\"$relBasePath/public/img/agent_off.gif\" />";
            }
        		$label="$icon  $callerid &lt;$ext&gt;";
          }
          //Is agent linked to an application?
         	else{
          	$applArr=getApplication($v["client"]);
            if((is_array($applArr))&&(is_array($applArr[0]))){
            	$appl=$applArr[0];
              $ext=$appl["extension"];
              $callerid=$appl["label"];
              //retrieve agent status
              if((is_array($availAgents))&&(in_array($ext,$availAgents))){
                $icon="<img src=\"$relBasePath/public/img/agent_on.gif\" />";
              }else{
                $icon="<img src=\"$relBasePath/public/img/agent_off.gif\" />";
              }
  						$label="$icon  $callerid &lt;$ext&gt;";
            }
          }
        }
      }
      //create div id
    	$div_id="agent_".$id."_".rand("00000000","99999999");
      //html
      ob_start();
      ?>
      	<div style="padding:0;margin:0;border:0;display:inline;" id="<?=$div_id?>">
        	<div style="float:left;width:60px;"><a href="" onclick="xajax_removeAgent('<?=$id?>','<?=$div_id?>'); return false;"><img src="<?=$relBasePath?>/public/img/trash.gif"/></a></div>
          <div style="float:left;width:250px;">
          	<?=$label?>
          	<input type="hidden" id="agents[<?=$id?>]" name="agents[<?=$id?>]" value="<?=$id?>" />
          </div>
          <div style="float:left;">
          	<span style="color:#333;"><?=T_('Priority')?>: </span>
            <input style="vertical-align:middle;padding:1px;" type="text" size="2" maxlength="2" id="penalty[<?=$id?>]" name="penalty[<?=$id?>]" value="<?=$penalty?>" />
            <span class="help">(<?=T_('leave black for priority 0')?>)</span>
          </div>
          <div style="clear:both;"></div>
          <hr/>
        </div>
      <?
      $agent_list.=ob_get_contents();
  		ob_end_clean();  
      $memberArr[]=$id;
    }
  }
  if(trim($agent_list=="")){
  	//html
    ob_start();
    ?>
    	<div id="queue_empty" style="text-align:center;padding:0;margin:0;border:0;display:block;">
      	<?=T_("Queue is empty. Select an user and add it to the queue")?>
        <div style="clear:both;"></div>
        <hr/>
      </div>
    <?
    $agent_list.=ob_get_contents();
		ob_end_clean();
  }
  //build left list
  $listLeft="";
  $ret=$asterisk->getAgent(0);
  if(is_array($ret)) {
    $extOpt="";$virtualOpt="";
    foreach($ret as $v){
      $id=$v["id"];
      //insert option in the correct column
      if((is_array($memberArr))&&(in_array($id,$memberArr,true))) continue;
      $clientArr=getClient($v["client"]);
      //Is agent linked to an extension?
      if((is_array($clientArr))&&(is_array($clientArr[0]))){
        $client=$clientArr[0];
        $ext=$client["extension"];
        $callerid=$client["name"]." ".$client["surname"];
      	$listLeft.="<option value=\"".$id."\">$callerid &lt;$ext&gt;</option>\n";
      }
      //Is agent linked to a virtual extension?
      else{
      	$virtualArr=getVirtualExtension($v["client"]);
        if((is_array($virtualArr))&&(is_array($virtualArr[0]))){
        	$virtual=$virtualArr[0];
          $ext=$virtual["extension"];
          $callerid=$virtual["name"]." ".$virtual["surname"];
      		$listLeft.="<option value=\"".$id."\">$callerid &lt;$ext&gt;</option>\n";
        }
        //Is agent linked to an application?
       	else{
        	$applArr=getApplication($v["client"]);
          if((is_array($applArr))&&(is_array($applArr[0]))){
          	$appl=$applArr[0];
            $ext=$appl["extension"];
            $callerid=$appl["label"];
						$listLeft.="<option value=\"".$id."\">$callerid &lt;$ext&gt;</option>\n";
          }
        }
      }
    }
  }else $html.="<td><span class=\"help\">".T_("There are no members defined in the system.<br/>Please define almost one extension before creating a queue.")."</span></td>\n";
  //get the configuration option
  $optionArr=$asterisk->getConfOption(0,"QUEUES",SECTION_DEFAULT);
  $html_option=getOption($optionArr,$selOptionArr,false,"");

  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/");
  ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3>
      <a href="../" class="admin" ><?=T_("Return without save")?></a>
    </h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?><? if ($_GET['id']!="") echo "?id=".$_GET['id']; ?>" method="post">
      <div id="client_form" >
        <h2><?=T_("General Informations")?></h2>
        <p class="blockintro"><?=T_("Define the queue general options")?></p>
        <div class="block">
          <dl>
            <!-- Name -->
            <dt class="required"><label for="queue[name]"><?=T_("Name")?>:</label></dt>
            <dd><input type="text" size="25" maxlength="30" id="queue[name]" name="queue[name]" value="<?=$queueName?>" /><span id="nameErr"></span> <?=T_("I.e. administration, tech support,...")?></dd>
          </dl>    
       	</div>
        <!-- Members -->
        <h2><?=T_("Members")?></h2>
        <p class="blockintro"><?=T_("Choose the agents that belongs to this queue")?></p>
        <div class="block">
        	<div id="membersErr" style="float:right;margin:15px 20px 0 0;"></div>
        	<dl>
          	<dt class="required"><label for=""><?=T_('Agents')?>:</label></dt>
          	<dd>
            	<select name="listLeft[]" id="listLeft"><?=$listLeft?></select>&nbsp;&nbsp;
            	<img style="cursor:pointer;" src="<?=$relBasePath?>public/img/add.gif" onclick="xajax_addAgent(document.getElementById('listLeft').options[document.getElementById('listLeft').selectedIndex].value);" />
            </dd>        
        	</dl>
          <div id="agent_list" style="padding: 0 20px;">
          	<hr/>
            <?=$agent_list?>
        	</div>
        </div>
        <!-- Options -->
        <h2><?=T_('Options')?></h2>
        <p class="blockintro"><?=T_('Queue advanced options')?></p>
        <div class="block">
        	<!-- Advanced Options -->
          <table><?=$html_option?></table>
        </div>
      </div>
      <div class="action">
        <?if ($_GET["id"]!="") {?><input type="hidden" name="queue[id]" value="<?=$_GET['id']?>" /><?}?>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
        <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
      <!--
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Annulla" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Salva" />
       -->
      </div>
    </form>
  </div>

  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="queue";include("../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to create a new queue or to modify an existing one. To create a new queue you have to define the name, the list of the agents that receive calls from the queue, the priority order and to press save button on the end of the page. Moreover it's possible to define other advanced settings like queue strategy, periodic announce, etc...")?></p>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
  $smarty->assign("section", "queue");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');

?>

