<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET'){
    echo "<form method='POST' action='/ui/search.php' >";
    echo "<input type='input' name='query'></input>";
    echo "<input type='submit' value='search'></input>";
    echo "</form>";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST'){

    echo "<form method='POST' action='/ui/search.php' >";
    echo "<input type='input' name='query'></input>";
    echo "<input type='submit' value='search'></input>";
    echo "</form>";
    
    $query = $_POST['query'];
    echo var_dump($query);

    $ldaprdn  = "cn=admin,dc=mvtel,dc=local";     // ldap rdn or dn
    $ldappass = 'mis5093929_ha';  // associated password
    /* echo var_dump($phonedir); */
    $ds = ldap_connect("192.168.15.16");  // must be a valid LDAP server!
    echo "connect result is " . var_dump($ds) . "<br />";

    if ($ds) {

	ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
	ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
	// binding to ldap server
	$ldapbind = ldap_bind($ds, $ldaprdn, $ldappass);

	// verify binding
	if ($ldapbind) {
            echo "LDAP bind successful...";
	    $dn = 'ou=addressbook,dc=mvtel,dc=local';
	    $filter = "(&(objectClass=inetOrgPerson)(cn=$query*))";
	    $justthese = array("cn", "ou",  "mobile", "employeetype");
	    
	    $sr = ldap_search($ds, $dn, $filter, $justthese);
	    $info = ldap_get_entries($ds, $sr);

	    /* echo var_dump($info); */

	    $res = array();
	    
	    /* echo "<table border='true'>"; */
	    foreach ($info as $key => $val) {
		if(isset($res[$val['ou'][0]])) {
		    if(isset($val['ou'][0])) {
			array_push($res[$val['ou'][0]], $val);
		    }
		} else {
		    $res[$val['ou'][0]] = array();
		    if(isset($val['ou'][0])) {
			array_push($res[$val['ou'][0]], $val);
		    }
		}
		/* echo "<tr>";
		   echo "<td><input type='checkbox'></input>";
		   echo "<td>" . $val['cn'][0] . "</td>";
		   echo "<td>" . $val['ou'][0] . "</td>";
		   echo "<td>" . $val['employeetype'][0] . "</td>";
		   if (isset($val['mobile'])) {
		   echo "<td>" . $val['mobile'][0] . "</td>";
		   } else  {
		   echo "<td></td>";
		   }
		   echo "</tr>"; */
	    }
	    /* echo "</table>"; */

	    /* echo var_dump($res); */

	    foreach ($res as $key => $val) {
		if ($val) {
		    echo "<table border='true'>";
		    echo "<tr>";
		    echo "<td colspan='4'>$key</td>";
		    echo "</tr>";
		    foreach ($val as $el) {
			echo "<tr>";
			echo "<td><input type='checkbox'></input>";
			echo "<td>" . $el['cn'][0] . "</td>";
			echo "<td>" . $el['employeetype'][0] . "</td>";
			if (isset($el['mobile'])) {
			    for ($i = 0; $i < count($el['mobile']); $i++) {
				echo "<td>" . $el['mobile'][$i] . "</td>";
			    }
			    } else  {
				echo "<td></td>";
			    }
			    echo "<tr>";
			}
			echo "</table>";
		    }
		}

	    }
	}
	ldap_close($ds);
    }
?>
