<?
/**
 * VoiceOne Settings/Tech/misdn
 *
 * Frontend to provide access to the tech system in voiceone.
 * @package voiceone
 * @subpackage  settings_tech
 */
  include ("../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
  $alert=getAlert();
  //================ POST & GET ================
  //delete Isdn card
  if(!_isModuleLoaded('mISDN')) goToMainPage('',"../");
  if($_GET["cmd"]=="del"){
    $ret=$asterisk->delIsdnCard($_GET["id"]);
    if ($ret==1) $alert="<div class=\"AlertGood\">".T_("The card has been removed")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("The card hasn't been removed")."</div>";
    //reload page
    goToMainPage($alert,"index.php");
  }
  //install a new card or update the port parameters
  if(count($_POST)>0){
    if($_POST["act"]=="install"){
      $card=$_POST["card"];
      $ret=$asterisk->putIsdnCard($card);
      if ($ret>0) $alert="<div class=\"AlertGood\">".T_("The card has been installed")."</div>";
      else $alert="<div class=\"AlertBad\">".T_("The card hasn't been installed")."</div>";
    }else{
      $entry=Array();
      if(is_array($_POST["port"])){
        foreach($_POST["port"] as $id=>$p){
        	$entry[]=array(
          		"id" => $id,
              "layermask" => $p["layermask"], 
              "protocol" => $p["protocol"],
              'port' => 0,
              'card' => 0,
              'card_id' => 0,
              'available' => 0 
          	); 
        }
      }
      $ret=$asterisk->updateIsdnPort($entry);
      if ($ret>0) $alert="<div class=\"AlertGood\">".T_("The port configuration has been correctly performed")."</div>";
      else $alert="<div class=\"AlertBad\">".T_("The saving hasn't been performed, due to errors")."</div>";
    }
    //reload page
    goToMainPage($alert,"index.php");
  }
  //================ PAGE LOGIC ================
	//retrieve cards
  $ret=$asterisk->getIsdnPort(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  $old_card_id=0;
  $countcards=0;
  if((is_array($ret))&&(count($ret)>0)){
    $portsArr=array();
    //get mISDN Port Groups
    $ret2=$asterisk->getIsdnGroup(0);
    if(is_array($ret2)){
      foreach($ret2 as $pg){
        if(is_array($pg["port"])){
          foreach($pg["port"] as $p_id){
            $port=$asterisk->getIsdnPort($p_id);
            if((is_array($port))&&(is_array($port[0]))){
              $portsArr[$port[0]["channel"]]="Port Group <strong>mISDN/g:".$pg["name"]."</strong>";
            }
          }
        }
      }
    }
    //get mISDN extension array
    $ret3=$asterisk->getClient(0,MISDN);
    if(is_array($ret3)){
      //get channel option id
      $portsOptionArr=$asterisk->getOptionByName("ports","mISDN");
      $portsOptionId=$portsOptionArr[0]["id"];
      if($portsOptionId!=0){
        foreach($ret3 as $ext){
          if(is_array($ext["options"])){
            foreach($ext["options"] as $o){
              if($o["key"]==$portsOptionId){
                $portsArr[$o["value"]]="<strong>".$ext["name"]." ".$ext["surname"]." &lt;".$ext["extension"]."&gt;</strong>";     
                break;
              }
            }
          }
        }
      }
    }
    //loop ports
    foreach($ret as $v){
      $id=$v["id"];
      $port=$v["port"];
      $name=$v["name"];
      $layermask=$v["layermask"];
      $protocol=$v["protocol"];
      $card=$v["card"];
      $card_id=$v["card_id"];
      $available=$v["available"];
      if($old_card_id!=$card_id) {
        if($v["channel"]>1) $html.="<tr><td>&nbsp;</td></tr>\n";
        $c=$asterisk->getIsdnCard($card);
        $name=$c[0]["name"];
        $countcards++;
        //set delete button
        $erasabled=$asterisk->isIsdnCardErasable($card_id);
        if($erasabled==1){
          $onclick_erasable="if(confirm('".T_('WARNING: this operation will turn off pbx service! Are you sure to remove the card?')."')){location.href='".$PHP_SELF."?cmd=del&id=".$card_id."';}";
        }else{
          $onclick_erasable="alert('".sprintf(T_("Card n.%s cannot be deleted because almost one port of this card or next cards is locked.\\nPlease free all these ports before deleting card."),$countcards)."'); return false;";
        }
        ob_start();
      	?>
        	<tr>
          	<td>
            	<span style='color: green; font-weight: bold;'><?=T_("Card")?> n&deg;<?=$countcards?>:</span> <?=$name?>  
              <a href="#" onclick="<?=$onclick_erasable?>" >
              	<img src="<?=$relBasePath?>/public/img/trash.gif" />
              </a>
            </td>
         	</tr>
        <?
        $html.=ob_get_contents();
  			ob_end_clean();
      }
      //check if port is available
      if($available==0){
        if((is_array($portsArr))&&(array_key_exists($v["channel"],$portsArr))){
          $lock_entity=$portsArr[$v["channel"]];
        }else{
          $lock_entity="";
        }
        $lock="<img src=\"".$relBasePath."public/img/lock.gif\" alt=\"locked\"/>&nbsp;<span style=\"color:red\">".$lock_entity."</span>";
        $locked="disabled=\"disabled\"";
      }else{
        $locked="";
        $lock="&nbsp;";
      }
      ob_start();
      ?>
      	<tr>
        	<td style='border-bottom: 1px dotted gray;'>
          	<strong><? if($v["channel"]<10){echo "0";} ?><?=$v["channel"]?></strong> -&gt; <?=T_("Port")?> n&deg;<?=$port?>
      			<span style='margin-left: 20px;'>
            	<input type="radio" name="port[<?=$id?>][layermask]" value="nt" <?=$locked?> <? if ($layermask=='nt') echo "checked=\"checked\""; ?>/> NT
							<input type="radio" name="port[<?=$id?>][layermask]" value="te" <?=$locked?> <? if ($layermask=='te') echo "checked=\"checked\""; ?>/> TE
              <? if(trim($locked)!=""){ ?>
                <input type="hidden" name="port[<?=$id?>][layermask]" value="<?=$layermask?>"/>
              <? } ?>       			 
      			</span>
      			<span style='margin-left: 30px;'> 
            	<input type="radio" name="port[<?=$id?>][protocol]" value="ptmp" <?=$locked?> <? if ($protocol=='ptmp') echo "checked=\"checked\""; ?>/> Ptmp
              <input type="radio" name="port[<?=$id?>][protocol]" value="ptp" <?=$locked?> <? if ($protocol=='ptp') echo "checked=\"checked\""; ?>/> Ptp
              <? if(trim($locked)!=""){ ?>
                <input type="hidden" name="port[<?=$id?>][protocol]" value="<?=$protocol?>"/>
              <? } ?>    
       			</span>
            <span style='margin-left: 30px;'><?=$lock?></span>
      		</td>
        </tr>
      <?
			$html.=ob_get_contents();
  		ob_end_clean();
      $old_card_id=$card_id;
    }
  }else{
  	$html="";
  }
  //all cards list
  $ret=$asterisk->getIsdnCard(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($ret)) {
    foreach($ret as $v) {
      $id=$v["id"];
      $name=$v["name"];
      $ports=$v["ports"];
      $cards.="<option value=\"".$id."\">".$name." (".$ports." ".T_("ports").")</option>\n";
    }
  }    
  //================ MAIN CONTENTS ================
  ob_start();
  ?>
    <? $sel="cards"; include ("navigation.php");?>
    <div class="SectionHeader">
      <?=$alert?>
      <div style="clear:both;"></div>
      <!-- NEW CARDS -->
      <div style="float:right;margin-top:3px;">
      	<form id="form_install" action="<?=$PHP_SELF?>" method="post">
        	<h2 style="display:inline;font-size:14px;color:darkgreen;padding-right:10px;"><?=T_("Add a card")?>:</h2>
        	<select name="card"><?=$cards?></select>
          <img src="<?=$relBasePath?>/public/img/add.gif" style="cursor:pointer;margin-left:5px;vertical-align:top;" alt="<?=T_('Add a card')?>" onclick="if(confirm('<?=T_('WARNING: this operation will turn off pbx service! Continue?')?>')){document.getElementById('tplpbxsytatus').src='<?=$relBasePath?>/public/img/tl-red-small.gif'; document.getElementById('form_install').submit();} else return false;" />
        	<input type="hidden" name="act" value="install" />
      	</form>
      </div>
      <!-- TITLE -->
      <h1><?=T_("ISDN Cards")?></h1>
    </div>
    <!-- INSTALLED CARDS -->
    <div id="basic_form">
      <form id="main_form" action="<?=$PHP_SELF?>" method="post">
        <h2><?=T_("mISDN Cards")?></h2>
        <div>
          <table class="todolist">
            <tr>
              <?=$html?>
            </tr>
          </table>
          <? if ($html!=""){ ?>
          	<input type="submit" value="<?=T_('Apply')?>" style="font-size: 11px; float: right; margin-right: 20px;" onclick="if(confirm('<?=T_('WARNING: this operation will turn off pbx service! Continue?')?>')){document.getElementById('tplpbxsytatus').src='<?=$relBasePath?>/public/img/tl-red-small.gif'; document.getElementById('main_form').submit();} else return false;"/>
          <? } ?>
          <input type="hidden" name="act" value="update" />
        </div>
      </form>
    </div>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="isdn";include("../sidebar.php");?>
      <h1><?=T_("Installed card")?></h1>
      <p>
      	<?=T_("Integrated Services Digital Network (ISDN) is a type of circuit switched telephone network system, designed to allow digital transmission of voice and data over ordinary telephone copper wires, resulting in better quality and higher speeds than available with analog systems. More broadly, ISDN is a set of protocols for establishing and breaking circuit switched connections, and for advanced call features for the user. The English term is a \"backronym\", thought better for English-language advertisements than the original, \"Integriertes Sprach- und Datennetz\" (German for \"integrated voice and data net\")")?></p> 
        <img src="../../../admin/public/img/quad1.jpg" width="200" alt="isdn card" />
      </p>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "isdn");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

