<?php #pgs/xx_termine/class.php

class AnwesenheitenPage extends BasePage
{
  private $monthsback = 1;
  
  protected function update($id) {
    $this->man->AddMessage($id);
    $this->get($id);
    $qry = "UPDATE Anwesenheiten SET Bezeichnung = ? WHERE ID = ?";
    if ($stmt = $this->db->prepare($qry)) {
      $Bezeichnung = $this->man->input["BEZEICHNUNG"] ?? $this->output["MAIN"]["BEZEICHNUNG"];
      $stmt->bind_param(
        "si",
        $Bezeichnung,
        $id
      );
      if ($stmt->execute()) {
        $this->man->AddMessage("Anwesenheitsliste wurde aktualisiert!");
        $this->get($id);
        return 200;
      } else {
        $this->man->AddMessage("Mysql error: ".$this->db->error);
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
    }
    return 500;
  }
  
  protected function insert() {
    $qry = "INSERT INTO Anwesenheiten (Bezeichnung) VALUES (?)";
    if ($stmt = $this->db->prepare($qry)) {
      $Bezeichnung = $this->man->input["BEZEICHNUNG"] ?? "";
      $stmt->bind_param("s", $Bezeichnung);
      $stmt->execute();
      if ($stmt->affected_rows==1) {
        $this->man->AddMessage("Anwesenheitsliste wurde hinzugefügt!");
        $this->get($this->db->insert_id);
        return 201;
      } else {
        $this->man->AddMessage("Anwesenheitsliste konnte nicht hinzugefügt werden! (".$Bezeichnung.")"
        );
        return 400;
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
      return 500;
    }
  }
    
  protected function get($id = null) {
  	$this->output = [];
    $where = "";
    if ($id) {
      $where = "WHERE a.ID = ? ";
    } else if (sizeof($this->man->Filter())>0) {
      $where = "WHERE 1 ";
      foreach ($this->man->Filter() as $filter) {
        $where.= "or"==$filter["and"] ? "OR " : "AND ";
        if ("none"==$filter["field"]) {
          $where.= "1 ";
        } else {
          switch ($filter["field"]) {
            /*case "BEGINN":
              $where.= $this->getFilterString($filter["op"], ["<=", ">="], "t", "Beginn", $filter["value"]);
              break;
            case "ENDE":
              $where.= $this->getFilterString($filter["op"], ["<=", ">="], "t", "Ende", $filter["value"]);
              break;
            case "THEMA":
              $where.= $this->getFilterString($filter["op"], ["like", "not like"], "t", "Thema", $filter["value"]);
              break;
            case "DIENSTPLAN":
              $where.= $this->getFilterString($filter["op"], ["=", "<>"], "t", "Dienstplan", $filter["value"]);
              break;
            case "KATEGORIE":
              $where.= $this->getFilterString($filter["op"], ["=", "<>"], "t", "Kategorie", $filter["value"]);
              break;
            case "GRUPPE":
              $where.= $this->getFilterString($filter["op"], ["=", "<>"], "t", "Gruppe", $filter["value"]);
              break;*/
            default:
              $where.= "1 ";
      } } }
    } else {
      $where = "WHERE 1 ";
    }
    
    $qry = "SELECT a.*, "
          ."CONCAT(',', GROUP_CONCAT(DISTINCT at.Termine SEPARATOR ','), ',') Termine, "
          ."CONCAT(',', GROUP_CONCAT(DISTINCT ae.Einsätze SEPARATOR ','), ',') Einsätze, "
          ."CONCAT(',', GROUP_CONCAT(DISTINCT ap.Personal SEPARATOR ','), ',') Personal "
          ."FROM Anwesenheiten a "
          ."LEFT JOIN Anwesenheiten_Termine at ON a.ID=at.Anwesenheiten "
          ."LEFT JOIN Anwesenheiten_Einsätze ae ON a.ID=ae.Anwesenheiten "
          ."LEFT JOIN Anwesenheiten_Personal ap ON a.ID=ap.Anwesenheiten "
          .$where
          ."GROUP BY a.ID ";
    if ($stmt = $this->db->prepare($qry)) {
      $userID = $this->man->user->ID();
      if ($id) {
        $stmt->bind_param("i", $id);
      } else {
      	
      }
      $stmt->execute();
      $res = $stmt->get_result();
      while ($row = $res->fetch_assoc()) {
				$entry = [
          "ID" => strval($row["ID"]),
          "MAIN" => [
            "BEZEICHNUNG" => $row["Bezeichnung"]
          ],
          "SUB" => [
            "TERMINE" => $this->getSub("TERMINE", $row["Termine"]),
            "EINSÄTZE" => $this->getSub("EINSÄTZE", $row["Einsätze"]),
            "PERSONAL" => $this->getSub("PERSONAL", $row["Personal"])
          ],
        ];
        $this->addEntryToOutput("DEFAULT", $entry, $id);
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
    }
    
    return 200;
  }
  
  protected function fillOptions($admin = false) {
    $ret = array();
    $res = $this->db->query("SELECT ID, Beginn, Thema "
                           ."FROM Termine "
                           ."ORDER BY Beginn DESC");
    while ($row = $res->fetch_assoc()) {
      $ret["TERMINE"][] = ["ID" => $row["ID"], "BEGINN" => $row["Beginn"], "THEMA" => $row["Thema"]];
    }
    $res = $this->db->query("SELECT e.ID, e.Alarmierungszeit, e.Adresse, ea.Name aName "
                           ."FROM Einsätze e "
                           ."LEFT JOIN Einsätze_Arten ea ON ea.ID=e.Art "
                           ."ORDER BY Alarmierungszeit DESC");
    while ($row = $res->fetch_assoc()) {
      $ret["EINSÄTZE"][] = [
      	"ID" => $row["ID"], 
      	"ALARMIERUNGSZEIT" => $row["Alarmierungszeit"], 
      	"ADRESSE" => $row["Adresse"],
      	"ART" => $row["aName"]
      ];
    }
    $res = $this->db->query("SELECT p.ID, Nachnamen, Vornamen, pk.Name pkName FROM Personal p LEFT JOIN Personal_Kategorien pk ON pk.ID=p.Kategorie "
                             ."ORDER BY pk.Reihenfolge ASC, Nachnamen ASC, Vornamen ASC");
    $lastKategorie = "";
    while ($row = $res->fetch_assoc()) {
      if ($row["pkName"]!=$lastKategorie) {
        $ret["PERSONAL"][] = ["ID" => 0, "NAME" => " === ".$row["pkName"]." === "];
        $lastKategorie = $row["pkName"];
      }
      $ret["PERSONAL"][] = ["ID" => $row["ID"], "NAME" => preg_replace("/(?<![ -])\p{Ll}+/u", ".", $row["Vornamen"])." ".$row["Nachnamen"]];
    }
    $res = $this->db->query("SELECT ID, Name, Kürzel FROM Fahrzeuge");
    $ret["FAHRZEUGE"][] = ["ID" => null, "NAME" => "Keins", "KÜRZEL" => "-"];
    while ($row = $res->fetch_assoc()) {
      $ret["FAHRZEUGE"][] = [
      	"ID" => $row["ID"], 
      	"NAME" => $row["Name"], 
      	"KÜRZEL" => $row["Kürzel"]
      ];
    }
    return $ret;
  }
  
}
