<?php

	class LDAP {
		private static $instance;
		
		private static $dn   = LDAP_CONNECTION_DATA["dn"];
		private static $host = LDAP_CONNECTION_DATA["host"];
		private static $port = LDAP_CONNECTION_DATA["port"];

		private static function getInstance() {
			if (!isset(self::$instance)) {
				try {
					self::$instance = ldap_connect("ldap://".self::$host.":".self::$port) or die("Não foi possível conectar ao servidor LDAP.");
				
					ldap_set_option(self::$instance, LDAP_OPT_PROTOCOL_VERSION, 3);
					ldap_set_option(self::$instance, LDAP_OPT_REFERRALS, 0);

				} 
				catch (\Throwable $th) {
					echo $th->getMessage();
				}
			}
			return self::$instance;
		}

		public function authenticate($uid, $password){
			try {   
				$result = ldap_search(self::getInstance(), self::$dn, "(uid=".$uid.")");

				$entries = ldap_get_entries(self::getInstance(), $result);

				for ($i = 0; $i < $entries["count"]; $i++) {
					$dn = $entries[$i]["dn"];
				}

				$result = @ldap_bind(self::getInstance(), $dn, $password);

				ldap_close(self::getInstance());
				
				if ($result) {
					return true;
				}
				else {
					return false;
				}
			} 
			catch (\Throwable $th) {
				return false;
			}
		}

		public function get($uid){
			try {
				$result = ldap_search(self::getInstance(), self::$dn, "(uid=".$uid.")");

				$entries = ldap_get_entries(self::getInstance(), $result);
				$data = [];
				
				for ($i = 0; $i < $entries["count"]; $i++) {
					$dn = $entries[$i]["dn"];
					$data = [
						"uid"  => $entries[$i]["uid"][0],
						"name" => $entries[$i]["displayname"][0],
						"mail" => $entries[$i]["mail"][0],
					];
				}

				ldap_close(self::getInstance());
				
				if (count($data) > 0) {
					return $data;
				}
				else {
					return false;
				}
			} 
			catch (\Throwable $th) {
				return false;
			}
		}
	}

?>