<?
  /**
  * VoiceOne Settings/Tech/zapata
  *
  * 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();
  //================ PAGE LOGIC ================
  if(!_isModuleLoaded('zap')) goToMainPage('',"../");
  //delete Zapata card
  if($_GET["cmd"]=="del") {
    $ret=$asterisk->delZapataCard($_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->putZapataCard($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();
      $card=$_POST["card"];
      foreach($_POST["type"] as $id=>$l) {
        if($_POST["crc4"][$id]   != 1) $crc4=0;   else $crc4=1;
        if($_POST["yellow"][$id] != 1) $yellow=0; else $yellow=1;
        $entry[]=Array(
            "id"     =>$id, 
             "type"   =>$_POST["type"][$id],
             "device" =>$_POST["device"][$id],
             "timing" =>$_POST["timing"][$id],
             "lbo"    =>$_POST["lbo"][$id],
             "framing"=>$_POST["framing"][$id],
             "coding" =>$_POST["coding"][$id],
             "crc4"   =>$crc4,
             "yellow" =>$yellow
           );
      }
      //set Tone Zone
      if($_POST["loadzone"]){
        foreach($_POST["loadzone"] as $id=>$l){
          $zones[]=Array("id"=>$id, "loadzone"=>$l, "defaultzone"=>"");
        }
      }
      $zones[]=Array("id"=>$id, "loadzone"=>"", "defaultzone"=>$_POST["defzone"]);
			//update ports
      $ret=$asterisk->updateZapataPort($entry,$zones);
      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->getZapataPort(0);
  if ($err=$asterisk->getError()) die("Error: $err");
  $old_card_id=0;
  $count=1;
  if((is_array($ret))&&(count($ret)>0)){
    //get channels array
    $channelArr=array();
    $ret2=$asterisk->getZapataChannel(0);
    if(is_array($ret2)){
      foreach($ret2 as $c){
        $channelArr[$c["port_id"]]=$c;
      }
    }
    //get Zap extension array
    $extensionArr=array();
    $ret3=$asterisk->getClient(0,ZAP);
    if(is_array($ret3)){
      //get channel option id
      $channelOptionArr=$asterisk->getOptionByName("channel","ZAP");
      $channelOptionId=$channelOptionArr[0]["id"];
      if($channelOptionArr!=0){
        foreach($ret3 as $ext){
          if(is_array($ext["options"])){
            foreach($ext["options"] as $o){
              if($o["key"]==$channelOptionId){
                $extensionArr[$o["value"]]=$ext["name"]." ".$ext["surname"]." &lt;".$ext["extension"]."&gt;";     
                break;
              }
            }
          }
        }
      }
    }
    //loop ports
    $countcards=0;
    foreach($ret as $v){
      $id=$v["id"];
      $port=$v["port"];
      $type=$v["type"];
      $device=$v["device"];
      $span=$v["span"];
      $timing=$v["timing"];
      $lbo=$v["lbo"];
      $framing=$v["framing"];
      $coding=$v["coding"];
      $crc4=$v["crc4"];
      $yellow=$v["yellow"];
      $order=$v["order"];
      $card=$v["card"];
      $card_id=$v["card_id"];
      //get zchannel,group and available from channel
      if((is_array($channelArr))&&(array_key_exists($id,$channelArr))){
        $group=$channelArr[$id]["group"];
        $available=$channelArr[$id]["available"];
        if($channelArr[$id]["zchannel"]<10) $zchannel="0".$channelArr[$id]["zchannel"];
        else $zchannel=$channelArr[$id]["zchannel"];
        
      }else{
        $available=-1;
        $zchannel="00";
      }
      //New Card
      if($old_card_id!=$card_id){
        $c=$asterisk->getZapataCard($card);
        if((is_array($c))&&(is_array($c[0]))){
          $name=$c[0]["name"];
          $description=$c[0]["description"];
          $show=explode(',',$c[0]["type"]);
        }else{
          $name="unknown";
        }
        $countcards++;
        //set delete button
        $erasabled=$asterisk->isZapataCardErasable($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?")."')){document.getElementById('tplpbxsytatus').src='".$relBasePath."/public/img/tl-red-small.gif'; return true;} else return false;";
        }else{
          $onclick_erasable="alert('".sprintf(T_("Card n.%s cannot be deleted because almost one channel of this card or next cards is locked.\\nPlease free all these channels before deleting card."),$countcards)."'); return false;";
        }
        ob_start();
      	?>
          <? if($count>1){ ?>
                </table>
              </tr>
            <tr><td colspan="9">&nbsp;</td></tr>
          <? } ?>
          <tr>
            <table class="todolist" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <td colspan="9">
                  <span style='color: green; font-weight: bold;'><?=T_("Card")?> No. <?=$countcards?>:</span> 
                  <?=$name?>
                  <a href="<?$PHP_SELF?>?cmd=del&id=<?=$card_id?>" onclick="<?=$onclick_erasable?>">
                    <img src="<?=$relBasePath?>public/img/trash.gif" alt="delete"/>
                  </a>
                </td>
              </tr>
              <!-- Print header-->
              <tr>
                <td width=100>&nbsp;</td>
                <td width=51 style="text-align:center">Type</td>
                <td width=51 style="text-align:center">Protocol</td>
                <? if($show[0]=="E1" or $show[0]=="T1"){ ?>
                  <td style="text-align:center">Timing</td>
                  <td style="text-align:center">LBO</td>
                  <td style="text-align:center">Framing</td>
                  <td style="text-align:center">Coding</td>
                  <td style="text-align:center">CRC4</td>
                  <td style="text-align:center">Yellow</td>
                <? }else{ ?>
                  <td colspan="6">&nbsp;</td>
                <? } ?>
            </tr>
        <?
        $html.=ob_get_contents();
  			ob_end_clean();
      }
      //port type selection
      $option_type="";
      //$option_type.="<option value=\"\">[unused]</option>";
      if(is_array($show)){
        foreach($show as $c){
          if($c==$type) $chk_opt="selected=\"selected\""; else $chk_opt="";
          $option_type.="<option $chk_opt>".$c."</option>";
        }
      }
      // options to choose from pulldown
      $choose_device   = "";
      $choose_timing   = "";
      $choose_lbo      = "";
      $choose_framing  = "";
      $choose_coding   = "";
      $option=$asterisk->getZapataPortOption("$type");
      if((is_array($option))&&(is_array($option[0]))){
        //extract options
        $choose_device   = explode(',',$option[0]["device"]);
        $choose_timing   = explode(',',$option[0]["timing"]);
        $choose_lbo      = explode(',',$option[0]["lbo"]);
        $choose_framing  = explode(',',$option[0]["framing"]);
        $choose_coding   = explode(',',$option[0]["coding"]);
        //set menus
        $option_device="<option>[unused]</option>";
        foreach($choose_device as $c) {
          if ($c==$device) $chk_opt="selected=\"selected\""; else $chk_opt="";
            $option_device.="<option $chk_opt>".$c."</option>";
        }
        $option_timing="";
        foreach($choose_timing as $c) {
          if ($c==$timing) $chk_opt="selected=\"selected\""; else $chk_opt="";
            $option_timing.="<option $chk_opt>".$c."</option>";
        }
        
        $option_lbo="";
        foreach ($choose_lbo as $c) {
          if($c==$lbo) $chk_opt="selected=\"selected\""; else $chk_opt="";
            $option_lbo.="<option $chk_opt>".$c."</option>";
        }
        
        $option_framing="";
        foreach ($choose_framing as $c) {
          if($c==$framing) $chk_opt="selected=\"selected\""; else $chk_opt="";
            $option_framing.="<option $chk_opt>".$c."</option>";
        }
        
        $option_coding="";
        foreach ($choose_coding as $c) {
          if($c==$coding) $chk_opt="selected=\"selected\""; else $chk_opt="";
            $option_coding.="<option $chk_opt>".$c."</option>";
        }
      }
      if($crc4) $status_crc4="checked=\"checked\""; else $status_crc4="";
      if($yellow) $status_yellow="checked=\"checked\""; else $status_yellow="";
      //check if port is available
      if($available==0){
        if($group!="") $lock_entity="Port Group <strong>Zap/g:".$group."</strong>";
        else if((is_array($extensionArr))&&(array_key_exists(intval($zchannel),$extensionArr))){
          $lock_entity="<strong>".$extensionArr[intval($zchannel)]."</strong>";
        }
        $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;";
      }
      //print html
      $border="valign=\"top\" style=\"border-bottom: 1px dotted gray;\"";
      ob_start();
      ?>
        <tr>
          <td width="100" align="left" <?=$border?> >
            <strong><?=$zchannel?></strong>&nbsp;-&gt;&nbsp;<?=T_("Port")?> n&deg;<?=$port?>
          </td>
          <td align="left" <?=$border?> >
            <select name="type[<?=$id?>]" <?=$locked?> ><?=$option_type?></select><?=$input?>
            <? if(trim($locked)!=""){ ?>
              <input type="hidden" name="type[<?=$id?>]" value="<?=$type?>"/>
            <? } ?>
          </td>
          <!-- Figure out form display parameter -->   
          <? if($type == "E1" || $type == "T1"){ ?> 
            <td align="left" <?=$border?> ><select name="device[<?=$id?>]"><?=$option_device?></select></td>
            <td align="left" <?=$border?> ><select name="timing[<?=$id?>]"><?=$option_timing?></select></td>
            <td align="left" <?=$border?> ><select name="lbo[<?=$id?>]"><?=$option_lbo?></select></td>
            <td align="left" <?=$border?> ><select name="framing[<?=$id?>]"><?=$option_framing?></select></td>
            <td align="left" <?=$border?> ><select name="coding[<?=$id?>]"><?=$option_coding?></select></td>
            <td align="left" <?=$border?> ><input type="checkbox" name="crc4[<?=$id?>]" value="1" <?=$status_crc4?> /></td>
            <td align="left" <?=$border?> ><input type="checkbox" name="yellow[<?=$id?>]" value="1" <?=$status_yellow?> /></td>     
          <? }else if($type=='FXS' or $type=='FXO'){ ?>  
            <td colspan="3" align="left" <?=$border?> >
              <select name="device[<?=$id?>]" <?=$locked?> ><?=$option_device?></select>
              <? if(trim($locked)!=""){ ?>
                <input type="hidden" name="device[<?=$id?>]" value="<?=$device?>"/>
              <? } ?>
              <input type="hidden" name="timing[<?=$id?>]"/>
              <input type="hidden" name="lbo[<?=$id?>]"/>
              <input type="hidden" name="framing[<?=$id?>]"/>
              <input type="hidden" name="coding[<?=$id?>]"/>
              <input type="hidden" name="crc4[<?=$id?>]"/>
              <input type="hidden" name="yellow[<?=$id?>]"/>
            </td>
            <td colspan="2" <?=$border?> >&nbsp;</td>
            <td colspan="2" <?=$border?> ><?=$lock?></td>
          <? }else{ ?>
            <td colspan="7" align="left" <?=$border?> >
              <input type="hidden" name="device[<?=$id?>]">
              <input type="hidden" name="timing[<?=$id?>]">
              <input type="hidden" name="lbo[<?=$id?>]">
              <input type="hidden" name="framing[<?=$id?>]">
              <input type="hidden" name="coding[<?=$id?>]">
              <input type="hidden" name="crc4[<?=$id?>]">
              <input type="hidden" name="yellow[<?=$id?>]">
            </td>
          <? } ?>
        </tr>
      <?
      $html.=ob_get_contents();
			ob_end_clean();
      $old_card_id=$card_id;
      $count++;
    }
    $html.="</table></tr>";
  }  
  //all card list
  $ret=$asterisk->getZapataCard(0);
  if($err=$asterisk->getError()) die("Error: $err");
  if(is_array($ret)){
    foreach($ret as $v){
      $id=$v["id"];
      $name=$v["name"];
      $description=$v["description"];
      $cards.="<option value=\"".$id."\">".$name." (".$description.")</option>\n";
    }
  }
  //tonezones
  $ret=$asterisk->getZapataToneZone(0);  
  if(is_array($ret)){
    $count="0";
    foreach($ret as $v){
      $id=$v["id"];
      $name=$v["name"];
      $fullname=$v["fullname"];
      $loadzone=$v["loadzone"];
      $defaultzone=$v["defaultzone"];
      if($loadzone!="0"){ $select="checked"; $loadzoneall.=$name.",";} else{ $select="";}
      if($defaultzone!="0"){ $select2="selected";} else{ $select2="";}
      if($count%4==0)$zone.="<tr>";
      $zone.="<td><input name=loadzone[$count] type=checkbox value='$name' $select>$name : $fullname";
      $defzone.="<option value='$name' $select2>$name : $fullname</option>\n";
      $count++; 
    }
  }
  //================ MAIN CONTENTS ================
  ob_start();
  ?>
    <? $sel="cards"; include ("navigation.php");?>
    <div class="SectionHeader">
      <?=$alert?>
      <!-- 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_("Zapata Cards")?></h1>
    </div>
    <div id="basic_form">
      <form id="main_form" action="<?=$PHP_SELF?>" method="post">
        <!-- INSTALLED CARDS -->
        <h2><?=T_("Zapata 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>
        <!-- TONEZONES -->
        <h2 style="margin-top:20px;"><?=T_("Tonezones")?></h2>
        <!--p class="blockintro"><?=T_("Set zaptel tonezones")?></p-->
        <div class="block">
          <dl>
            <dt class="required"><label for="defzone">Default Zone:</label></dt>
            <dd><select id="defzone" name="defzone"><?=$defzone?></select></dd>
            <dt class="required"><label for="defzone"><a href="#" onclick="return showHide('table_zone');">LoadZone</a>:</label></dt>
            <dd><span style="line-height:20px;"><?=substr($loadzoneall,0,-1)?></span></dd>
          </dl>
          <table class="todolist" id="table_zone" bgcolor="#f6f6f6" border=0 cellpadding=0 cellspacing=0 style="display:none">
            <?=$zone?>
          </table>
        </div>
      </form>
    </div>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="zapata";include("../sidebar.php");?>
      <h1><?=T_("Installed Zapata card")?></h1>
      <p><?=T_("<b>Span Card Configuration:</b><br>\n".
          "<br>\n" .
          "<b>Warning:</b> Before doing any<br>\n" .
          "span configuration, check the <br>\n" .
          "E1/T1 jumpers on the cards !<br>\n" .
          "<br>\n" .
          "<b>Type:</b><br>\n" .
          "Set E1/T1 according to jumpers<br>\n" .
          "<b>Protocol:</b><br>\n" .
          "Set PRI for pri lines<br>\n" .
          "Set E&M for e&m lines<br>\n" .
          "Set FX? for channel banks<br>\n" .
          "Empty = unconfigured<br>\n" .
          "<b>Timing:</b><br>\n" .
          "'0' master, internal clocking<br>\n" .
          "'1' slave, primary sync source<br>\n" .
          "'2' slave, secondary sync source<br>\n" .
          "'3' slave, tertiary sync source<br>\n" .
          "<b>LBO:</b>&nbsp;Line Build Out<br>\n" .
          "0:0db (CSU), 0-133 feet (DSX-1)<br>\n" .
          "1:133-226 feet (DSX-1)<br>\n" .
          "2:266-399 feet (DSX-1)<br>\n" .
          "3:399-533 feet (DSX-1)<br>\n" .
          "4:533-655 feet (DSX-1)<br>\n" .
          "5:-7.5db (CSU)<br>\n" .
          "6:-15db (CSU)<br>\n" .
          "7:-22.5db (CSU)<br>\n" .
          "<b>Framing, Coding, CRC4, Yellow:</b><br>\n" .
          "Match partner system setup<br>\n" .
          "<br>\n" .
          "<b>FXO,FXS Card Configuration:</b><br>\n".
          "<b>Type:</b><br>\n" .
          "Set FXO,FXS according to Modules<br>\n" .
          "Empty = no module installed<br>\n" .
          "<b>Protocol:</b><br>\n" .
          "fxsks: Kewlstart<br>\n" .
          "fxsls: Loopstart<br>\n" .
          "fxsgs: Groundstart<br>\n" .
          "fxoks: Kewlstart<br>\n" .
          "fxols: Loopstart<br>\n" .
          "fxogs: Groundstart<br>\n" .
          "Empty: Not configured<br>\n" .
          "</p>")?></p>
      <p> 
        <img src="../../../admin/public/img/quad1.jpg" width="200" alt="zapata card" />
      </p>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "zapata");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

