<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\KuferTools\Utils\LDAP;

class LoginLDAP
{
  private $ldapHelper;
  private $tool0Settings;

  public function __construct()
  {
    if (!function_exists('ldap_connect')) {
      \Logger::logg("Fehlende PHP Extension 'LDAP'!", 200);
      throw new \Exception("Fehlende PHP Extension 'LDAP'");
    }
    $this->tool0Settings = \ToolSettingsAPI::getToolSettings(0);
  }

  public function checkLogin($username, $password)
  {
    $this->setupLdapHelper();

    return $this->checkLdapLogin($username, $password);
  }

  private function setupLdapHelper()
  {
    $this->ldapHelper = new LdapHelper();
    $this->ldapHelper->connect($this->tool0Settings->tnLdapLoginUrl, $this->tool0Settings->tnLdapLoginPort);
    $this->ldapHelper->setOptions(LDAP_OPT_PROTOCOL_VERSION, 3);
    $this->bindServiceAccount();
  }

  private function checkLdapLogin($username, $password)
  {
    $searchResult = $this->searchLehrkraftByUsername($username);
    if ($searchResult['count'] > 0) {
      return $this->ldapHelper->bind($this->ldapHelper->getDnFromSearchResult($searchResult), $password);
    } else {
      
      return \DBWorkLogin::LOGIN_ERR_NO_USER_OR_PW;
    }
  }

  public function createTnFromLdap($username)
  {
    $this->bindServiceAccount();
    $searchResult = $this->searchLehrkraftByUsername($username);

    $nachnameMitTitel = $this->ldapHelper->getFirstAttributeFromSearchResult($searchResult, 'sn');
    $posLastDot = strrpos($nachnameMitTitel, '.');

    if ($posLastDot !== false) {
      $titel = \StringOperations::substr($nachnameMitTitel, 0, $posLastDot + 1);
      $nachname = trim(\StringOperations::substr($nachnameMitTitel, $posLastDot + 1, strlen($nachnameMitTitel) - 1));
    } else {
      $titel = '';
      $nachname = $nachnameMitTitel;
    }

    $vorname = $this->ldapHelper->getFirstAttributeFromSearchResult($searchResult, 'givenName');
    $email = $this->ldapHelper->getFirstAttributeFromSearchResult($searchResult, 'mailprimaryaddress');
    $schulNr = $this->ldapHelper->getFirstAttributeFromSearchResult($searchResult, 'ucsschoolSchool');

    $tnAnlegen = new \Kufer\KuferTools\Oeffentlich\LoginAnfordern\Utils\NeuesLoginAnlegenTeilnehmerLdap($titel, $schulNr);

    return $tnAnlegen->neuesLoginPerDmzAnlegen($username, '', $nachname, $vorname, '', '0', $email, '', \WebPasswordsUsers::AUTH_EXTERN_LDAP);
  }

  private function searchLehrkraftByUsername($username)
  {
    $customSearchFilter = $this->ldapHelper->createSearchFilter(
      $this->tool0Settings->tnLdapLoginSearchFilter,
      array('username' => $username)
    );

    return $this->ldapHelper->search($this->tool0Settings->tnLdapLoginSearchBasisDN, $customSearchFilter);
  }

  private function bindServiceAccount()
  {
    $this->ldapHelper->bind($this->tool0Settings->tnLdapLoginServiceAccDN, $this->tool0Settings->tnLdapLoginServiceAccPassword);
  }
}