<?
/**
 * VoiceOne Settings/Contacts List
 *
 * Frontend to provide access to the contacts list system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 */

  include ("../../admin/config/cfg.php");
  global $cwlang,$cwUserId,$cwUserInfo;
  DEFINE("CONTACTS_PER_PAGE", 30);

  //================ POST & GET =================
  $alert=getAlert();
	//delete contact
  if((isset($_GET["del"]))&&($_GET["del"]!="")){
    $ret=$asterisk->delContact($_GET["del"],$cwUserId);
    //set return
    if ($ret==1) $alert="<div class=\"AlertGood\">".T_("Contact successfully deleted")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Delete failed")."</div>";
    goToMainPage($alert,"./");
  }
  //================ AJAX =================
  if(count($_GET)>0){
    //get contact list
    if((isset($_GET["char"]))&&($_GET["char"]!="")){
    	$_SESSION['reload_char']=$_GET["char"];
      $ret=$asterisk->getContactList($cwUserId,$_GET["char"],$_GET["filter"],CONTACTS_PER_PAGE,$_GET['page']);
      if($_GET['page']!=1){
    		while((!is_array($ret))&&(--$_GET['page']!=1)){
      		$ret=$asterisk->getContactList($cwUserId,$_GET["char"],$_GET["filter"],CONTACTS_PER_PAGE,$_GET['page']);
      	}
      }
      $html.="<div>\n";
      if(!is_array($ret)){
      	$html.="<p style=\"text-align:center;\">".sprintf(T_("There are no contacts starting with letter %s"),strtoupper($_GET["char"]) )."</p>";
      }else{
      	//contacts
        $count=0;
        $html.="<table width=\"100%\">";
      	$html.="  <tr>";
        foreach($ret as $v){
          $id=$v["id"];
          $id_user=$v["id_user"];
          $name=$v["name"];
          $write=$v["write"];
          //trash
          if(($id_user==$cwUserId)||($cwUserInfo["type"]!=USER_STANDARD)||($write==1)) $trash="<a href=\"$PHP_SELF?del=$id\" onclick=\"if (confirm('".sprintf(T_("Are you sure you want to remove the contact: %s ?"),$name )."')) return true; else return false;\"><img src=\"$relBasePath/public/img/trash.gif\" /></a>";
          else $trash="<img src=\"$relBasePath/public/img/lock.gif\" alt=\"".T_("Contact are read only")."\"/>";
          //dial
          if((is_array($cwUserInfo))&&(trim($cwUserInfo["exten"])!="")){
            $dial="<a href=\"dial/?contact=".$id."&TB_iframe=true&height=250&width=350\" class=\"thickbox\" title=\"Contact File\">".$name."</a>";
          }else{
            $dial=$name;
          }
          //modify
          $modify="<a href=\"edit/?id=".$id."\"><img src=\"".$relBasePath."public/img/edit.gif\"/></a>";
          //numbers
          $numb='';
          if(trim($v['phonenumber'])!='') $numb.="Phone: ".$v['phonenumber'];
          if(trim($v['mobile'])!=''){
            if(trim($numb)!='') $numb.="<br/>";
            $numb.="Mob: ".$v['mobile'];
          }
          if(trim($v['fax'])!=''){
            if(trim($numb)!='') $numb.="<br/>";
            $numb.="Fax: ".$v['fax'];
          }
          $numb="<div style=\"padding-left:19px; color:gray;\">".$numb."</div>";
          //html
          $html.="<td class=\"unknown\" style=\"font-size: xx-small;\"><img src=\"".$relBasePath."public/img/unknown.gif\" alt=\"$alt\"/> $dial $modify $trash $numb</td>";
          if((++$count)%2==0) $html.="</tr><tr>\n";
        }
        if(($count!=0)&&(($count%2)!=0)) $html.="<td colspan=\"".($count%2)."\">&nbsp;</td>\n";
        $html.="  </tr>";
        $html.="</table>";
        //page buttons
        $page=$_GET["page"];
        $tot=$_GET["result"];
        $numbers="";
        if($tot>CONTACTS_PER_PAGE){
        	$rounds=intval($tot/CONTACTS_PER_PAGE);
          if($tot%CONTACTS_PER_PAGE!=0) $rounds++;
        }else $rounds=1;
        $startPage=max(1,($page-5));
        for($i=$startPage;$i<=$rounds;$i++){
        	if(($startPage!=1)&&($numbers=="")) $numbers="<span style=\"font-size:11px;color:#333;background:#fff\">...</span> | ";
					else{
        		if($i==$page) $numbers.="<span style=\"font-size:13px;font-weight:bold;\">".$i."</span> | ";
          	else $numbers.="<span><a style=\"font-size:11px;color:#333;background:#fff\" href=\"./?page=".$i."&reload_char=".$_GET["char"]."\">".$i."</a></span> | ";
          }
          if($i>=$startPage+10-1){
          	$numbers.="<span style=\"font-size:11px;color:#333;background:#fff\">...</span> | ";
            break;
          }
        }
        if(strlen($numbers)>3) $numbers=substr($numbers,0,-3);
        $html.="<div style=\"margin-top:20px;width:100%;text-align:center;\">";
        if($page>1) $html.="<a href=\"./?page=1&reload_char=".$_GET["char"]."\">&lt;&lt;</a>&nbsp;&nbsp;"; else $html.="&lt;&lt;&nbsp;&nbsp;";
        if($page>1) $html.="<a href=\"./?page=".intval($page-1)."&reload_char=".$_GET["char"]."\">&lt;</a>&nbsp;&nbsp;&nbsp;"; else $html.="&lt;&nbsp;&nbsp;&nbsp;";
        $html.=$numbers;
        if($page<$rounds) $html.="&nbsp;&nbsp;&nbsp;<a href=\"./?page=".intval($page+1)."&reload_char=".$_GET["char"]."\">&gt</a>"; else $html.="&nbsp;&nbsp;&nbsp;&gt;";
        if($page<$rounds) $html.="&nbsp;&nbsp;<a href=\"./?page=".$rounds."&reload_char=".$_GET["char"]."\">&gt;&gt;</a>"; else $html.="&nbsp;&nbsp;&gt;&gt;";
        $html.="</div>";
      }
      $html.="</div>\n";
      die($html);
    }
  }
  //================ PAGE LOGIC =================
  //set filter
  $reload=false;
  if(isset($_GET['search'])){
  	$_SESSION["filter"]=$_GET['search'];
    $_SESSION["page"]=1;
    $reload=true;
  }else if(!isset($_SESSION["filter"])||($_SESSION["filter"]=="")){
  	$_SESSION["filter"]="";
  }
  if((isset($_GET['reload_char']))&&($_GET['reload_char']!="")){
  	$_SESSION['reload_char']=$_GET['reload_char'];
    $reload=true;
  }else if(!isset($_SESSION["reload_char"])||($_SESSION["reload_char"]=="")){
  	$_SESSION['reload_char']="a";
 	}
  if((isset($_GET['page']))&&($_GET['page']!="")){
  	$_SESSION["page"]=$_GET['page'];
    $reload=true;
  }else if(!isset($_SESSION["page"])||($_SESSION["page"]=="")){
  	$_SESSION["page"]=1;
  }
  if($reload===true) goToMainPage("","./index.php");
  $filter=trim($_SESSION["filter"]);
  $reload_char=trim($_SESSION['reload_char']);
  $page=$_SESSION["page"];
  //build html for external contacts (extensions)
  $ret=$asterisk->getContactIndex($cwUserId,$filter);
  if(is_array($ret)){
    foreach($ret as $v) $tabArr[$v["key"]]=$v["value"];
  }
  $alphabet=array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
  foreach($alphabet as $key){
  	if((isset($tabArr[$key]))&&($tabArr[$key]>0)){
    	$class="act";
      $c_num=$tabArr[$key];
    }else{
    	$class="dis";
      $c_num=0;
    }
    if($key==$reload_char) $link_to_page=$page; else $link_to_page=1;
    $html.="<li>";
    $html.="<a href=\"index.php?char=".$key."&result=".$c_num."&page=".$link_to_page."&filter=".$filter."\" title=\"".strtoupper($key)."\" style=\"background-image: url(".$relBasePath."public/img/tab.png);\" onclick=\"document.getElementById('reload_char').value='".$key."';\">";
    $html.="<span class=\"$class\" style=\"background-image: url(".$relBasePath."public/img/tab.png);\">".strtoupper($key)."</span>";
    $html.="</a>";
    $html.="</li>\n";
  }
  if($reload_char!="") $starting_tab=intval(array_search($reload_char,$alphabet))+1;
  else $starting_tab=0;
  //================ MAIN CONTENTS ================
  ob_start();
  ?>
  <div class="SectionHeader">
    <?=$alert?>
    <div id="loading" style="float: right;">
      <img src="<?=$relBasePath?>public/img/ico-progress.gif" alt="loading" /><span><?=T_("loading")?></span>
    </div>
    <h1><?=T_("Contact List")?></h1>
    <div style="float:right;margin-top:5px;">
    	<form action="index.php" method="get">
      	<input type="text" name="search" value="<?=$filter?>" />
        <input type="hidden" id="reload_char" name="reload_char" value="<?=$reload_char?>" />
      	<input type="image" style="vertical-align:middle;cursor:pointer;" src="<?=$relBasePath?>/public/img/search.gif" alt="Search"/>
      </form>
    </div>
    <h3>
      <a href="edit/" class="admin" ><?=T_("New Contact")?></a>
      <a style="margin-left:10px;" href="import/" class="admin" ><?=T_("Import Contacts")?></a>
      <a style="margin-left:10px;" href="export/" class="admin" ><?=T_("Export Contacts")?></a>
    </h3>
    
  </div>
  <div style="clear:both;"></div>
  <div id="container-1" style="display:none; margin-top:10px; border: 1px solid #97A5B0;">
  	<ul>
    	<?=$html?>
    </ul>
  </div>
  <script type="text/javascript">
    $(window).bind("load", function(){
        $('#container-1 ul').tabs(<?=$starting_tab?>,{
          	fxFade: true,
            fxSpeed: 'fast'
        	});
        $('#container-1').css({display: "block"});
        $('#loading').css({display: "none"});
     });
  </script>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start();
  ?>
    <div class="Sidebar">
      <?$sel="list";include("../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
      <p><?=T_("This page allows you to manage contacts configured on the system. It's possible to search a contact and surf the results using tabs. To create, import or export contacts follow the links under the section title, otherwise click on the pencil on the left of an existing contact to edit it or on the basket on the right of the name to delete it. If you have a registerd extension you can star a call from your phone clicking on the contact and then on the number you want to dial.")?></p>  
      <div style="text-align: center"><img src="<?=$relBasePath?>public/img/book.jpg" align="center"/></div>
    </div>
  <?
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "contacts");
  $smarty->assign("subsection", "");
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("contents", $contents);
  $smarty->display('main.tpl');
?>
