<?
/*********************** INCLUDES *********************************************/
  $includePath=realpath(dirname(__FILE__)."/../");
  require_once($includePath.'/config/cfg.php');
  require_once ($includePath.'/lib/phpagi/phpagi.php');
/*********************** INITIALIZATION ***************************************/
  $agi = new AGI();
  // Get AGI parameters
  // check if $_GET array is available. If not use $_SERVER
  if((is_array($_GET))&&(count($_GET)>0)){
     $rootNode=$_GET["id"];
  }else{
    // (GET array may be null in many cases, parseArgv take $_SERVER content)
    parse_str($_SERVER["argv"][1], $var_GET);
    $rootNode=$var_GET["id"];
  }
  //play IVR
  agiError("[ PLAY IVR $rootNode ]");
  _processNode($rootNode);
  agiError("Exit from playivr.php");
  
/*********************** RECOURSIVE LOGIC *************************************/
function _processNode($id){ 
  global $agi;
  $node=_getIvrNode($id);
  if(is_array($node)){
    $name=$node["name"];
    $type=$node["type"];
    $timesegment=$node["timesegment"];
    $maudio=$node["maudio"];
    $waudio=$node["waudio"];
    $beep=$node["beep"];
    $macro=$node["macro"];
    $parameter=$node["parameter"];
    $link=$node["link"];
    $taudio=$node["taudio"];
    $trepeat=$node["trepeat"];
    $ttimes=$node["ttimes"];
    $iaudio=$node["iaudio"];
    $irepeat=$node["irepeat"];
    $itimes=$node["itimes"];
    $children=$node["children"];
    $tmacro=$node["tmacro"];
    $tparameter=$node["tparameter"];
    $imacro=$node["imacro"];
    $iparameter=$node["iparameter"];
    if($ttimes=="") $ttimes=0;
    if($itimes=="") $itimes=0;
    //Process node
    switch($type) {
      case IVR_LEAF: //node is a leaf --> execute macro
        agiError("  - ACTION $name");
        //play welcome audio file
        if(($waudio!=0)&&($waudio!="")){
          $filepath=_getAudioFilePath($waudio);
          $filepath=substr($filepath,0,-4);
          if($filepath!=""){
            agiError("    --> Play welcome ($filepath)");
            $agi->get_data($filepath,1,10);
          }else agiError("    --> ERROR: unknown welcome audio message");
        }else agiError("    --> Mute welcome");
        //exec macro
        if(($macro!=0)&&($macro!="")){
          $arrMacro=prepareMacro($macro,$parameter);  
          agiError("    --> Executing macro ".$arrMacro[0].$arrMacro[1]." ...");
          $agi->exec("macro ".$arrMacro[0].$arrMacro[1], '');
        }else agiError("    --> ERROR: macro is null");
      break;
      case IVR_LINK: //node is a link --> jump to target
        agiError("  - LINK $name");
        //play welcome audio file
        if(($waudio!=0)&&($waudio!="")){
          $filepath=_getAudioFilePath($waudio);
          $filepath=substr($filepath,0,-4);
          if($filepath!=""){
            agiError("    --> Play welcome ($filepath)");
            $agi->get_data($filepath,1,10);
          }else agiError("    --> ERROR: unknown welcome audio message");
        }else agiError("    --> Mute welcome");
        //jump to the linked node
        if(($link!=0)&&($link!="")){
          $target=_getIvrNode($link);
          if(is_array($target)){
            agiError("    --> Jump to node ".$target["name"]);
            _processNode($link);
          }else agiError("    --> ERROR: unknown link target (node $link)");
        }else agiError("    --> ERROR: link is null");
      break;
      case IVR_NODE: //node has children --> play menu
        $repeat=true;
        $timeoutTimes=0; 
        $invalidTimes=0;
        while($repeat===true){ 
          agiError("  - MENU $name (t:$timeoutTimes/$ttimes | i:$invalidTimes/$itimes)");
          $exten="";
          //extract menu
          $menu=array();
          $keyArr=array();
          if(is_array($children)){
            //extract menu
            foreach($children as $childNode){
              $childKey=$childNode["key"];
              $childType=$childNode["type"];
              $childAudio=$childNode["maudio"];
              $childTimesegment=$childNode["timesegment"];
              $childLink=$childNode["link"];
              //check timesegment
              if(($childTimesegment!="")||($childTimesegment!=0)){
                if(checkTime($childTimesegment)===false){
                  agiError("    --> [$childKey] Skipped choice (checkTime return false)");
                  continue;
                }
              }
              //if child is a link, check target timesegment
              if($childType==IVR_LINK){
                if(($childLink!=0)&&($childLink!="")){
                  $target=_getIvrNode($childLink);
                  if(is_array($target)){
                    $targetTimesegment=$target["timesegment"];
                    if(($targetTimesegment!="")||($targetTimesegment!=0)){
                      if(checkTime($targetTimesegment)===false){
                        agiError("    --> [$childKey] Skipped choice (target checkTime return false)");
                        continue;
                      }
                    }
                  }else{ 
                    agiError("    --> [$childKey] Skipped choice (unknown link target)");
                    continue;
                  }
                }else{
                  agiError("    --> [$childKey] Skipped choice (link is null)");
                  continue;
                }
              }
              //audio file is not null
              if(($childAudio!=0)&&($childAudio!="")){
                $filepath=_getAudioFilePath($childAudio);
                $filepath=substr($filepath,0,-4);
                if($filepath!="") $menu[$childKey]=$filepath;
                else agiError("    --> ERROR: unknown choices audio message");
              //audio file is null
              }else $menu[$childKey]="";
              //save key in array
              $keyArr[]=$childKey;
            }
          }
          //play welcome audio file
          if(($waudio!=0)&&($waudio!="")){
            $filepath=_getAudioFilePath($waudio);
            $filepath=substr($filepath,0,-4);
            if($filepath!=""){
              agiError("    --> Play welcome ($filepath)");
              //play audio message and exstract digit (1 char)
              $retArr=$agi->get_data($filepath,1,10);
              $ret=trim($retArr["result"]);
              //wait for other digit (1 char per cicle)
              while($ret!=""){
                $exten.=$ret;
                $retArr=$agi->wait_for_digit(2000);
                $ret=trim(chr($retArr["result"]));
              }
            }else agiError("    --> ERROR: unknown welcome audio message");
          }else agiError("    --> Mute welcome");  
          //play menu
          if(($exten=="")&&(is_array($menu))){
            foreach($menu as $k=>$m){
              if($m=="") agiError("    --> [$k] Mute choice");
              else{
                agiError("    --> [$k] Play choice ($m)");
                //play audio message and exstract digit (1 char)
                $retArr=$agi->get_data($m,1,10);
                $ret=trim($retArr["result"]);
                //wait for other digit (1 char per cicle)
                while($ret!=""){
                  $exten.=$ret;
                  $retArr=$agi->wait_for_digit(2000);
                  $ret=trim(chr($retArr["result"]));
                }
              }
              if($exten!="") break;
            }
          }
          //Wait for choice
          if($exten==""){
            if(($beep!=0)&&($beep!="")){
              agiError("    --> Play beep and wait for choice");    
              $retArr=$agi->get_data("beep",0,10);
              $exten=$retArr["result"];
            }else{
              agiError("    --> Mute beep and wait for choice");    
              $retArr=$agi->get_data("silence/1",0,10);
              $exten=$retArr["result"];
            }
          }
          // END WITH TIMEOUT 
          if($exten==""){  
            agiError("  - CHOICE: null (TIMEOUT)");
            //play audio message
            if(($taudio!=0)&&($taudio!="")){
              $filepath=_getAudioFilePath($taudio);
              $filepath=substr($filepath,0,-4);
              if($filepath!=""){
                agiError("    --> Play timeout ($filepath)");
                $agi->get_data($filepath,1,10);
              }else agiError("    --> ERROR: unknown timeout audio message");
            }else agiError("    --> Mute timeout");
            //set repeat
            if($trepeat==1){
              $timeoutTimes++; 
              if(($ttimes!=0)&&($timeoutTimes>$ttimes)){ 
                agiError("    --> No Reload (Node has been repeat on Timeout ".($timeoutTimes-1)."/$ttimes times)");
                $repeat=false;
              }else{
                agiError("    --> Reload node (Repeat on Timeout is ON [".($timeoutTimes)."/$ttimes])");
                $repeat=true;
              }
            }else{
              agiError("    --> No Reload (Repeat on Timeout is OFF)");
              $repeat=false;
            }
            //exec macro
            if($repeat===false){
              if(($tmacro!=0)&&($tmacro!="")){
                $arrMacro=prepareMacro($tmacro,$tparameter);  
                agiError("    --> Executing macro ".$arrMacro[0].$arrMacro[1]." ...");
                $agi->exec("macro ".$arrMacro[0].$arrMacro[1], '');
              }else agiError("    --> No Macro (timeout macro is null");
            }else agiError("    --> Macro not Execute (node has been reloaded)");
          }
          // END WITH INVALID
          else if((is_array($keyArr))&&(!in_array($exten,$keyArr))){
            agiError("  - CHOICE: $exten (INVALID)");
            //play audio message
            if(($iaudio!=0)&&($iaudio!="")){
              $filepath=_getAudioFilePath($iaudio);
              $filepath=substr($filepath,0,-4);
              if($filepath!=""){
                agiError("    --> Play invalid ($filepath)");
                $agi->get_data($filepath,1,10);
              }else agiError("    --> ERROR: unknown invalid audio message");
            }else agiError("    --> Mute invalid");
            //set repeat
            if($irepeat==1){
              $invalidTimes++; 
              if(($itimes!=0)&&($invalidTimes>$itimes)){ 
                agiError("    --> No Reload (Node has been repeat on Invalid ".($invalidTimes-1)."/$itimes times)");
                $repeat=false;
              }else{
                agiError("    --> Reload node (Repeat on Invalid is ON [".($invalidTimes)."/$itimes])");
                $repeat=true;
              }
            }else{
              agiError("    --> No Reload (Repeat on Invalid is OFF)");
              $repeat=false;
            }
            //exec macro
            if($repeat===false){
              if(($imacro!=0)&&($imacro!="")){
                $arrMacro=prepareMacro($imacro,$iparameter);  
                agiError("    --> Executing macro ".$arrMacro[0].$arrMacro[1]." ...");
                $agi->exec("macro ".$arrMacro[0].$arrMacro[1], '');
              }else agiError("    --> No Macro (macro is null)");
            }else agiError("    --> Macro not Execute (node has been reloaded)");
          }
          // PROCESS CHOICE  
          else if((is_array($keyArr))&&(in_array($exten,$keyArr))){
            agiError("  - CHOICE: $exten");
            if(is_array($children)){
              foreach($children as $targetArr){
                if($exten==$targetArr["key"]){ 
                  $target_id=$targetArr["id"];
                  $target_name=$targetArr["name"];
                  break;
                }
              }
            }else agiError("    --> ERROR: menu has no children");
            if(($target_id!=0)&&($target_id!="")){
              agiError("    --> Process chosen node (".$target_name.")");
              _processNode($target_id);
            }else agiError("    --> ERROR: unable to extract chosen node");
            $repeat=false;
          }
          // ERROR
          else{ 
            agiError("    --> ERROR: menu has no children");
            $repeat=false;
          }
        }        
      break;
    }
  }
}  
    
?>
