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


class ToolAdressInfo extends ToolBase
{
  private $_user;
  private $_dbwadr;

  private $_datenSaetzeProSeite;

  
  public function __construct()
  {
    parent::__construct();
    $this->toolTitle = 'Adressinfo';
    $this->_user = SessionOperations::getCurrentWebToolsUser();
    $this->_dbwadr = new DBWorkAdresse();

    
    $this->_datenSaetzeProSeite = $this->toolSettings->datensaetzeproseite > 0 ? $this->toolSettings->datensaetzeproseite : 6;
  }

  
  protected function doByBrowserRefresh()
  {
    $_POST = array();
    $_SERVER['REQUEST_METHOD'] = 'GET';
  }

  
  public function init($pPageId)
  {
    
    $this->checkBrowserReload();
    
    switch ($pPageId) {
      default:
      case 55:
        $statusMessage = '';
        if (PostOperations::isDefined('adressinsert') && PostOperations::getVarValue('adressinsert') == 1) {
          if (Xsrf::KEY_OK == Xsrf::checkAndUseXsrfFromGet('wt_ma_adrneu')) {
            $detailsSightId = 58;
            
            $result = $this->_handleAdressInsert($detailsSightId);
            $statusMessage = $result['statusMessage'];
            $adrId = $result['adrId'];
            if ($adrId != -1) {
              $dbwAdr = $this->_getDefaultDBWorkAdresse();
              $alleAdressNummern = $dbwAdr->getAdressIdsbyFilter();
              $this->setTotalData($alleAdressNummern);
              $keys = array_keys($this->getTotalData(), $adrId);
              GetOperations::fakeCall(array('tool_id' => \ToolsAPI::TOOL_ADRESSINFO_MA, 'toolsection_id' => 410, 'anr' => $adrId,
                  'currentIndex' => ($keys[0] + 1)));
              $page = $this->_handleAdressdetails(410, $statusMessage);
              break;
            }
          } else {
            $statusMessage = HTMLOperations::getAlertBox('Die Adresse konnte aus technischen Gründen nicht angelegt werden.', 'Fehler beim Anlegen der Adresse');
          }
        }
        $page = $this->_handleAdressUebersicht($pPageId, $statusMessage);
        break;
      case 410:
        $statusMessage = '';
        
        if (PostOperations::isDefined('adrupdate') && PostOperations::getVarValue('adrupdate') == 1) {
          if (Xsrf::KEY_OK == Xsrf::checkAndUseXsrfFromGet('wt_ma_adrbearbeiten', $this->getNr4Userdetails('adresse'))) {
            $detailsSightId = 58;
            
            $statusMessage .= $this->_handleAdressUpdate($detailsSightId);
          } else {
            $statusMessage = HTMLOperations::getAlertBox('Die Adresse konnte aus technischen Gründen nicht bearbeitet werden.', 'Fehler beim Bearbeiten der Adresse');
          }
        }
        $page = $this->_handleAdressDetails($pPageId, $statusMessage);
        break;
    }
    if ($page == null) {
      throw new Exception('ungültige PageId');
    }

    $this->currentPage = $page;
  }

  

  
  private function _handleAdressUebersicht($pPageId, $pStatusMessage = '')
  {
    
    
    $this->updateAndGetSelectedIds();
    $pageLinks = array();
    $dbwAdr = $this->_getDefaultDBWorkAdresse();

    $searchAPI = new AdresssuchAPI();
    
    
    $searchAPI->getSearchParamsFromReqToSession('tool' . $this->toolId, 'searchadresse');

    
    
    $dbwAdr->fromobject = $searchAPI->getFromObjectBySession($dbwAdr->fromobject, 'tool' . $this->toolId);
    $dbwAdr->toobject = $searchAPI->getToObjectBySession($dbwAdr->toobject, 'tool' . $this->toolId);


    
    $alleAdressNummern = $dbwAdr->getAdressIdsbyFilter();

    
    $this->setTotalData($alleAdressNummern);
    $adressAnzahl = count($alleAdressNummern);
    $adrNummernDerSeite = ToolsAPI::getDataForCurrentPage($alleAdressNummern, $this->_datenSaetzeProSeite);

    
    $data = $dbwAdr->getAdressenByIDArray($adrNummernDerSeite);
    

    
    $userid = $this->_user->getIdentifier();
    
    
    
    $pageLinks['adressDetails'] = (\SecurityOperations::privilegAllowed($userid, \ToolsAPI::TOOL_ADRESSINFO_MA, $pPageId . '.0.1') == 2
                                     && $this->rechteOR(array('410.1.1', '410.1.3')));

    
    if (\SecurityOperations::privilegAllowed($userid, \ToolsAPI::TOOL_ADRESSINFO_MA, $pPageId . '.0.2') == 2) {
      $pageLinks['newAdresse'] = true;
      if (SessionOperations::isReplikat()) {
        $pageLinks['newAdresse'] = $this->allgSettings->dmzEnabled;
      }
    }

    
    $pageLinks['print'] = (\SecurityOperations::privilegAllowed($userid, \ToolsAPI::TOOL_ADRESSINFO_MA, $pPageId . '.0.3') == 2);

    
    $hasButton4Checkbox = false;
     
    $pageLinks['markieren'] = (\SecurityOperations::privilegAllowed($userid, \ToolsAPI::TOOL_ADRESSINFO_MA, $pPageId . '.0.1') && $hasButton4Checkbox);
    $pageLinks['checkboxen'] = $hasButton4Checkbox;

    $pageLinks['filter'] = true;
    $pageLinks['self'] = $this->getUrlParamsForFile(array('toolsection_id' => 55));
    

    
    $adrSuchForm = $this->getSearchForm();
    $page = new PageMaAdressUebersicht($this, $data, $adressAnzahl, $this->_datenSaetzeProSeite, $pPageId, $pStatusMessage, $adrSuchForm);
    $page->setLinks($pageLinks);

    return $page;
  }

  

  
  public function getAjaxResponse()
  {
    $result = '';
    
    if (RequestOperations::isDefined('action')) {
      switch (RequestOperations::getVarValue('action')) {
        
        case 'newAdresse':
          $pageId4Details = 58; 

          $dbwAdr = new DBWorkAdresse();
          $data = $dbwAdr->getNewObject();
          $searchAPI = new AdresssuchAPI();
          
          $fromObject = $searchAPI->getFromObjectBySession(null, 'tool' . $this->getToolId());
          
          $data->name = $fromObject->name;
          $data->vorname = $fromObject->vorname;
          $data->gebdat = ''; 

          $xsrf = new Xsrf();
          $xsrfKey = $xsrf->generateKey4Action('wt_ma_adrneu'); 
          
          
          
          $page = new TabPageSightBuilder('Details zur neuen Adresse', $data, $this->getToolId(), $pageId4Details, true, 'Infotool', $xsrfKey);
          $result = JsonOperations::encode4Ajax($page->getAjaxObject4Tab());
          break;

          
        case 'updateAdresse':
          $pageId4Details = 58; 
          
          $dbwAdr = new DBWorkAdresse();
          $anr = PostOperations::getVarValue('anr', -1);
          $data = $dbwAdr->getAdresse($anr);
          

          $xsrf = new Xsrf();
          $xsrfKey = $xsrf->generateKey4Action('wt_ma_adrbearbeiten', $anr);
          
          
          $page = new TabPageSightBuilder('Adressdetails bearbeiten', $data, $this->getToolId(), $pageId4Details, true, 'Infotool', $xsrfKey);
          $result = JsonOperations::encode4Ajax($page->getAjaxObject4Tab());
          break;
        case 'validate':
          $result = JsonOperations::encode4Ajax($this->_handleAjaxValidateBankData());
          break;
          
          
      }
    }

    return $result;
  }

  
  private function _handleAdressInsert($pSightId)
  {
    $saveResult = array('statusMessage' => '', 'adrId' => -1);
    $dbwAdr = new DBWorkAdresse();
    $adresse = $dbwAdr->getNewObject();
    
    if (RequestOperations::getMethod() == 'post') {
      $builder = new SightBuilder($this->getToolId(), $pSightId, $adresse);
      
      $builder->saveData();
      $validationOK = $builder->checkValidation();
      if ($validationOK) {
        
        $saveResult = AdressAPI::saveAdresse($builder, false);
      } else {
        $saveResult['statusMessage'] = $builder->buildInvalidFieldsDiv();
      }
    }
    
    return $saveResult;
  }

  
  private function _handleAdressUpdate($pSightId)
  {
    $statusMessage = '';
    $dbwAdr = new DBWorkAdresse();
    $anr = $this->getNr4Userdetails('adresse');
    $adresse = $dbwAdr->getAdresse($anr);
    
    if (RequestOperations::getMethod() == 'post') {
      $builder = new SightBuilder($this->getToolId(), $pSightId, $adresse);
      
      $builder->saveData();
      $validationOK = $builder->checkValidation();
      if ($validationOK) {
        
        $saveResult = AdressAPI::saveAdresse($builder, true);
        $statusMessage .= $saveResult['statusMessage'];
      }
    } 
    
    return $statusMessage;
  }

  

  
  private function _handleAdressdetails($pPageId = 410, $statusMessage = '')
  {
    
    $fromOtherTab = SessionOperations::getVarValueWTIntern($this->toolId . '_fromTab');
    
    
    if (GetOperations::isDefined('fromOtherTool')) {
      $adr = GetOperations::getVarValue('anr');
      $this->setTotalData(array($adr));
    }
    $adr = $this->getNr4Userdetails('adresse');
    
    $data = $this->_dbwadr->getAdresse($adr, true);

    $userid = $this->getUser()->getIdentifier(); 
    
    $reiterSeite = new ReiterSeite($pPageId, $this->toolSettings->reiterBeschriftung);

    
    
    
    $allAdrNrs = $this->getTotalData('##');

    $anzahlAllerAdressen = 0;
    $anzahlAdrProSeite = 1;
    if ($allAdrNrs != '##') {
      $anzahlAllerAdressen = count($allAdrNrs);
    }

    
    $detailSightId = 58;

    $tabPage = new TabCollectionPersonendetails(
      'Adresse',
      $pPageId,
      $this,
      'Adresse ' . $data->namevorname,
      $data,
      $anzahlAllerAdressen,
      $anzahlAdrProSeite,
      $statusMessage,
      'adressdetails'
    );
    $pageLinks = array();


    
    if (\SecurityOperations::privilegAllowed($userid, $this->getToolId(), $reiterSeite->getRecht('Adressdetails'))) {
      $tabPage->addTabPage(new TabPageSightBuilderUebersicht($reiterSeite->getLabel('Adressdetails'), $data, $this->getToolId(), $detailSightId));
    }
    
    

    
    
    if (\SecurityOperations::privilegAllowed($userid, $this->getToolId(), $reiterSeite->getRecht('Fotos'))) {
      $tabPage->addTabPage(new TabAdressFotos($reiterSeite->getLabel('Fotos'), $data->id));
    }

    
    
    
    $pageLinks['back'] = ToolsAPI::getLastHistoryEntry();
    if ($fromOtherTab != '') {
      $pageLinks['back'] .= '#' . $fromOtherTab;
    }

    




    
    if (\SecurityOperations::privilegAllowed($userid, \ToolsAPI::TOOL_ADRESSINFO_MA, $pPageId . '.0.1')) {
      $pageLinks['adrUpdate'] = true;
      
      
      if (SessionOperations::isReplikat()) {
        if (!$this->allgSettings->dmzEnabled) {
          $dbwReplikatSettings = new DBWorkWebReplikatSettings();
          $highestAdrNr = $dbwReplikatSettings->getHighestAdrNr();
          if ($data->id > $highestAdrNr->value) {
            
            
            $pageLinks['adrUpdate'] = false;
          }
        }
      }
    }



    
    if (\SecurityOperations::privilegAllowed($userid, \ToolsAPI::TOOL_ADRESSINFO_MA, $pPageId . '.0.2')) {
      $pageLinks['druck_smallJs'] = 'javascript:window.print();';
    }

    $tabPage->setLinks($pageLinks);

    return $tabPage;
  }

  

  
  public function getSearchForm()
  {
    $adressForm = '<div id="adrSuche" style="display:none;">' . "\n";
    $searchAPI = new AdresssuchAPI();
    
    
    $fromobject = $searchAPI->getFromObjectBySession(new Adresse(), 'tool' . $this->toolId, false);

    
    $actionLink = $searchAPI->getAdrSearchLink();
    $adressForm
       .= '<form action="' . $actionLink . '" method="POST"> '
       . ' <table cellspacing="5" cellpadding="5">' . "\n"
       . '   <tr><td class="labelleft">Name:</td>'
       . '     <td class="inputleft"><input type="text" name="s_name" value="' . CleanOperations::cleanStringForHtml($fromobject->getVarValue('name')) . '" size="20"></td>' . "\n"
       . '     <td class="labelright">Nummer:</td>'
       . '     <td><input type="text" size="5" class="val_int" name="s_adrnr" value="' . CleanOperations::cleanInt($fromobject->getVarValue('id'), '') . '"></td></tr>' . "\n"
       . '   <tr><td class="labelleft">Vorname:</td>'
       . '     <td class="inputleft"><input type="text" name="s_vorname" value="' . CleanOperations::cleanStringForHtml($fromobject->getVarValue('vorname')) . '" size="20"></td>' . "\n"
       . '   <tr><td class="labelleft">Stra&szlig;e:</td>'
       . '     <td class="inputleft"><input type="text" name="s_strasse" value="' . CleanOperations::cleanStringForHtml($fromobject->getVarValue('strasse')) . '" size="20"></td></tr>' . "\n"
       . '   <tr><td class="labelleft">Wohnort:</td>'
       . '     <td class="inputleft"><input type="text" name="s_wohnort" value="' . CleanOperations::cleanStringForHtml($fromobject->getVarValue('ort')) . '" size="20"></td></tr>' . "\n"
       . ' </table>' . "\n";

    $adressForm .= '</form>' . "\n"
                . '</div>' . "\n";

    return $adressForm;
  }

  

  public function getToolId()
  {
    return \ToolsAPI::TOOL_ADRESSINFO_MA;
  }

  private function _getDefaultDBWorkAdresse()
  {
    $dbwAdr = new DBWorkAdresse();
    $dbwAdr->newSearch();
    $dbwAdr->setPersonenOrderBySettings($this->toolSettings, 'adr');

    return $dbwAdr;
  }
}