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

class DBWorkWBLoginsSettings extends DBWorkGenerated
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'tnr, merklisteerinnerungsmailaktiv';
    $this->_dataModulFields = array('tnr', 'merklisteerinnerungsmailaktiv', 'id');
  }

  
  public function getNewObject()
  {
    return new WBLoginSettings();
  }

  public function getTableName(): string
  {
    return 'web_wblogins_settings';
  }

  public function createNewEntry($tnr)
  {
    $qb = $this->getInsertIntoQueryBuilder();
    $sql = $qb->insertInto($this->getTableName())
              ->columns(array('tnr'))
              ->values(array(':tnr:'))
              ->paramInt('tnr', $tnr)
              ->getSQL();
    $this->dboperation->clear();
    $this->dboperation->execute($sql);
  }

  public function getSettings($tnr)
  {
    $qb = $this->getSelectQueryBuilder();
    $sql = $qb->select($this->select)
              ->from($this->getTableName())
              ->where('tnr = :tnr:')
              ->paramInt('tnr', $tnr)
              ->getSql();
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    return $this->getFirstRow();
  }

  public function settingsExist($tnr)
  {
    $settings = $this->getSettings($tnr);

    return $settings->tnr === $tnr;
  }

  public function setSetting($key, $value)
  {
    if (!WBLoginSettings::isSettingKey($key)) {
      return;
    }
    $tnr = SessionOperations::getCurrentStammhoererTnr();
    if (!$this->settingsExist($tnr)) {
      $this->createNewEntry($tnr);
    }
    $sql = 'UPDATE ' . $this->getTableName()
      . " SET $key = '{$this->dboperation->getString4Sql($value)}'"
      . " WHERE tnr = '$tnr'";
    $this->dboperation->clear();
    $this->dboperation->execute($sql);
  }
}