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


class DBWorkDokumenteWeb extends DBWork
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'id, knr, bezeichnung, stand, ' . $this->clob('original') . ', ' . $this->clob('internet') . ', kostenbemerkung, kosten, '
                    . 'autor, autoram, reihenfolge, ' . $this->clob('bemerkung')
                    . ', freigabenoetig, downloadTN, freigabeVon, freigabeam, uploadDoz, objekt_id, autoupload';
    $this->orderby = 'reihenfolge';
  }

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

  
  public function getCurrentRow($pRefreshCache = false)
  {
    $retour = $this->getNewObject();
    $retour->id = $this->getDatamodulValue('id');
    $retour->knr = $this->getDatamodulValue('knr');
    $retour->bezeichnung = $this->getDatamodulValue('bezeichnung');
    $retour->stand = $this->getDatamodulValue('stand');
    $retour->bemerkung = $this->getDatamodulValue('bemerkung');
    $retour->original = $this->getDatamodulValue('original');
    $retour->internet = $this->getDatamodulValue('internet');
    $retour->kostenbemerkung = $this->getDatamodulValue('kostenbemerkung');
    $retour->kosten = $this->getDatamodulValue('kosten');
    $retour->autor = $this->getDatamodulValue('autor');
    $retour->autoram = $this->getDatamodulValue('autoram');
    $retour->reihenfolge = $this->getDatamodulValue('reihenfolge');
    $retour->freigabevon = $this->getDatamodulValue('freigabeVon');
    $retour->freigabeam = $this->getDatamodulValue('freigabeam');
    
    $retour->uploaddoz = $this->getDatamodulValue('uploadDoz');
    $retour->freigabenoetig = $this->getDatamodulValue('freigabenoetig');
    $retour->downloadTN = $this->getDatamodulValue('downloadTN');
    $retour->objekt_id = $this->getDatamodulValue('objekt_id');
    $retour->autoupload = $this->getDatamodulValue('autoupload'); 
    
    $retour->downloadlinkkomplett = '';
    if ($retour->internet !== '') {
      
      $retour->downloadlinkkomplett = '<a target="_blank" href="' . CleanOperations::cleanStringForHtml($retour->internet) . '" title="' . CleanOperations::cleanStringForHtml($retour->bezeichnung) . ' herunterladen">Download</a>';
    }

    
    return $retour;
  }

  
  public function canupdate($pVarname)
  {
    switch ($pVarname) {
      case 'id':
      default: return true;

        
        
      case 'downloadlinkkomplett':
        
      case 'autor':
      case 'autoram':
      case 'suche_kursFreigegeben':
      case 'cachedFileModifyDate':
      case 'darstellungWeb': return false;
        


    }
  }

  

  
  public function insertDokument($pDokument, $dmzBetrieb = false)
  {
    $pDokument->id = $this->insertRecord('dokumenteweb', 'id', 'bezeichnung', false);
    $this->saveChanging('dokumenteweb', '', '', $pDokument->id, 'id', 'I');
    $orgDokument = $this->getDokument($pDokument->id);
    
    $orgDokument->id = $pDokument->id;
    $this->updateObject($pDokument, $orgDokument, 'dokumenteweb', 'id', 'A', false, $dmzBetrieb);
    $this->setActionIDs();

    return $pDokument->id;
  }

  
  public function updateDokument($pDokument, $pDmzBetrieb = false)
  {
    $orgDokument = $this->getDokument($pDokument->id);
    
    $this->updateObject($pDokument, $orgDokument, 'dokumenteweb', 'id', 'U', false, $pDmzBetrieb);
    $this->setActionIDs();
  }

  public function getAllQuery(): \SelectQueryBuilder
  {
    return $this->getSelectQueryBuilder()
      ->select($this->select)
      ->from($this->getTableName(), 'dw')
      ->orderBySrcCode($this->getCompleteOrderByDefault('reihenfolge', 'dw'));
  }

  
  public function getMaxReihenfolge4Kurs($pKnr)
  {
    $knr = $this->dboperation->getString4Sql($pKnr);
    
    $sql = 'SELECT ' . $this->dboperation->dbparser->isNull('max(reihenfolge)', 0) . ' AS maxreihe FROM dokumenteweb WHERE knr = \'' . $knr . '\'';
    $this->dboperation->clear();
    $this->dboperation->query($sql);
    $this->dboperation->selectrow(0);

    return $this->getDatamodulValue('maxreihe');
  }

  
  public function getReleasedKnrFromDokumente($pDokumentname)
  {
    $sql = 'SELECT DISTINCT(knr) FROM dokumenteweb  '
           . 'WHERE bezeichnung = \'' . $pDokumentname . '\' AND uploaddoz = -1' . "\n "
           . 'ORDER BY knr ASC';
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    $ary = array();
    $rows = $this->dboperation->rowcount();
    if ($rows > 0) {
      for ($i = 0; $i < $rows; $i++) {
        $this->dboperation->selectrow($i);
        $tmp = $this->getDatamodulValue('knr');
        if (isset($tmp)) {
          array_push($ary, $tmp);
        }
      }
    }

    return $ary;
  }

  
  public function getDokument($pDokument_Id)
  {
    $dokument_id = $this->dboperation->getInt4Sql($pDokument_Id);
    $sql = 'SELECT ' . $this->select . ' FROM dokumenteweb dw '
           . 'WHERE dw.id = ' . $dokument_id . "\n "
           . $this->getCompleteOrderByDefault('dw.id');
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    return $this->getFirstRow();
  }

  
  public function getDocCount4Kurs($pKid)
  {
    $kid = $this->dboperation->getString4Sql($pKid);
    $sql = 'SELECT count(id) num_docs FROM dokumenteweb dw WHERE knr = \'' . $kid . '\'';
    $this->dboperation->clear();
    $this->dboperation->query($sql);
    $this->dboperation->selectrow(0);

    return $this->getDatamodulValue('num_docs');
  }

  public function getDokumente4KursQuery($pKnr): \SelectQueryBuilder
  {
    return $this->getAllQuery()
      ->and('1=1')
      ->addToWhere($this->getSearchSQL('dw.', $pKnr));
  }

  
  public function getDokumente4Kurs($pKnr)
  {
    $builder = $this->getDokumente4KursQuery($pKnr);

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

    return $this->getAllRows();
  }

  
  public function getDokuIds2Process($pDokuIDAry)
  {
    $dokuIds = array();
    if (empty($pDokuIDAry)) {
      return $dokuIds;
    }
    
    foreach ($pDokuIDAry as $dokuId) {
      $dokuIds[] = $this->dboperation->getInt4Sql($dokuId);
    }
    $sql = 'SELECT dkw.id FROM dokumenteweb dkw WHERE dkw.id IN (' . StringOperations::convertArray2InList($dokuIds) . ')';
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    return $this->getAllRowsSingleColumn('id');
  }

  

  
  public function getSearchSQL($pPraeffix, $pKnr = '')
  {
    $sql = '';
    $knr = $this->dboperation->getString4Sql($pKnr);
    $praeffix = $this->dboperation->getString4Sql($pPraeffix);
    if ($pKnr != '') {
      $sql .= ' AND ' . $praeffix . "knr = '$knr'";
    }

    if (isset($this->fromobject)) {
      if (isset($this->fromobject->freigabenoetig)) {
        if ($this->fromobject->freigabenoetig) {
          $freigabeDatum = DateTimeOperations::getDateNow();
          if (isset($this->fromobject->freigabeam) && DateTimeOperations::isValidDate($this->fromobject->freigabeam)) {
            $freigabeDatum = $this->fromobject->freigabeam;
          }
          $sql .= ' AND (' . $this->dboperation->dbparser->isNull($praeffix . 'freigabenoetig', "'F'") . "<> 'W' " 
                         . 'OR (' . $this->dboperation->dbparser->isNull($praeffix . 'freigabenoetig', "'F'") . "= 'W' " 
                              . 'AND dw.freigabeam < ' . $this->datetimeop->getFormatDate4Server($freigabeDatum) . ')' 
                  . ')';
        }
      }
      if (isset($this->fromobject->downloadtn) && is_numeric($this->fromobject->downloadtn)) {
        $sql .= ' AND ' . $this->dboperation->dbparser->isNull($praeffix . 'downloadtn', SHOW_DOKU_TN_ALL) . ' >=' . $this->fromobject->downloadtn;
      }

      if (isset($this->fromobject->suche_kursFreigegeben) && $this->fromobject->suche_kursFreigegeben) {
        $sql .= " AND EXISTS( select * from kurse kurs where {$praeffix}knr = kurs.nr ";
        $sql .= ' AND ' . DBWorkKurseBase::getSQLInternetIntranetAktiv('kurs.');
        $sql .= ' AND ' . $this->datetimeop->getGueltigPart('kurs.', 'internetvon', 'internetbis') . ') ';
      }
    }
    if (isset($this->toobject)) {
      if (isset($this->toobject->downloadtn) && is_numeric($this->toobject->downloadtn)) {
        $sql .= ' AND ' . $this->dboperation->dbparser->isNull($praeffix . 'downloadtn', SHOW_DOKU_TN_ALL) . ' <=' . $this->toobject->downloadtn;
      }
    }

    return $sql;
  }

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

  
  public function deleteDokument($pDokumentId, $pDmzBetrieb = false)
  {
    $dokumentid = $this->dboperation->getInt4Sql($pDokumentId);
    $this->dboperation->clear();
    $this->dboperation->execute('DELETE FROM dokumenteweb WHERE id=' . $dokumentid);
    $this->saveChanging('dokumenteweb', '', '', "'" . $dokumentid . "'", 'id', 'D', $pDmzBetrieb);

    $this->setActionIDs();
  }

  
  public function getDocCount4Objekt($pObjektId)
  {
    $objId = $this->dboperation->getInt4Sql($pObjektId);
    $sql = 'SELECT count(id) num_docs FROM dokumenteweb dw WHERE objekt_id = \'' . $objId . '\'';
    $this->dboperation->clear();
    $this->dboperation->query($sql);
    $this->dboperation->selectrow(0);

    return $this->getDatamodulValue('num_docs');
  }

  
  public function getDokumente4Objekt($pObjektId)
  {
    $sql = 'SELECT ' . $this->select . ' FROM dokumenteweb dw WHERE  dw.objekt_id = ' . $this->dboperation->getInt4Sql($pObjektId);
    $sql .= $this->getSearchSQL('dw.');
    $sql .= $this->getCompleteOrderByDefault('reihenfolge', 'dw');
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    return $this->getAllRows();
  }
}