<?
/**
 * VoiceOne Settings/Rules/incoming/edit
 *
 * Frontend to provide access to the rules system in voiceone.
 * @package voiceone
 * @subpackage  settings_rules
 */
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  
  //================ XAJAX ================
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_("loading")."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form's params
    $id=$formData["id"];
    $name=$formData["name"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">&nbsp;&nbsp;";
    // Retrieve all ruleset
    //$rulesetArr=$asterisk->getRule(0,RULE_INCOMING); //cannot be the same as another incoming or outgoing ruleset
    $rulesetArr=$asterisk->getRule(0,0);               //
    if(is_array($rulesetArr)){
      foreach($rulesetArr as $rs) {
        if($id==$rs["id"]) continue;
        $rsNameArr[]=$rs["name"];
      }
    }
    // Check Name ((not null)&&(unique)&&(alphanumeric))
    $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($rsNameArr))&&(in_array($name,$rsNameArr))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }else{
      //name must be alphanumeric
      for($i=0; $i<strlen($name); $i++){
        $ch=ord($name[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58))||($ch==95)||($ch==45))){
          $errOut[]=sprintf(T_("Rule set name doesn't allow character \" %s \" Please change it"),$name[$i] );
          $objResponse->addAssign("nameErr","innerHTML",$imgErr);
          $nameErr=true;
          break;
        }
      }
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","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("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  
  //==================== POST ====================
  if (count($_POST)>0) {
    $entry=Array(
      "id" => $_POST["id"],
      "name" => $_POST["name"],
      "description" => $_POST["description"],
      "type" => RULE_INCOMING 
    );
    //add jump to structure
    if($_POST["jump_enabled"]!=0){
      //process end of life
      $end_of_life=$_POST["jump"]["end_of_life"];
      list($date,$time)=explode(' ',$end_of_life,2);
      list($day,$month,$year)=explode('-',$date,3);
      $_POST["jump"]["end_of_life"]=$year."-".$month."-".$day." ".$time;
      //add jump structure
      $entry["jump"]=$_POST["jump"];
    }else{
      $entry["jump"]=array();
    }
    //save the group informations
    $ret=$asterisk->putRule($entry);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Rule set created")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Error: Rule set not created")."</div>";
    //return to main page
    goToMainPage($alert);
  }
  //================ PAGE LOGIC ================
  //if modify, read the group informations
  if(isset($_GET["id"])){
    $ret=$asterisk->getRule($_REQUEST["id"],RULE_INCOMING);
    if ($err=$asterisk->getError()) die("Error: $err");
    $id=$ret[0]["id"];
    $name=$ret[0]["name"];
    $description=$ret[0]["description"];
    if((is_array($ret[0]["jump"]))&&($ret[0]["jump"]["id"]!=0)){
      $jump_enabled=1;
      $ruleset_to=$ret[0]["jump"]["ruleset_to"];
      $end_of_life=$ret[0]["jump"]["end_of_life"];
      list($date,$time)=explode(' ',$end_of_life,2);
      list($day,$month,$year)=explode('-',$date,3);
      $end_of_life=$year."-".$month."-".$day." ".$time;
    }
    // the name can't be changed, because of it is written all over the asterisk
    $disableName=" disabled=\"disabled\" ";
  }else{
    $jump_enabled=0;
  }
  //get all rulset list
  $ret=$asterisk->getRule(0,RULE_INCOMING);
  if((is_array($ret))&&(count($ret)>1)){
    $disabledJump="";
    $rulesetOpt="";
    foreach($ret as $r){
      if($r["id"]==$id) continue;
      if($r["id"]==$ruleset_to) $selected="selected=\"seleceted\""; else $selected="";
      $rulesetOpt.="<option value=\"".$r["id"]."\" $selected>".$r["name"]."</option>";
    }
  }else{
    $rulesetOpt="<option value=\"0\">[".T_("None")."]</option>";
    $disabledJump="disabled=\"disabled\"";
  }
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/"); 
  ?>
  <?$sel="incoming";include("../../navigation.php");?>
  
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=T_("Incoming rule set")?></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?>" method="post" onsubmit="document.getElementById('alert').innerHTML=''; location.href='#'; xajax_processFormData(xajax.getFormValues('mainform')); return false;" > 
      <!-- GENERAL INFORMATIONS -->
      <p class="blockintro"></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="name"><?=T_("Name")?>:</label></dt>
          <dd><input type="text" size="25" maxlength="30" id="name" name="name" value="<?=$name?>" <?=$disableName?>/></dd>
          <dt class="required"><label for="description"><?=T_("Description")?>:</label></dt>
          <dd><textarea rows="10" cols="40" id="description" name="description"><?=$description?></textarea></dd>
        </dl>
      </div>
      <!-- RULESET JUMP -->
      <h2><?=T_("Ruleset Jump")?></h2>
      <p class="blockintro"><?=T_("If set, all calls sent to this ruleset will be forwarded to the target one")?></p>
      <div class="block">
        <dl>
          <dt class="required"><label for="name"><?=T_("Enabled")?>:</label></dt>
          <dd>
            <input type="radio" name="jump_enabled" value="0" onclick="document.getElementById('ruleset_to').disabled='disabled';document.getElementById('end_of_life').disabled='disabled';" <? if($jump_enabled==0) echo "checked=\"checked\""; ?>>
            <?=T_("Off")?>
            <input style="margin-left:15px;" type="radio" name="jump_enabled" value="1" onclick="document.getElementById('ruleset_to').disabled='';document.getElementById('end_of_life').disabled='';" <? if($jump_enabled==1) echo "checked=\"checked\""; ?> <?=$disabledJump?>>
            <?=T_("On")?>
          </dd>
          <dt class="required"><label for="name"><?=T_("Target")?>:</label></dt>
          <dd><select id="ruleset_to" name="jump[ruleset_to]" <? if($jump_enabled==0) echo "disabled=\"disabled\""; ?>><?=$rulesetOpt?></select></dd>
          <dt class="required"><label for="name"><?=T_("Validity")?>:</label></dt>
          <dd>
            <input type="text" size="25" maxlength="30" id="end_of_life" name="jump[end_of_life]" value="<?=$end_of_life?>" <? if($jump_enabled==0) echo "disabled=\"disabled\""; ?>/>
            <a onclick="jumpEOL.popup();" href="#"><img src="<?=$relBasePath?>/public/js/calendar/img/cal.gif"/></a>
            <a onclick="document.getElementById('end_of_life').value=''; return false" href="#"><img src="<?=$relBasePath?>/public/js/calendar/img/del.gif"/></a>
            <span class="help"><?=T_("(DD-MM-YYYY hh:mm:ss)")?></span>
            <script>
              jumpEOL = new calendar(document.getElementById('end_of_life')); 
              jumpEOL.year_scroll = true; 
              jumpEOL.time_comp = true;
            </script>
          </dd>
        </dl>
      </div>
      <!-- BUTTONS -->
      <div class="action">
        <?if (isset($_GET["id"])) {?><input type="hidden" name="id" value="<?=$id?>" /><input type="hidden" name="name" value="<?=$name?>" /><?}?>
        <input type="image" align="right" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save"  />
        <img style="cursor: pointer;" vspace="2" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;" />
      <!--
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>
        <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" />
       -->
      </div>
    </form>
   </div>  
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to create a new ruleset or to modify an existing one. To create a new ruleset you have to define the name of the rulset and to press save button on the end of the page. You cannot modify rulset name once you have created it.")?></p>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================

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

