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



class DBWorkBASysUser extends DBWork
{ 

  private $tables = ' benutzer bu LEFT JOIN benutzer_aa buaa ON bu.kennung = buaa.kennung ';

  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);

    $this->select
            = 'bu.id, bu.guid, bu.name, bu.vorname, bu.kennung, bu.aussenst, bu.anrede, bu.telefon, bu.telefon2, bu.telefon3, '
            . 'bu.email, bu.telfax, bu.mobiltel, bu.www, bu.s117, bu.s118, bu.s120, bu.gruppe, bu.gruppe1, bu.gruppe2, bu.gruppe3, bu.webnichtuebersicht, '
            . 'bu.stelle, bu.zimmer, bu.agb_bestaetigen, bu.vorschlagknr, '
            . 'bu.email2, bu.email3, '
            . 'buaa.adr1, buaa.adr2, buaa.adr3, buaa.adr4 ';
    
  }

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

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

  
  public function getCurrentRow($pRefreshCache = false)
  {
    $tmp = $this->getNewObject();
    $tmp->id = $this->getDatamodulValue('id');
    $tmp->guid = $this->getDatamodulValue('guid');
    $tmp->name = $this->getDatamodulValue('name');
    $tmp->vorname = $this->getDatamodulValue('vorname');
    $tmp->namevorname = $this->getDatamodulValue('name') . ', '
                            . $this->getDatamodulValue('vorname');
    $tmp->kennung = $this->getDatamodulValue('kennung');
    $tmp->aussenstelle = $this->getDatamodulValue('aussenst');
    $tmp->anrede = $this->getDatamodulValue('anrede');
    $tmp->tel = $this->getDatamodulValue('telefon');
    $tmp->tel2 = $this->getDatamodulValue('telefon2');
    $tmp->tel3 = $this->getDatamodulValue('telefon3');
    $tmp->email = $this->getDatamodulValue('email');
    $tmp->email2 = $this->getDatamodulValue('email2');
    $tmp->email3 = $this->getDatamodulValue('email3');
    $tmp->fax = $this->getDatamodulValue('telfax');
    $tmp->mobil = $this->getDatamodulValue('mobiltel');
    $tmp->www = $this->getDatamodulValue('www');
    $tmp->rechtber_d = $this->getDatamodulValue('s117');
    $tmp->rechtber_t = $this->getDatamodulValue('s118');
    $tmp->rechtber_k = $this->getDatamodulValue('s120');
    $tmp->gruppe = $this->getDatamodulValue('gruppe');
    $tmp->gruppe1 = $this->getDatamodulValue('gruppe1');
    $tmp->gruppe2 = $this->getDatamodulValue('gruppe2');
    $tmp->gruppe3 = $this->getDatamodulValue('gruppe3');
    $tmp->webnichtuebersicht = $this->getDatamodulValue('webnichtuebersicht');
    $tmp->stelle = $this->getDatamodulValue('stelle');
    $tmp->zimmer = $this->getDatamodulValue('zimmer');
    $tmp->agb_bestaetigen = $this->getDatamodulValue('agb_bestaetigen');
    $tmp->adr1 = $this->getDatamodulValue('adr1');
    $tmp->adr2 = $this->getDatamodulValue('adr2');
    $tmp->adr3 = $this->getDatamodulValue('adr3');
    $tmp->adr4 = $this->getDatamodulValue('adr4');
    $tmp->vorschlagknr = $this->getDatamodulValue('vorschlagknr');

    return $tmp;
  }

  
  public function canupdate($varname)
  {
    switch ($varname) {
      default: return DBWork::canupdate($varname);
      case 'id':
      case 'rechtber':
      case 'namevorname':
      case 'webnichtuebersicht':
      case 'adr1': 
      case 'adr2':
      case 'adr3':
      case 'adr4':
        return false;
    }
  }

  
  public function getBASysUsers($pGruppe = true)
  {
    $where = '';
    $this->dboperation->clear();
    if ($pGruppe) {
      $where = ' WHERE bu.gruppe = \'F\'';
    }
    $this->dboperation->query('SELECT ' . $this->select . ' FROM ' . $this->tables . $where);

    return $this->getAllRows();
  }

  public function getAllQuery(): \SelectQueryBuilder
  {
    return $this->getSelectQueryBuilder()
      ->select($this->select)
      ->from($this->tables);
  }

  
  public function getBASysUser($pBasys_User_Id, $pOnlyWebAktiv = false)
  {
    if ($pBasys_User_Id === '' || $pBasys_User_Id === -1) { 
      return $this->getNewObject();
    }

    $pBasys_User_Id = \Kufer\Web\Classes\Identifier\IdentifierFactory::createFromIdIfNecessary($pBasys_User_Id);
    $builder = $this->getAllQuery()
      ->and(':bid:')
      ->paramId('bid', $pBasys_User_Id, 'bu.id', 'bu.guid');

    if ($pOnlyWebAktiv) {
      $builder = $builder->and($this->getStandardWebEinschraenkung());
    }

    $this->dboperation->clear();
    $this->dboperation->query($builder->getSQL());

    return $this->getFirstRow();
  }

  
  public function getBasysUserForUebersicht()
  {
    $sqlstr = 'SELECT ' . $this->select . ' FROM ' . $this->tables;
    $sqlstr .= 'WHERE ';
    $sqlstr .= $this->getStandardWebEinschraenkung();
    $sqlstr .= $this->getCompleteOrderByDefault(array('name', 'vorname'), 'bu', array($this->orderbyasc, $this->orderbyasc));
    $this->dboperation->clear();
    $this->dboperation->query($sqlstr);

    return $this->getAllRows();
  }

  public function getStandardWebEinschraenkung()
  {
    return 'bu.gruppe = \'F\' AND ' . $this->dboperation->dbparser->isNull('bu.webnichtuebersicht', "'W'") . "= 'F'";
  }

  
  public function getBASysUserByKennung($pBasys_User_Kennung, $pRefreshcache = false, $pOnlyWebAktiv = false)
  {
    static $cache = array();
    $basys_user_kennung = $this->dboperation->getString4Sql($pBasys_User_Kennung);
    if (!$pRefreshcache && array_key_exists($basys_user_kennung, $cache)) {
      return $cache[$basys_user_kennung];
    }
    $sql = 'SELECT ' . $this->select . ' FROM ' . $this->tables . " WHERE bu.kennung='" . $basys_user_kennung . "'";
    if ($pOnlyWebAktiv) {
      $sql .= ' AND ' . $this->getStandardWebEinschraenkung();
    }
    $this->dboperation->clear();
    $this->dboperation->query($sql);
    $cache[$basys_user_kennung] = $this->getFirstRow();

    return $cache[$basys_user_kennung];
  }

  public function translateVarName($varname)
  {
    switch ($varname) { default: return DBWork::translateVarName($varname);
      case 'tel': return 'telefon';
      case 'tel2': return 'telefon2';
      case 'tel3': return 'telefon3';
      case 'mobil': return 'mobiltel';
      case 'fax': return 'telfax';
      case 'aussenstelle': return 'aussenst';
      case 'rechtber_d': return 's117';
      case 'rechtber_t': return 's118';
      case 'rechtber_k': return 's120';
    }
  }

  public function updateBASysBenutzer($pBasysBenutzer, $pUserId, $pDontProtocol = false)
  {
    $orgben = $this->getBASysUser($pBasysBenutzer->id);
    if ($orgben->anrede !== '' && $orgben->anrede == $pBasysBenutzer->anrede) {
      $pBasysBenutzer->anrede = str_replace($orgben->name, $pBasysBenutzer->name, $pBasysBenutzer->anrede);
      $pBasysBenutzer->anrede = str_replace($orgben->vorname, $pBasysBenutzer->vorname, $pBasysBenutzer->anrede);
    }
    $this->updateObject($pBasysBenutzer, $orgben, 'benutzer', 'id', 'U', $pDontProtocol);
    $this->setActionIDs();

    $this->updateBASysBenutzerAA($pBasysBenutzer, $pUserId, $pDontProtocol);
  }

  private function updateBASysBenutzerAA($pBasysBenutzer, $pUserId, $pDontProtocol = false)
  {
    $dbwBenutzerAA = new DBWorkBenutzerAA(1, true);
    $dbwBenutzerAA->updateBenutzerAAByBasysBenutzer($pBasysBenutzer, $pUserId, $pDontProtocol);
  }

  
  public function hasBenutzerKurs($pKennung, $pKnr)
  {
    $kennung = $this->dboperation->getString4Sql($pKennung);
    $knr = $this->dboperation->getString4Sql($pKnr);
    $this->dboperation->clear();
    $this->dboperation->query("SELECT nr FROM kurse WHERE hpm = '" . $kennung . "' AND nr = '" . $knr . "'");

    return ($this->dboperation->rowcount() > 0);
  }

  
  public function getBASysUserByKategorie($pKategorieId, $pRefreshcache = false)
  {
    static $cache = array();
    if ($pKategorieId === null) {
      return array();
    }
    $katid = $this->dboperation->getInt4Sql($pKategorieId);
    if ($katid <= 0) {
      return array();
    }
    if (!$pRefreshcache && array_key_exists($katid, $cache)) {
      return $cache[$katid];
    }
    $sql = 'SELECT ' . $this->select . ' FROM ' . $this->tables . " join kategorien_ma km on bu.id = km.benid where katid='$katid' AND " . $this->getStandardWebEinschraenkung();
    $sql .= ' ORDER BY ' . $this->getOrderbyDefault('km.sort');
    $this->dboperation->clear();
    $this->dboperation->query($sql);
    $cache[$katid] = $this->getAllRows();

    return $cache[$katid];
  }

  public function getBASysUserByKategorieOrParent($pKategorieId, $pRefreshcache = false)
  {
    static $cache = array();
    $katid = $this->dboperation->getInt4Sql($pKategorieId);
    if ($katid <= 0) {
      return array();
    }
    if (!$pRefreshcache && array_key_exists($katid, $cache)) {
      return $cache[$katid];
    }
    static $dbwCat = null;
    if (is_null($dbwCat)) {
      $dbwCat = new DBWorkCategories($this->dbtyp, true);
    }
    $result = $this->getBASysUserByKategorie($katid, $pRefreshcache);

    $cat = $dbwCat->getCategory($katid);
    if ($cat->owner > 0) {
      $basysUserParent = $this->getBASysUserByKategorieOrParent($cat->owner, $pRefreshcache);
      $result = array_merge($result, $basysUserParent);
    }
    $cache[$katid] = $result;

    return $cache[$katid];
  }

  
  public function getBASysUsers4Kurs($pKnr, $pRefreshcache = false)
  {
    if (!is_string($pKnr) || $pKnr === '') {
      return array();
    }

    static $cache = array();
    $knr = $this->dboperation->getString4Sql($pKnr);
    if (!isset($cache[$knr])) {
      $sql = 'SELECT ' . $this->select . ' FROM ' . $this->tables . ' join web_kurse_asp a on bu.id = a.benutzer'
             . ' WHERE a.knr =\'' . $knr . '\' AND ' . $this->getStandardWebEinschraenkung()
             . ' order by a.sort';

      $this->dboperation->clear();
      $this->dboperation->query($sql);
      $cache[$knr] = $this->getAllRows();
    }

    return $cache[$knr];
  }

  
  public function getBASysUsers4Team($pTeamId, $pRefreshcache = false, $pOrderByInt = false)
  {
    if (!is_int($pTeamId) || $pTeamId <= 0) {
      return array();
    }

    $orderBy = ($this->orderby != '') ? $this->getCompleteOrderByDefault($this->orderby, '', true, array($pOrderByInt)) : '';
    static $cache = array();
    $teamId = $this->dboperation->getInt4Sql($pTeamId);
    $cacheKey = $teamId . $orderBy;
    if (!isset($cache[$cacheKey]) || $pRefreshcache) {
      $sql = 'SELECT ' . $this->select . ' FROM ' . $this->tables . ' join teams_ad ta on bu.id = ta.nr'
             . ' WHERE ta.teamsid =' . $teamId . ' AND ' . $this->getStandardWebEinschraenkung();
      $sql .= $orderBy;
      $this->dboperation->clear();
      $this->dboperation->query($sql);
      $cache[$cacheKey] = $this->getAllRows();
    }

    return $cache[$cacheKey];
  }
}