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

namespace Kufer\Web\Classes\db\searchobject;

class BelegungToObjectStatusByDate
{
  
  public $status;

  
  public $date;

  
  public $restrictByAustritt;

  
  public $restrictByKuendingung;

  public function __construct(
    array $status,
    ?string $date,
    bool $restrictByAustritt,
    bool $restrictByKuendingung
  ) {
    $this->status = $status;
    $this->date = $date;
    $this->restrictByAustritt = $restrictByAustritt;
    $this->restrictByKuendingung = $restrictByKuendingung;
  }

  public function isBelegungAllowed(\Belegung $belegung, ?string $date): bool
  {
    $dateRestrict = $date ?? $this->date;
    $status = \ConstantOperations::mapBelegungStatusToRealStatus($this->status);
    if (!$this->hasDateRestriction() || \DateTimeOperations::isEmptyOrDefault($dateRestrict)) {
      return !in_array($belegung->status, $status, true);
    }

    if (in_array($belegung->status, $status, true)) {
      $dates = array();
      if ($this->restrictByAustritt && !\DateTimeOperations::isEmptyOrDefault($belegung->austritt)) {
        $dates[] = $belegung->austritt;
      }
      if ($this->restrictByKuendingung && !\DateTimeOperations::isEmptyOrDefault($belegung->gekuendigt_zum)) {
        $dates[] = $belegung->gekuendigt_zum;
      }

      foreach ($dates as $date) {
        if (\DateTimeOperations::isDateBefore($date, $dateRestrict)) {
          return false;
        }
      }
    }

    return true;
  }

  public function hasDateRestriction(): bool
  {
    return count(array_filter(array(
      $this->restrictByAustritt, $this->restrictByKuendingung
    ))) !== 0;
  }

  public static function createFromSettings(\ToolAdministrationSettings $toolSettings, ?string $date): ?self
  {
    if ($toolSettings->ktRestrictTeilnehmerStatus === '') {
      return null;
    }

    return new BelegungToObjectStatusByDate(
      \StringOperations::str_split($toolSettings->ktRestrictTeilnehmerStatus),
      $date,
      $toolSettings->ktRestrictTeilnehmerByAustritt,
      $toolSettings->ktRestrictTeilnehmerByKuendingung
    );
  }
}