<?
/**
 * VoiceOne Settings/User/edit
 *
 * Frontend to provide access to the tech system in voiceone.
 * @package voiceone
 * @subpackage  settings_user
 */

  include ("../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
 	sajax_init();

  //================ PAGE LOGIC ================
  if (count($_POST)>0) {
    $data=$_POST["user"];
    //define user structure
    $entry=Array(
            "username" => $data["username"],
            "lang" => $data["language"],
            "type" => $data["type"],
            "entity_id" => $data["entity_id"]
          );
    if($data["id"]!="") $entry["id"]=$data["id"]; //modify mode or insert mode?
    $pwd_error="";
    if((isset($data["changepwd"]))&&($data["changepwd"]=="on")){ //check password
      if($data["newpassword"]!=""){
        if($data["newpassword"]==$data["confirmpassword"]){
          $entry["password"] = $data["newpassword"];
        }else $pwd_error=T_("The new password and the confirmation password do not match");
      }else $pwd_error=T_("The new password cannot be null");
    }else $entry["password"]=$data["password"];
    //create/update user
    $putted=false;
    if($pwd_error=="") {
      $ret=$asterisk->putUser($entry);
      if($ret>0){
        $alert="<div class=\"AlertGood\">".T_("The user has been modified")."</div>";
        $putted=true;
      }else $alert="<div class=\"AlertBad\">".T_("The user hasn't been modified")."</div>";
    }else $alert="<div class=\"AlertBad\">".$pwd_error."</div>";
    //put Fax
    unset($entry);
    $entry=array();
    if(($putted===true)&&(_isModuleLoaded('fax'))){
      $entry=array(
          'id' => $ret,
          'notify_address' => $_POST["fax_notify"],
          'can_delete' => $_POST["fax_candel"],
          'list' => $_POST["faxes"]
        );
      $ret=$asterisk->addFaxtoUser($entry);
      if($ret<1){
        $alert="<div class=\"AlertGood\">".T_("Error posting Fax permissions (User successfully saved)")."</div>";
        $putted=false;
      }
    }
    goToMainPage($alert);
  }

  //get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getUser($id);
    if ($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $username=$v["username"];
    $password=$v["password"];
    $lang=$v["lang"];
    $type=$v["type"];
    $entity_id=$v["entity_id"];
    //check if it is locked
    if($entity_id>0) $disabled=" disabled=\"disabled\" "; else $disabled="";
    $title=sprintf(T_("Modify user: %s"),$username );
   	// is entity a vistual extension? If yes set username and password as hidden fields
  	$ret=$asterisk->getVirtualExtension($entity_id);
  	if((is_array($ret))&&(is_array($ret[0]))){
    	$hiddenFields="<input type=\"hidden\" name=\"user[username]\" value=\"".$username."\" />".
      							"<input type=\"hidden\" name=\"user[password]\" value=\"".$password."\" />";
    }
  }else $title=T_("New user");
  //create the language list
  $availLang=getAvailLang();
  if(is_array($availLang)){
    foreach($availLang as $l) {
      if($l['key']==$lang) $s="selected=\"selected\""; else $s="";
      $select.="<option value=\"".$l['key']."\" $s>".$l['value']."</option>\n";
    }
  }
  //fax list
  if(_isModuleLoaded('fax')){
    $faxList='';
    $fax_res=getFaxFromUser($id);
    if(is_array($fax_res)){
      $fax_notify=$fax_res['notify_address'];
      $fax_can_delete=$fax_res['can_delete'];
      $faxes=$fax_res['list'];
    }else{
      $faxes=array();
    }
    $faxArr=$asterisk->getFaxExtension(0);
    if(is_array($faxArr)){
      $count=0;
      foreach($faxArr as $f){
        if($f['allow_everyone']==1){
          $c="checked=\"checked\"";
          $d="disabled=\"disabled\"";
        }else if((is_array($faxes))&&(in_array($f['id'],$faxes))){
          $c="checked=\"checked\"";
          $d="";
        }else{ 
          $c="";
          $d="";
        }
        $fax_name=$f["client"]["name"]." ".$f["client"]["surname"]." &lt;".$f["client"]["extension"]."&gt; (".$f["phonenumber"].")";
        $faxList.="<td style=\"padding:0;\"><input type=\"checkbox\" name=\"faxes[]\" value=\"".$f['id']."\" ".$c." ".$d."/><img src=\"$relBasePath/public/img/fax.gif\" alt=\"".$fax_name."\" /> ".$fax_name."</td>";
        if((++$count)%2==0) $faxList.="</tr><tr>\n";
      }
    }
    if(trim($faxList)=='') $faxList="<td colspan=\"2\">".T_("No fax extesions defined on the system")."</td>";
  }

  //================ MAIN CONTENTS ================
  ob_start();
  ?>
  <div class="SectionHeader">
  <?=$alert?>
    <h1><?=$title?></h1>
    <h3><a href="../" class="admin" ><?=T_("Return without save")?></a> </h3>
  </div>

  <div id="basic_form">
    <form action="<?=$PHP_SELF?><?if ($_GET["id"]!="") echo "?id=".$_GET["id"]; ?>" method="post">
      <!-- User info -->
      <div id="client_form" >
        <h3><?=T_("Users")?></h3>
        <p class="blockintro"><?=T_("Fill in the access data. If the user is connected to an extension, it isn't possible to change the access information.")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="user[username]"><?=T_("Username")?>:</label></dt>
              <dd><input type="text" size="25" maxlength="30" id="user[username]" name="user[username]" value="<?=$username?>" <?=$disabled?>/></dd>
          <? if ($_GET["id"]=="") { ?>
            <dt class="required"><label for="user[password]"><?=T_("Password")?>:</label></dt>
              <dd><input type="password" size="25" maxlength="30" id="user[password]" name="user[password]" value="<?=$password?>" /></dd>
            <dt class="required"><label for="user[language]"><?=T_("Language")?>:</label></dt>
                <dd><select id="user[language]" name="user[language]" ><?=$select?></select></dd>
          <? } else { ?>
            <dt class="required"><label for="user[password]"><?=T_("Password")?>:</label></dt>
              <dd><input type="password" size="25" maxlength="30" id="password" name="password" value="<?=$password?>" disabled="disabled" /></dd>
            <? if ($entity_id == 0) { ?>
              <dt class="required"><label for="user[changepwd]"></label></dt>
                <dd><input type="checkbox" id="user[changepwd]" name="user[changepwd]" onclick="if(this.checked){document.getElementById('user[newpassword]').disabled=''; document.getElementById('user[confirmpassword]').disabled=''; } else {document.getElementById('user[newpassword]').disabled='disabled'; document.getElementById('user[confirmpassword]').disabled='disabled'; document.getElementById('user[newpassword]').value=''; document.getElementById('user[confirmpassword]').value=''; }"/>
                    <?=T_("Change password")?>
                    <input type="hidden" id="user[password]" name="user[password]" value="<?=$password?>" /></dd>
              <dt class="required"><label for="user[newpassword]"><?=T_("New Password")?>:</label></dt>
                <dd><input type="password" size="25" maxlength="20" id="user[newpassword]" name="user[newpassword]" value="" disabled="disabled" /></dd>
              <dt class="required"><label for="user[confirmpassword]"><?=T_("Confirm")?>:</label></dt>
                <dd><input type="password" size="25" maxlength="20" id="user[confirmpassword]" name="user[confirmpassword]" value="" disabled="disabled" /></dd>
              <dt class="required"><label for="user[language]"><?=T_("Language")?>:</label></dt>
                <dd><select id="user[language]" name="user[language]" ><?=$select?></select></dd>
            <? } else { ?>
              <dt class="required"><label for="user[language]"><?=T_("Language")?>:</label></dt>
                <dd>
                	<select id="language" name="language" disabled="disabled" ><?=$select?></select>
                  <input type="hidden" id="user[language]" name="user[language]" value="<?=$lang?>" />
                </dd>
                <?=$hiddenFields?>
            <? } ?>
          <? } ?>
          </dl>
        </div>
    
        <!-- User type -->
        <h3><?=T_("Type")?></h3>
        <p class="blockintro"><?=T_("Choose the kind of user you want to create/modify")?></p>
          <dl>
            <dt class="required"><label for="user[type]"><?=T_("Type")?>:</label></dt>
            <dd>
              <img src="<?=$relBasePath?>/public/img/user_standard.gif" alt="Standard User" />
              <input type="radio" size="25" maxlength="30" id="user[type1]" name="user[type]" value="<?=USER_STANDARD?>" checked="checked" onclick="faxAccountSwitch('on')"/>
              <?=T_("Standard User")?>
              <img src="<?=$relBasePath?>/public/img/user_configurator.gif" alt="Configurator User" />
              <input type="radio" size="25" maxlength="30" id="user[type2]" name="user[type]" value="<?=USER_CONFIGURATOR?>" <?if ($type==USER_CONFIGURATOR) echo "checked=\"checked\"";?> onclick="faxAccountSwitch('off')"/>
              <?=T_("Configurator")?>
          <?  if ($cwUserInfo["type"]==USER_SUPERUSER ) { ?>
              <img src="<?=$relBasePath?>/public/img/user_superuser.gif" alt="Superuser" />
              <input type="radio" size="25" maxlength="30" id="user[type3]" name="user[type]" value="<?=USER_SUPERUSER?>" <?if ($type==USER_SUPERUSER) echo "checked=\"checked\"";?> onclick="faxAccountSwitch('off')"/>
              <?=T_("SuperUser")?>
          <?  } ?>
            </dd>
          </dl>
        
        <? if(_isModuleLoaded('fax')){ ?>
          <!-- Faxes -->
          <h3><?=T_("Faxes")?></h3>
          <p class="blockintro"><?=T_("Set service parameters and select which fax accounts user can read and send through")?></p>
          <div class="block">
            <dl>
              <dt class="required"><label for="fax_notify_address"><?=T_("Notify to")?>:</label></dt>
              <dd><input type="text" size="25" maxlength="100" id="fax_notify" name="fax_notify" value="<?=$fax_notify?>"/> <span class="help"><?=T_('Email address for notifications')?></span></dd>
              <dt class="required"><label for="fax_can_delete"><?=T_("Can delete")?>:</label></dt>
              <dd><input type="checkbox" id="fax_candel" name="fax_candel" value="1" <? if(($fax_can_delete==1)||($fax_can_delete=='1')) echo "checked=\"checked\""; ?>/> <span class="help"><?=T_('If checked, user can delete faxes')?></span></dd>
              <dt class="required"><label for="fax_candel"><?=T_("Accounts")?>:</label></dt>
              <dd>
                <table id="account_table" cellpadding="0" cellspacing="0" style="width:80%; <? if(($type==USER_CONFIGURATOR)||($type==USER_SUPERUSER)) echo 'display:none;' ?>">
                  <tr><?=$faxList?></tr>
                </table>
                <span id="account_span" style="<? if(($type!=USER_CONFIGURATOR)&&($type!=USER_SUPERUSER)) echo 'display:none;' ?>">
                  <?=T_('Configurator and Superuser are enabled to use all fax lines')?>
                </span>
              </dd>
            </dl>
          </div>
        <? } ?>
        
      </div>
    <div class="action">
      <?if ($_GET["id"]!="") {?> <input type="hidden" name="user[id]" value="<?=$id?>" /><?}?>
      <input type="hidden" name="user[entity_id]" value="<?=$entity_id?>" />
      <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>
  <script>
    function faxAccountSwitch(value){
      tableObj=document.getElementById('account_table');
      spanObj=document.getElementById('account_span');
      if((tableObj!=null)&&(spanObj!=null)){
        if(value=='on'){
          tableObj.style.display='inline';
          spanObj.style.display='none';
        }else{
          tableObj.style.display='none';
          spanObj.style.display='inline';
        }
      }
    }
  </script>
  <?
  $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 user or to modify an existing one. To create a new user you have to define the username, the password, the type of user and to press save button on the end of the page.")?></p>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();

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

