<?php
/**
 * 
 */

/**
 * getNode
 * 
 * get list of object under node
 * 
 * @param array  $Cfg   - Configuration array
 * @param string $ID 
 */
function getNode($Cfg, $ID)
{
  $cnx=NULL;
  $TOKEN="";
  $oUser=[];
  $ad = [];
  $hasChildren = ['#','root','Organizational-Unit','Container','Builtin-Domain','Physical-Location','Organization'];

  error_log("Dans get_node - $ID");
  // Recupere le token
  $TOKEN = $_COOKIE["aduc"];
  error_log("Cookie : ".$_COOKIE["aduc"]);
  $redis = new Redis();
  $redis->connect($Cfg['redishost'], 6379);
  $oUser = json_decode($redis->get($TOKEN));
  error_log(print_r($oUser,true));
  // Ajuste le timeOut
  $oUser->timeOut = date('Y-m-d H:i:s',time()+3600);
  $redis->set($TOKEN,json_encode($oUser));

  // Connection à l'AD
  if( ! $cnx=ldap_connect($Cfg['uri'])) 
    die("erreur: ldap_connect");

  if( ! ldap_bind ( $cnx , $oUser->Login , $oUser->Password ) )
  {
    echo ldap_errno($cnx).": ".ldap_error($cnx);
    die("<br />erreur: ldap_bind");
  }
    
  ldap_set_option($cnx, LDAP_OPT_PROTOCOL_VERSION, 3);
  ldap_set_option($cnx, LDAP_OPT_REFERRALS, 0);

  switch( $ID )
  {
    case '#':
      // ldap root
      $ad = [ 
        "id"       => "REM9ZWFzeWxpbnV4LERDPWxhbgo=",
        "text"     => "DC=easylinux,DC=lan",
        "type"     => "root",
        "children" => []
      ]; 
      $sr = ldap_list($cnx, $Cfg['baseDN'],"dn=*",['dn','objectCategory','showinadvancedviewonly']);

      $info = ldap_get_entries($cnx, $sr);

      for ($i=0; $i < $info["count"]; $i++) {
        //echo var_dump($info);
        
        //if( $info[$i]["showinadvancedviewonly"][0] == "FALSE" )
        {
          error_log(print_r($info[$i],true));
          $sType = extractNameFromDn($info[$i]["objectcategory"][0]);
          $bChildren = false;
          if(in_array($sType,$hasChildren)){
            $bChildren = true;
          }
          $ad['children'][] = [
            'id' => base64_encode($info[$i]["dn"]),
            'text' => extractNameFromDn($info[$i]["dn"]),
            'type' => $sType,
            "children" => $bChildren
          ];
        }
      }
      ldap_close($cnx);
      
      return $ad;
      break;

    default:
      $Dn = base64_decode($ID);
      $ad = [ ]; 
      $sr = ldap_list($cnx, $Dn,"dn=*",['dn','objectCategory','showinadvancedviewonly']);

      $info = ldap_get_entries($cnx, $sr);
      error_log("DNs : ". print_r($info,true));
      for ($i=0; $i < $info["count"]; $i++) {
        $sType = extractNameFromDn($info[$i]["objectcategory"][0]);
        $bChildren = false;
        if(in_array($sType,$hasChildren)){
          $bChildren = true;
        }
        error_log(print_r($info[$i],true));
        $ad[] = [
          'id' => base64_encode($info[$i]["dn"]),
          'text' => extractNameFromDn($info[$i]["dn"]),
          'type' => $sType,
          "children" => $bChildren
        ];
        
      }
      ldap_close($cnx);
      return $ad;
  }
}

function extractNameFromDn($dn)
{
  //CN=Builtin,DC=easylinux,DC=lan
  return explode("=",explode(",",$dn)[0])[1];
}
