<?php #lnk/xx_termine_teilnahmen/class.php

class Termine_TeilnahmenLink extends BaseLink
{
  private $isAdmin = null;
  
  public function __construct($database, $keyvaluestore, $manager, $info, $page) {
    parent::__construct($database, $keyvaluestore, $manager, $info, $page);
  }
  
  protected function insert($ids) {
    $foreign = false;
    $status = $this->man->input["Status"] ?? 0;
    if ($ids["Personal"]!=null) {
      if (!$this->isAdmin($ids)) {
        return 403; // You shall not pass!
      }
      $foreign = true;
    } else {
      $ids["Personal"] = $this->man->user->ID();
    }
    
    $possibleStats = $this->canJoin($ids);
    if (empty($possibleStats)) {
      return 403; // You shall not pass!
    } else if (!in_array($status, $possibleStats)) {
      $status = $possibleStats[0];
    }

    $qry = "INSERT INTO Termine_Teilnahmen (Termine, Personal, Status) VALUES (?, ?, ?)";
    if ($stmt = $this->db->prepare($qry)) {
      $stmt->bind_param("iii", $ids["Termine"], $ids["Personal"], $status);
      $stmt->execute();
      if (1==$stmt->affected_rows) {
        if ($foreign) {
          $this->man->AddMessage("Teilnehmer hinzugefügt!");
        } else {
          $this->man->AddMessage("Anmeldung erfolgreich!");
        }
        return 201;
      } else {
        return 200;
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
    }
    return 500; // Should not reach this stage
  }
  
  protected function update($ids) {
    $foreign = false;
    $status = $this->man->input["Status"] ?? 1;
    
    if ($ids["Personal"]!=null) {
      if (!$this->isAdmin($ids)) {
        return 403; // You shall not pass!
      }
      $foreign = true;
    } else {
      $ids["Personal"] = $this->man->user->ID();
      $status = 1;  // Only possible way to patch for a non-privileged action is from 0 to 1
    }
    
    $possibleStats = $this->canJoin($ids);
    if (empty($possibleStats)) {
      return 403; // You shall not pass!
    } else if (!in_array($status, $possibleStats)) {
      $status = $possibleStats[0];
    }

    $qry = "UPDATE Termine_Teilnahmen SET Status = ? WHERE Termine = ? AND Personal = ?";
    if (isset($this->man->input["Status"]) && $stmt = $this->db->prepare($qry)) {
      $stmt->bind_param("iii", $status, $ids["Termine"], $ids["Personal"]);
      $stmt->execute();
      if (1==$stmt->affected_rows) {
        if ($foreign) {
          $this->man->AddMessage("Teilnahmestatus geändert!");
          
        } else {
          $this->man->AddMessage("Mitmachen erfolgreich!");
        }
        return 200;
      } else {
        return 404;
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
    }
    return 500;
  }
  
  protected function remove($ids) {
    $foreign = false;
    if ($ids["Personal"]!=null) {
      if (!$this->isAdmin($ids)) {
        return 403; // You shall not pass!
      }
      $foreign = true;
    } else {
      $ids["Personal"] = $this->man->user->ID();
    }
    $possibleStats = $this->canJoin($ids);
    if (empty($possibleStats) || !in_array(null, $possibleStats)) {
      $this->man->AddMessage("Verlassen des Dienstes nicht möglich");
      return 403;
    }
    
    $qry = "DELETE FROM Termine_Teilnahmen WHERE Termine = ? AND Personal = ?";
    if ($stmt = $this->db->prepare($qry)) {
      $stmt->bind_param("ii", $ids["Termine"], $ids["Personal"]);
      $stmt->execute();
      if (1==$stmt->affected_rows) {
        if ($foreign) {
          $this->man->AddMessage("Teilnehmer entfernt!");
        } else {
          $this->man->AddMessage("Abmeldung erfolgreich!");
        }
        return 200;
      } else {
        return 404;
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
    }
    return 500;
  }
  
  private function isAdmin($ids) {
    if ($this->isAdmin===null) {
      $qry = "SELECT r.Name rName, tt.Status FROM Termine t "
            ."LEFT JOIN Termine_Kategorien tk ON tk.ID = t.Kategorie "
            ."LEFT JOIN Rechte r ON tk.Recht = r.ID "
            ."LEFT JOIN Termine_Teilnahmen tt ON tt.Termine=t.ID AND tt.Personal = ? "
            ."WHERE t.ID = ?";
      if ($stmt = $this->db->prepare($qry)) {
        $stmt->bind_param("ii", $ids["Personal"], $ids["Termine"]);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        // Mögliche Rechte zum Bearbeiten
        $possiblePrivileges = array($this->adminRight);
        if (null!==$row["rName"]) {
          $possiblePrivileges[] = $row["rName"];
        }
        $this->isAdmin = $this->man->user->HasRight($possiblePrivileges) || "2"==$row["Status"];
    } }
    return $this->isAdmin;
  }
  
  private function canJoin($ids) {
    if ($this->isAdmin($ids)) {
      return [0, 1, 2, null]; // This user is privileged enough to do what he wants in this appointment
    }
    
    $ret = [];
    $qry = "SELECT t.Ausgelost, IF(t.Beginn<NOW(), 1, 0) vorbei, tp.MaxTeilnehmer, td.Abteilung, t.Gruppe, tt.Status "
          .", (SELECT COUNT(*) FROM Termine_Teilnahmen tt2 WHERE tt2.Termine=t.ID AND tt2.Status>=1) num "
          .", (SELECT COUNT(*) FROM Termine_Teilnahmen tt3 LEFT JOIN Termine t2 ON t2.ID=tt3.Termine "
          ."   WHERE tt3.Personal=? AND t2.ID!=t.ID AND t2.Kategorie=t.Kategorie "
          ."   AND (t2.Beginn BETWEEN t.Beginn AND t.Beginn + INTERVAL 7 DAY OR "
          ."       ((tt3.Status>0 OR t2.Ausgelost=0) AND t2.Beginn BETWEEN t.Beginn - INTERVAL 7 DAY AND t.Beginn))) naheDienste "
          ."FROM Termine t "
          ."LEFT JOIN Termine_Dienstpläne td ON td.ID=t.Dienstplan "
          ."LEFT JOIN Termine_Platzvergaben tp ON tp.ID=t.Platzvergabe "
//          ."LEFT JOIN Termine_Kategorien tk ON tk.ID = t.Kategorie "
//          ."LEFT JOIN Rechte r ON tk.Recht = r.ID "
          ."LEFT JOIN Termine_Teilnahmen tt ON tt.Termine=t.ID AND tt.Personal = ? "
          ."WHERE t.ID = ?";
    if ($stmt = $this->db->prepare($qry)) {
      $stmt->bind_param("iii", $ids["Personal"], $ids["Personal"], $ids["Termine"]);
      $stmt->execute();
      $row = $stmt->get_result()->fetch_assoc();
      $stmt->close();
      
      if ("0"==$row["vorbei"]) {
        if ($this->man->user->InAbteilung($row["Abteilung"]) 
        && $this->man->user->InGruppe($row["Gruppe"])
        /*&& intVal($row["naheDienste"])==0*/) {  // Die 7-Tage Sperrfrist ist zur Zeit aufgehoben
        // The appointment is not over yet and the user is allowed to join
          if ("0"==$row["MaxTeilnehmer"]) {
            // There is no restriction 
            $ret = [1];
          } else if ($row["Ausgelost"]=="1" && intVal($row["num"])<intVal($row["MaxTeilnehmer"])) {
            $ret = [1];
          } else {
            $ret = [0];
          }
          if (null!==$row["Status"]) {
            $ret[] = null;
      } } }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
    }
    return $ret;
  }
}
