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

use Kufer\Web\Classes\Identifier\Identifier;

abstract class Personn extends Datamodul implements \Kufer\Mail\Address\IEMailAddress
{
  
  public $guid;

  public $anrede = '';
  public $name = '';
  public $vorname = '';
  public $namevorname = '';
  public $suchbegriff = '';

  public $zusatz = '';
  public $zusatz2 = '';
  public $zusatz3 = '';
  public $ort = '';
  public $strasse = '';
  public $nation = '';

  
  public $email;
  
  public $email2;
  public $emailgrafik;

  public $tel_anzeige = '';
  public $tel2_anzeige = '';
  public $fax_anzeige = '';
  public $fax2_anzeige = '';
  public $mobil_anzeige = '';
  public $email_anzeige = '';
  public $email2_anzeige = '';

  
  public $tel;
  
  
  
  public $tel2;
  
  public $mobil;
  
  public $tel_dyn;
  
  public $fax;
  
  public $fax2;

  public $gebjahr;
  public $gebdat = DEFAULTDATE;
  public $geschlecht = '';

  public $kontoinhaber = '';
  public $konto = '';
  public $blz = '';
  public $bankbez = '';
  public $bic = '';
  public $iban = '';
  
  public $mandatam;

  public $titel = '';
  public $beruf = '';

  public $info = '';
  public $info_intern = '';
  
  public $email_formular = '';
  public $emailgrafik_formular = '';

  
  private $zustimmungen;

  
  public function getTelNrs()
  {
    return $this->getKommWerteByParam(array('tel', 'mobil', 'tel2'));
  }

  public function getDMZValue($fieldname)
  {
    if ($fieldname == 'mandatam') {
      return DateTimeOperations::getValidDateTimeString($this->mandatam, true);
    }
    if ($fieldname == 'bankbez') {
      return StringOperations::substr($this->bankbez ?? '', 0, 30);
    }

    return parent::getDMZValue($fieldname);
  }

  public function getVarValue($pName)
  {
    switch ($pName) {
      
      case 'namevorname':
      case 'name_ggf_vorname': return $this->getVarValue('name') . ($this->getVarValue('vorname') ? ', ' . $this->getVarValue('vorname') : '');
      case 'name_vorname_ohne_komma': return trim($this->getVarValue('name') . ' ' . $this->getVarValue('vorname'));
      case 'titel_name_vorname': return $this->fuegeTitelHinzu($this->getVarValue('name_vorname_ohne_komma'), $this->getVarValue('name_titel'));
      case 'titel_name': return $this->fuegeTitelHinzu($this->getVarValue('name'), $this->getVarValue('name_titel'));
      case 'vorname_name_ohne_komma': return trim($this->getVarValue('vorname') . ' ' . $this->getVarValue('name'));
      case 'titel_vorname_name': return $this->fuegeTitelHinzu($this->getVarValue('vorname_name_ohne_komma'), $this->getVarValue('name_titel'));
      case 'name_vorname_nr': return $this->getVarValue('name_vorname_ohne_komma') . ' (' . $this->id . ')';
      case 'name_zusatz': return trim(trim($this->getVarValue('name')) . ' ' . trim($this->getVarValue('zusatz')) . ' ' . trim($this->getVarValue('zusatz2')));
        
      case 'bankbezAnhandIban': return $this->getBankbezAnhandIban();
      case 'bankbezLangAnhandIban': return $this->getBankbezLangAnhandIban();
      case 'ansprache_default': return $this->getAnsprache();
      case 'kontoinhaber':
        return StringOperations::substr($this->kontoinhaber, 0, 35);
      case 'nurplz':
        return \Kufer\Web\Classes\Addfunctions\PlzOperations::getPlzFromPlzOrtStr($this->nation, $this->ort);
      case 'nurort':
        return \Kufer\Web\Classes\Addfunctions\PlzOperations::getOrtFromPlzOrtStr($this->nation, $this->ort);
      case 'nurstrasse':
        $found = array();
        preg_match('/(\\D*)(.*)/', $this->getVarValue('strasse'), $found);
        if (isset($found[1])) {
          return trim($found[1]);
        }

        return '';
      case 'nurhausnr':
        $found = array();
        preg_match('/(\\D*)(.*)/', $this->getVarValue('strasse'), $found);
        if (isset($found[2])) {
          return trim($found[2]);
        }

        return '';
      case 'iban_button_bankdaten_fuellen':
        return $this->getVarValue('iban');
      case 'mandatam':
        if (isset($this->mandatam)) {
          $mandatamParts = explode(' ', $this->mandatam);
          $result = DateTimeOperations::getValidDateString($mandatamParts[0], true);
          if (DateTimeOperations::isDateTimeDefault($result)) {
            return '';
          }

          return $result;
        }

        return '';
      case 'gebdat_tag_monat':
        $gebdat = $this->gebdat;
        if (\DateTimeOperations::isEmptyOrDefault($gebdat)) {
          return '';
        }

        return implode('.', array_slice(explode('.', $gebdat), 0, 2));
      default: return parent::getVarValue($pName);
    }
  }

  private function fuegeTitelHinzu($name, $nameTitel)
  {
    static $dbwTitel = null;
    if (is_null($dbwTitel)) {
      $dbwTitel = new DBWorkTitel(1, true);
    }

    return $dbwTitel->fuegeTitelHinzu($name, $nameTitel);
  }

  
  public function getKommWerteByParam($pParams, $pDelimiter = ', ')
  {
    $resultAry = array();
    foreach ($pParams as $kommwert) {
      if (isset($this->{$kommwert}) && $this->{$kommwert}->wert != '') {
        $resultAry[] = $this->{$kommwert}->wert;
      }
    }

    return implode($pDelimiter, $resultAry);
  }

  public function getVarValueEx($name, $datamodulname)
  {
    if (StringOperations::strtolower($datamodulname) == 'kommunikation') {
      $ary = get_object_vars($this);

      
      if ($name == 'emailgrafik') {
        
        $aryval = $this->getEmailGrafikValue($ary);
      } elseif ($name == 'email_formular' || $name == 'emailgrafik_formular') {
        
        
        
        
        
        
        $link = 'usertools.php?##TOOLPART##&##TOOLSECTIONPART_EMAILFORM_PERSON##&##IDPART####ADDURLPART##';

        
        if ($name == 'email_formular') {
          $aryval = $this->getEmailFormularValue($ary, $link);
        }
        
        else {
          $aryval = $this->getEmailGrafikFormularValue($ary, $link);
        }
      } 

      else {
        
        
        

        $aryval = '';
        
        if (!empty($ary[$name])) {
          $aryval = $ary[$name]->wert;
        }

        
        if ($name == 'tel_dyn') {
          $arySort = array();
          if (isset($ary['mobil']) && $ary['mobil']->wert) {
            $arySort[$ary['mobil']->sort] = $ary['mobil']->wert;
          }
          if (isset($ary['tel']) && $ary['tel']->wert) {
            $arySort[$ary['tel']->sort] = $ary['tel']->wert;
          }
          if (isset($ary['tel2']) && $ary['tel2']->wert) {
            $arySort[$ary['tel2']->sort] = $ary['tel2']->wert;
          }
          
          if (!empty($arySort)) {
            $aryval = $arySort[min(array_keys($arySort))];
          }
        } 
      } 

      return $aryval ?? '';
    } 

    return parent::getVarValueEx($name, $datamodulname);
  }

  
  private function getEmailGrafikValue($pKommAry)
  {
    

    
    
    $emailGrafikVal = '';
    
    if (EmailOperations::isValidEmail($pKommAry['email']) && trim($pKommAry['email']->wert ?? '') !== '') {
      $mailadress = $pKommAry['email']->wert ?? '';
      $emailGrafikVal = '<a href="mailto:' . CleanOperations::cleanStringForHtml($mailadress) . '" title="Mail an ' . CleanOperations::cleanStringForHtml($mailadress) . ' versenden"><img alt="" src="images/emailgrafik.gif"></a>' . "\n";
    }
    
    elseif (!empty($pKommAry['email']) && !empty($pKommAry['email']->wert)) {
      $emailGrafikVal = '<a class="invalidMailLink" href ="#/" title="Keine gültige E-Mail Adresse">'
                        . '<img class="invalidMail" alt="Keine gültige E-Mail Adresse" src="images/emailgrafik.gif"></a>' . "\n";
    }

    return $emailGrafikVal;
  }

  

  
  private function getEmailFormularValue($pKommAry, $pLink)
  {
    
    
    

    if (SessionOperations::isKuferToolsResponsive()) {
      
      return $this->email_formular;
    }

    
    
    $aryval = '';
    $mailadress = $pKommAry['email']->wert;
    
    if (EmailOperations::isValidEmail($pKommAry['email'])) {
      $aryval = '<a href="' . $pLink . '" class="emailform">' . "\n" . CleanOperations::cleanStringForHtml($mailadress)
                . '</a>' . "\n";
    }
    
    elseif (!empty($pKommAry['email']) && !empty($pKommAry['email']->wert)) {
      $aryval = '<a class="invalidMailLink" href ="#/" title="Keine gültige E-Mail Adresse">' . CleanOperations::cleanStringForHtml($mailadress) . '</a>' . "\n";
    }

    return $aryval;
  }

  

  
  private function getEmailGrafikFormularValue($pKommAry, $pLink)
  {
    
    
    
    if (SessionOperations::isKuferToolsResponsive()) {
      
      return $this->emailgrafik_formular;
    }

    
    
    $aryval = '';
    $mailadress = $pKommAry['email']->wert;
    
    if (EmailOperations::isValidEmail($pKommAry['email'])) {
      $linkContent = '<img class="emailform" alt="" src="images/emailgrafik.gif" title="Mail an ' . CleanOperations::cleanStringForHtml($mailadress) . ' versenden">';
      $aryval = '<a href="' . CleanOperations::cleanStringForHtml($pLink) . '" class="emailform">' . "\n" . $linkContent
                . '</a>' . "\n";
    }
    
    elseif (!empty($pKommAry['email']) && !empty($pKommAry['email']->wert)) {
      $aryval = '<a class="invalidMailLink" href ="#/" title="Keine gültige E-Mail Adresse">'
                       . '<img class="invalidMail" alt="Keine gültige E-Mail Adresse" src="images/emailgrafik.gif"></a>' . "\n";
    }

    return $aryval;
  }

  

  public function setValue2VarEx($var, $val, $datamodulname)
  {
    if (StringOperations::strtolower($datamodulname) == 'kommunikation') {
      $this->setValue2Var($var, $val);
    } else {
      parent::setValue2VarEx($var, $val, $datamodulname);
    }
  }

  
  public function getKommType()
  {
    return ' ';
  }

  public function setValue2Var($var, $val)
  {
    switch ($var) {
      case 'email':
        if ($this->email == null) {
          $this->email = new Kommunikation();
        }
        $this->email->typ = $this->getKommType();
        if ($val instanceof Kommunikation) {
          $val = $val->wert;
        } elseif ($val instanceof EmailXMLKomm) {
          $val = $val->kommwert;
        }
        $this->email->wert = $val;
        $this->email->nr = $this->id;
        if (!isset($this->email->art) || $this->email->art == '') {
          $this->email->art = 'E';
        }
        if (!isset($this->email->bezeichner) || $this->email->bezeichner == '') {
          $this->email->bezeichner = 'EMail';
        }
        break;
      case 'email2':
        if ($this->email2 == null) {
          $this->email2 = new Kommunikation();
        }
        $this->email2->typ = $this->getKommType();
        if ($val instanceof Kommunikation) {
          $val = $val->wert;
        } elseif ($val instanceof EmailXMLKomm) {
          $val = $val->kommwert;
        }
        $this->email2->wert = $val;
        $this->email2->nr = $this->id;
        if (!isset($this->email2->art) || $this->email2->art == '') {
          $this->email2->art = 'E';
        }
        if (!isset($this->email2->bezeichner) || $this->email2->bezeichner == '') {
          $this->email2->bezeichner = 'EMail 2';
        }
        break;
      case 'mobil':
        if ($this->mobil == null) {
          $this->mobil = new Kommunikation();
        }
        $this->mobil->typ = $this->getKommType();
        if ($val instanceof Kommunikation) {
          $val = $val->wert;
        }
        $this->mobil->wert = $val;
        $this->mobil->nr = $this->id;
        if (!isset($this->mobil->art) || $this->mobil->art == '') {
          $this->mobil->art = 'M';
        }
        if (!isset($this->mobil->bezeichner) || $this->mobil->bezeichner == '') {
          $this->mobil->bezeichner = 'Mobilfunktelefon';
        }
        break;
      case 'tel':
        if ($this->tel == null) {
          $this->tel = new Kommunikation();
        }
        $this->tel->typ = $this->getKommType();
        if ($val instanceof Kommunikation) {
          $val = $val->wert;
        }
        $this->tel->wert = $val;
        $this->tel->nr = $this->id;
        if (!isset($this->tel->art) || $this->tel->art == '') {
          $this->tel->art = 'T';
        }
        if (!isset($this->tel->bezeichner) || $this->tel->bezeichner == '') {
          $this->tel->bezeichner = 'Telefon';
        }
        break;
      case 'tel2':
        if ($this->tel2 == null) {
          $this->tel2 = new Kommunikation();
        }
        $this->tel2->typ = $this->getKommType();
        if ($val instanceof Kommunikation) {
          $val = $val->wert;
        }
        $this->tel2->wert = $val;
        $this->tel2->nr = $this->id;
        if (!isset($this->tel2->art) || $this->tel2->art == '') {
          $this->tel2->art = 'T';
        }
        if (!isset($this->tel2->bezeichner) || $this->tel2->bezeichner == '') {
          $this->tel2->bezeichner = 'Telefon 2';
        }
        break;
      case 'fax':
        if ($this->fax == null) {
          $this->fax = new Kommunikation();
        }
        $this->fax->typ = $this->getKommType();
        if ($val instanceof Kommunikation) {
          $val = $val->wert;
        }
        $this->fax->wert = $val;
        $this->fax->nr = $this->id;
        if (!isset($this->fax->art) || $this->fax->art == '') {
          $this->fax->art = 'F';
        }
        if (!isset($this->fax->bezeichner) || $this->fax->bezeichner == '') {
          $this->fax->bezeichner = 'Fax';
        }
        break;
      case 'fax2':
        if ($this->fax2 == null) {
          $this->fax2 = new Kommunikation();
        }
        $this->fax2->typ = $this->getKommType();
        if ($val instanceof Kommunikation) {
          $val = $val->wert;
        }
        $this->fax2->wert = $val;
        $this->fax2->nr = $this->id;
        if (!isset($this->fax2->art) || $this->fax2->art == '') {
          $this->fax2->art = 'F';
        }
        if (!isset($this->fax2->bezeichner) || $this->fax2->bezeichner == '') {
          $this->fax2->bezeichner = 'Fax 2';
        }
        break;
      case 'nurplz':
        $plz = $val;
        $ort = $this->getVarValue('nurort');
        $this->ort = \Kufer\Web\Classes\Addfunctions\PlzOperations::getOrtStrFromPlzOrt($this->nation, $plz, $ort);
        break;
      case 'nurort':
        $plz = $this->getVarValue('nurplz');
        $ort = $val;
        $this->ort = \Kufer\Web\Classes\Addfunctions\PlzOperations::getOrtStrFromPlzOrt($this->nation, $plz, $ort);
        break;
      case 'nurstrasse':
        $strasse = $val;
        $hausnr = $this->getVarValue('nurhausnr');
        $this->strasse = trim($strasse . ' ' . $hausnr);
        break;
      case 'nurhausnr':
        $strasse = $this->getVarValue('nurstrasse');
        $hausnr = $val;
        $this->strasse = trim($strasse . ' ' . $hausnr);
        break;
      case 'iban_button_bankdaten_fuellen':
        $this->setValue2Var('iban', $val);
        break;
      case 'bankbezAnhandIban':
      case 'bankbezLangAnhandIban':
        $this->bankbez = $val;
        break;
      default: parent::setValue2Var($var, $val);
    }
  }

  public function getTyp($pFieldName)
  {
    switch ($pFieldName) {
      default:
        return parent::getTyp($pFieldName);
      case 'gebdat':
      case 'bearbdatum':
        return \DatamodulVarType::TYPE_DATE;
      case 'mandatam':
        return \DatamodulVarType::TYPE_DATETIME;
      case 'nr':
        return \DatamodulVarType::TYPE_INT;
      case 'guid':
        return \DatamodulVarType::TYPE_GUID;
    }
  }

  
  public function getKommAnzeigeAry($pOrigDm)
  {
    $kommDataAry = array('tel', 'tel2', 'mobil', 'email', 'email2', 'fax', 'fax2');
    $kommAnzeigeAry = array();
    
    foreach ($kommDataAry as $kommDat) {
      if (empty($pOrigDm) || $this->{$kommDat}->wert !== $pOrigDm->{$kommDat}->wert) {
        $kommAnzeigeAry[] = $kommDat . '_anzeige';
      }
    }

    
    if (in_array('tel_anzeige', $kommAnzeigeAry) && trim($this->tel->wert) == '' && !in_array('tel2_anzeige', $kommAnzeigeAry)) {
      $kommAnzeigeAry[] = 'tel2_anzeige';
    }
    if (in_array('fax_anzeige', $kommAnzeigeAry) && trim($this->fax->wert) == '' && !in_array('fax2_anzeige', $kommAnzeigeAry)) {
      $kommAnzeigeAry[] = 'fax2_anzeige';
    }
    if (in_array('email_anzeige', $kommAnzeigeAry) && trim($this->email->wert) == '' && !in_array('email2_anzeige', $kommAnzeigeAry)) {
      $kommAnzeigeAry[] = 'email2_anzeige';
    }

    return $kommAnzeigeAry;
  }

  

  
  public function updateKommAnzeige()
  {
    $this->tel_anzeige = isset($this->tel) ? $this->tel->wert : '';
    $this->tel2_anzeige = isset($this->tel2) ? $this->tel2->wert : '';
    $this->fax_anzeige = isset($this->fax) ? $this->fax->wert : '';
    $this->fax2_anzeige = isset($this->fax2) ? $this->fax2->wert : '';
    $this->mobil_anzeige = isset($this->mobil) ? $this->mobil->wert : '';
    $this->email_anzeige = isset($this->email) ? $this->email->wert : '';
    $this->email2_anzeige = isset($this->email2) ? $this->email2->wert : '';

    if (trim($this->tel_anzeige ?? '') == '' && trim($this->tel2_anzeige ?? '') != '') {
      $this->tel_anzeige = $this->tel2_anzeige;
      $this->tel2_anzeige = ''; 
    }

    if (trim($this->fax_anzeige ?? '') == '' && trim($this->fax2_anzeige ?? '') != '') {
      $this->fax_anzeige = $this->fax2_anzeige;
      $this->fax2_anzeige = ''; 
    }

    if (trim($this->email_anzeige ?? '') == '' && trim($this->email2_anzeige ?? '') != '') {
      $this->email_anzeige = $this->email2_anzeige;
      $this->email2_anzeige = ''; 
    }
  }

  

  
  protected function getAnsprache()
  {
    if (isset($this->ansprache) && trim($this->ansprache) != '') {
      $ansprache = $this->ansprache . ',';
    } elseif ($this instanceof BASysBenutzer && isset($this->anrede) && trim($this->anrede) != '') {
      $ansprache = $this->anrede;
    } else {
      $titel = trim($this->getVarValue('name_titel')) != '' ? trim($this->getVarValue('name_titel')) . ' ' : '';
      if ($this->geschlecht == 'W') {
        $ansprache = 'Sehr geehrte Frau ' . $titel . $this->getVarValue('name') . ',';
      } elseif ($this->geschlecht == 'M') {
        $ansprache = 'Sehr geehrter Herr ' . $titel . $this->getVarValue('name') . ',';
      } elseif ($this->geschlecht == 'F') {
        $ansprache = 'Sehr geehrte Mitarbeiter der Firma ' . $this->getVarValue('name') . ',';
      } elseif ($this->geschlecht == 'B') {
        $ansprache = 'Sehr geehrter Bruder ' . $this->getVarValue('name') . ',';
      } elseif ($this->geschlecht == 'S') {
        $ansprache = 'Sehr geehrte Schwester ' . $this->getVarValue('name') . ',';
      } else {
        $ansprache = 'Sehr geehrte Damen und Herren,';
      }
    }

    return $ansprache;
  }

  
  public function getVarName4EmailSenderSetting(string $pEmpfaenger): string
  {
    return '';
  }

  
  protected function _referenzVariablen()
  {
    return array(
        'email',
        'email2',
        'fax',
        'fax2',
        'tel',
        'tel2',
        'mobil');
  }

  
  private function getBankbezAnhandIban()
  {
    $bankDaten = $this->ermittleBankbez();

    return $bankDaten['bankNameKurz'];
  }

  
  private function getBankbezLangAnhandIban()
  {
    $bankDaten = $this->ermittleBankbez();

    return $bankDaten['bankNameLang'];
  }

  
  private function ermittleBankbez()
  {
    $iban = $this->getVarValue('iban');

    if ($iban !== '' && BankDatenOperations::isIbanDeutsch($iban)) {
      $blz = BankDatenOperations::getBlzFromIban($iban);
      $data = KtoPruef::getBank4Blz($blz);
      if ($data === false) {
        $bankNameKurz = StringOperations::substr($this->bankbez, 0, 30);
        $bankNameLang = StringOperations::substr($this->bankbez, 0, 30);
      } else {
        $bankNameKurz = $data['ezucode'];
        $bankNameLang = $data['bez_lang'];
      }
    } else {
      $bankNameKurz = StringOperations::substr($this->bankbez, 0, 30);
      $bankNameLang = StringOperations::substr($this->bankbez, 0, 30);
    }

    return array('bankNameKurz' => $bankNameKurz, 'bankNameLang' => $bankNameLang);
  }

  
  

  
  protected function getDsgvoStatus($pOnlyText = false)
  {
    $text = 'Achtung: Es liegt noch keine Datenschutzerklärung vor.';
    $classIcon = 'fa fa-question-circle-o dsgvo_status_symbol_fragezeichen';
    if (!DateTimeOperations::isDateTimeEmptyOrDefault($this->dse_unterschrieben_datum)
      || !DateTimeOperations::isDateTimeEmptyOrDefault($this->dse_widerrufen_datum)) {
      $text = 'Die Datenschutzerklärung wurde am ' . $this->dse_widerrufen_datum . ' widerrufen.';
      $classIcon = 'fa fa-close dsgvo_status_symbol_widerrufen';
      if (DateTimeOperations::isDateTimeAfter($this->dse_unterschrieben_datum, $this->dse_widerrufen_datum, 'earlier')) {
        $text = 'Die Datenschutzerklärung wurde am ' . $this->dse_unterschrieben_datum . ' Uhr erteilt.';
        $classIcon = 'fa fa-check dsgvo_status_symbol_zugestimmt';
      }
    }

    $result = $text;
    if (!$pOnlyText) {
      $result = '<div class="dsgvo_status_symbol_div"><i class="' . $classIcon . '" title="' . $text . '"></i></div>';
    }

    return $result;
  }

  
  protected function getDsgvoStatusOnlyText()
  {
    return $this->getDsgvoStatus(true);
  }

  public function getIdentifier(): Identifier
  {
    return new Identifier($this->id, $this->guid);
  }

  
  public function getZustimmungen(bool $reloadCache = false): array
  {
    if (is_null($this->zustimmungen) || $reloadCache) {
      if (is_null($this->id) || $this->id === '') {
        return array();
      }

      $dbwZustimmungAd = \DBWorkZustimmungAd::getDefaultInstance();
      $filter = \Kufer\Web\Classes\Dbfilter\ZustimmungAdSQLFilter::create();
      $filter->equalsAnzTyp($this->getDbTyp());
      $filter->equalsAnzId($this->id);
      $this->zustimmungen = $dbwZustimmungAd->findByFilter($filter);
    }

    return $this->zustimmungen;
  }
}