<?php

namespace App\Model;

use App\Model\Exception\StorageNotConnect;

class Storage {

    private $host;
    private $rdn;
    private $pass;
    private $base;
    private $bind;
    private $conn;
    
    public function __construct($config)
    {
        $this->host = $config['host'];
	$this->rdn = $config['rdn'];
	$this->pass = $config['pass'];
	$this->base = $config['base'];
	$this->conn = ldap_connect($this->host);
	if ($this->conn){
	    ldap_set_option($this->conn, LDAP_OPT_PROTOCOL_VERSION, 3);
	    ldap_set_option($this->conn, LDAP_OPT_REFERRALS, 0);
	    $this->bind = ldap_bind($this->conn, $this->rdn, $this->pass);
	    
	}
    }
    

    private function execute($filter, $dn_list, $fields){
	if($this->bind){
	    
	    $sr = ldap_search($this->conn, $dn_list, $filter, $fields);
	    $res = ldap_get_entries($this->conn, $sr);
	    return $res;
	} else {
	    throw new StorageNotConnect("asdasd");
	}
    }
    
    public function get_operator($name){
	
	$filter = "(&(objectClass=InetOrgPerson)(cn=$name))";
	$dn_list = "ou=addressbook,$this->base";
	$fields = array("cn", "employeetype", "uid", "o");
	$res = $this->execute($filter, $dn_list, $fields);
	
        // echo var_dump($res);
        $operator = [];
        $operator['name'] = $res[0]['cn'][0];
        $operator['employeetype'] = $res[0]['employeetype'][0];
        $operator['username'] = $res[0]['uid'][0];
        $operator['role'] = $res[0]['o'][0];
        
	return $operator;

    }
}
