<?php

namespace Helpers\SSO;

class LDAP
{
    /** @var string $host */
    private string $host;

    /** @var int $port */
    private int $port;

    /** @var string $suffix */
    private string $suffix;

    /** @var bool $secure */
    private bool $secure;
    
    /**
     * __construct
     *
     * @param  string $host
     * @param  int $port
     * @param  string $suffix
     * @param  bool $secure
     * @return void
     */
    public function __construct(string $host, int $port, string $suffix, bool $secure = false)
    {
        $this->host = $host;
        $this->port = $port;
        $this->suffix = $suffix;
        $this->secure = $secure;
    }
    
    /**
     * connectLDAP
     *
     *
        $ds = ldap_connect('ldap://pirou', 636);
        ldap_start_tls($ds);
        ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
        $rootdn = "cn=admin, dc=example,dc=org";
        $rootpw = 'adminpassword';
        $r=ldap_bind($ds,$rootdn,$rootpw);

        if (ldap_set_option($r,LDAP_OPT_PROTOCOL_VERSION,3))
        {
            echo "Using LDAP v3";
        }else{
            echo "Failed to set version to protocol 3";
        }

     * @param  string $user
     * @param  string $password
     * @return bool
     */
    public function connectLDAP(string $user, string $password) : bool
    {
        $ds = ldap_connect((($this->secure == true)?'ldaps':'ldap').'://'.$this->host.':'.$this->port, $this->port);

        if ($ds) {
            ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
    
            $rootdn = "cn=".$user.", ".$this->suffix;
            return ldap_bind($ds, $rootdn, $password);
        } else {
            return false;
        }
    }
}
