<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\KuferTools\Oeffentlich\PasswortAendern\SendePasswortAendernFormular;

use Kufer\Web\KuferTools\Oeffentlich\PasswortAnfordern\Utils\HandlePasswortAnfordernEingaben as HandlePasswortAnfordern;

class SendePasswortAendernFormularUseCase extends \Kufer\Web\KuferTools\Oeffentlich\PasswortAendern\PasswortAendernUseCase
{
  protected $dbwDblOptin;

  
  public function __construct($request)
  {
    parent::__construct($request, new SendePasswortAendernFormularResponse());
    $this->dbwDblOptin = new \DBWorkDblOptinToolPasswortAendern(1, true);
  }

  public function hasAccess($pToolSectionId = null)
  {
    $optin = $this->dbwDblOptin->getDblOptinByOptin($this->request->key);

    return !\is_null($optin) && HandlePasswortAnfordern::isOptinValid($optin);
  }

  public function action()
  {
    $this->response = parent::action();

    $this->response->password = $this->request->password;

    $optin = $this->dbwDblOptin->getDblOptinByOptin($this->request->key);
    $this->response->login = $optin->zusatz; 
    $this->response->key = $optin->optin;

    $checkEingaben = new HandlePasswortAnfordern($this->response->login, $this->request->password, $this->request->passwordRepeated, true);
    $statusCode = $checkEingaben->validateEingaben();
    if (empty($statusCode)) {
      $this->response->errormsg = array();
      $this->setPassword();
      \Logger::logg('Passwort-Änderung: Passwort von Login ' . $this->response->login . ' wurde erfolreich geändert', 40);
    } else {
      \Logger::logg('Passwort-Änderung: Fehler mit Login ' . $this->response->login . ': ' . implode(', ', $statusCode), 40);
      $this->response->errormsg = $statusCode;
    }

    return $this->response;
  }

  private function setPassword()
  {
    $this->dbwDblOptin->deleteByOptin($this->request->key);

    
    $pw = \PasswordFactory::getLatest();
    $passwordHash = $pw->getHash($this->request->password, array());
    $hashversion = $pw::getHashversion();

    $dbwUser = new \DBWorkUser(1, true);
    $dbwUser->setHashedPassWD($this->response->login, $passwordHash, $hashversion);

    \Logger::logg('Passwort des KuferTools Logins "' . $this->response->login . '" wurde geändert', 20);
  }
}

class SendePasswortAendernFormularRequest
{
  
  public $key;

  
  public $password = '';

  
  public $passwordRepeated = '';
}

class SendePasswortAendernFormularResponse extends \Kufer\Web\KuferTools\Basis\UseCase\BasisResponse
{
  public $menuPunkte;
  public $pwAnzahlZeichen;
  public $pwZahlErforderlich;
  public $pwGrossKleinBuchstabenErforderlich;
  public $pwSonderzeichenErforderlich;
  public $https;
  public $login;
  public $password;
  public $optin;
  public $errormsg = array();
  public $key;
}