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

namespace Kufer\KuferTools\Oeffentlich\PasswortAnfordern\AktivierePasswort;

class AktivierePasswortUseCase extends \Kufer\KuferTools\Basis\UseCase\UseCase
{
  public function __construct($request)
  {
    parent::__construct($request, new AktivierePasswortResponse());
  }

  public function hasAccess($pToolSectionId = null)
  {
    return true;
  }

  public function action()
  {
    $this->setzeMenupunkte();

    $this->response->erfolgreichAktiviert = $this->handleDoubleOptInKey();
    $this->response->mitCaptcha = $this->mitCaptcha();

    return $this->response;
  }

  private function handleDoubleOptInKey()
  {
    $dbwDoubleOptin = new \DBWorkDblOptinToolPasswortAnfordern();
    $optin = $dbwDoubleOptin->getDblOptinByOptin($this->request->key);
    if ($optin) {
      $this->aenderePasswort($optin);

      return true;
    } else {
      return false;
    }
  }

  private function aenderePasswort($pOptin)
  {
    $login = $pOptin->name;
    $passwordHash = $pOptin->passwort;
    if (\StringOperations::strlen($pOptin->passworttext) > 0) {
      $passwordHash = $pOptin->passworttext;
    }
    $hashversion = $pOptin->hashversion;
    $dbwUser = new \DBWorkUser(1, true);
    $dbwUser->setHashedPassWD($login, $passwordHash, $hashversion);

    $dbwDoubleOptin = new \DBWorkDblOptinToolPasswortAnfordern(1, true);
    $dbwDoubleOptin->deleteByOptin($pOptin->optin);
  }

  private function setzeMenupunkte()
  {
    $menuBar = new \MenuBar();
    $menuBar->setMenuBarFromSettings(array(), 'LOGIN', null, true, true);
    $menuPunkte = $menuBar->getMenuPunkte();

    $zumLoginMenuPunkt = new \Kufer\Menu\MenuPunkt\MenuPunkt4LoginSeite();
    array_unshift($menuPunkte, $zumLoginMenuPunkt);

    $this->response->menuPunkte = $menuPunkte;
  }

  private function mitCaptcha()
  {
    $tool0settings = \ToolSettingsAPI::getToolSettings(0);
    if ($tool0settings->captchaLoginFehlerhaft) {
      $dbwLoginVersuch = new \DBWorkToolsLoginError(1, true);

      return $dbwLoginVersuch->useCaptcha4CurrentIp(true);
    } else {
      return false;
    }
  }
}

class AktivierePasswortRequest
{
  public $key;
}

class AktivierePasswortResponse extends \Kufer\KuferTools\Basis\UseCase\BasisResponse
{
  public $menuPunkte;
  public $erfolgreichAktiviert;
  public $mitCaptcha;
}