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

if (!defined('BASEDIR')) {
  include_once '..' . DIRECTORY_SEPARATOR . 'constants.php';
}


class DBWorkTeams extends DBWorkGenerated
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'id, lfdnr, team, text, sort, email';
    $this->_dataModulFields = array('team', 'text', 'email', 'lfdnr', 'sort', 'id');
    $this->orderby = 'lfdnr';
  }

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

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

  public function getSearchSQL($pPraeffix)
  {
    $sql = ''; 

    if (isset($this->fromobject)) {
      $prefix = $this->dboperation->getString4Sql($pPraeffix);
      if (isset($this->fromobject->id) && is_array($this->fromobject->id)) {
        try {
          $ids = $this->dboperation->getInts4Sql($this->fromobject->id);

          return " AND {$prefix}id IN ( " . StringOperations::convertArray2InList($ids, true) . ') ';
        } catch (InvalidArgumentException $e) {
        }
      }
    }

    return $sql;
  }

  public function getTeamsWithMitarbeiter()
  {
    if ($this->getTableName() == '') {
      throw new Exception('ungültiger Aufruf, ' . __CLASS__ . ' ist nicht dafür vorbereitet');
    }
    $sql = "SELECT $this->select FROM " . $this->getTableName();

    $dbwBasysUser = DBWorkBASysUser::getDefaultInstance();
    $sql .= ' WHERE id in (select ta.teamsid from teams_ad ta join benutzer bu on bu.id = ta.nr and ta.typ = \'B\' and ' . $dbwBasysUser->getStandardWebEinschraenkung() . ')';

    $sql .= $this->getSearchSQL('');

    if ($this->orderby != '') {
      $sql .= $this->getCompleteOrderByDefault($this->orderby);
    }
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    return $this->getAllRows();
  }

  public function getTeamsWithDozenten($pSemlist)
  {
    if ($this->getTableName() == '') {
      throw new Exception('ungültiger Aufruf, ' . __CLASS__ . ' ist nicht dafür vorbereitet');
    }
    $sql = "SELECT $this->select FROM " . $this->getTableName();

    $sql .= ' WHERE id in (select dt.team_id from dozenten_teams dt join dozenten d on d.nr = dt.dnr';

    $dbwDoz = DBWorkDozentenWB::getDefaultInstance();

    $sql .= $dbwDoz->getSQLPart4GetDozenten4Uebersicht($pSemlist, false, false);
    $sql .= ')';

    $sql .= $this->getSearchSQL('');

    if ($this->orderby != '') {
      $sql .= $this->getCompleteOrderByDefault($this->orderby);
    }
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    return $this->getAllRows();
  }
}