<?php #pgs/xx_fahrzeuge/class.php

class FahrzeugePage extends BasePage
{
	private $prefixImage = "upl/Fahrzeuge/Bild/";
  
  protected function update($id) {
    $this->get($id);
    
    $qry = "UPDATE Fahrzeuge SET Kürzel = ?, Name = ? WHERE ID = ?";
    if ($stmt = $this->db->prepare($qry)) {
      $name = array_key_exists("NAME", $this->man->input) ? $this->man->input["NAME"] : $this->output["MAIN"]["NAME"];
      $kürzel = array_key_exists("KÜRZEL", $this->man->input) ? $this->man->input["KÜRZEL"] : $this->output["MAIN"]["KÜRZEL"];
      $stmt->bind_param(
        "ssi",
        $kürzel,
        $name,
        $id
      );
      if ($stmt->execute()) {
        $this->man->AddMessage("Fahrzeug 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() {
  	$res = $this->db->query("SELECT UUID_SHORT() uuid");
  	$uuid = $res->fetch_assoc()["uuid"];
  	
    $qry = "INSERT INTO Fahrzeuge (ID, Kürzel, Name) VALUES (?,?,?)";
    if ($stmt = $this->db->prepare($qry)) {
      $Kürzel = $this->man->input["KÜRZEL"] ?? "";
      $Name = $this->man->input["NAME"] ?? "";
      $stmt->bind_param(
        "sss",
        $uuid,
        $Kürzel,
        $Name
      );
      $stmt->execute();
      if ($stmt->affected_rows==1) {
        $this->man->AddMessage("Fahrzeug wurde hinzugefügt!");
        $this->get($uuid);
        return 201;
      } else {
        $this->man->AddMessage("Fahrzeug konnte nicht hinzugefügt werden! (".$Kürzel." / ".$Name.")");
        return 400;
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
      return 500;
    }
  }
  
  protected function get($id = null) {
  	$this->output = [];
    $where = "";
    $having = "";
    if ($id) {
      $where = "AND f.ID = ? ";
    } else if (sizeof($this->man->Filter())>0) {
      /*$where = "WHERE 1 ";*/
      foreach ($this->man->Filter() as $filter) {
        $and = "or"==$filter["and"] ? "OR " : "AND ";
        if ("none"==$filter["field"]) {
          $where.= $and."1 ";
        } else {
          switch ($filter["field"]) {
/*            case "RAUM":
              $where.= $and.$this->getFilterString($filter["op"], ["=", "<>"], "s", "Raum", $filter["value"]);
              break;
            case "BESITZER":
              $where.= $and.$this->getFilterString($filter["op"], ["=", "<>"], "s", "Besitzer", $filter["value"]);
              break;*/
            default:
              $where.= $and."1 ";
    } } } }
    
    $qry = "SELECT f.*, CONCAT(',', GROUP_CONCAT(DISTINCT fe.Personal SEPARATOR ','), ',') Eingewiesene FROM Fahrzeuge f "
    			."LEFT JOIN Fahrzeuge_Einweisungen fe ON fe.Fahrzeuge=f.ID "
          ."LEFT JOIN Personal p ON p.ID=fe.Personal "
          ."WHERE 1 ".$where
          ."GROUP BY f.ID ";
//          ."ORDER BY s.Raum ASC ";
    if ($stmt = $this->db->prepare($qry)) {
      if ($id) {
        $stmt->bind_param("s", $id);
      }
      $stmt->execute();
      $res = $stmt->get_result();
      while ($row = $res->fetch_assoc()) {
        $entry = [
          "ID" => strval($row["ID"]),
          "GROUP" => "Fahrzeuge",
          "MAIN" => [
            "KÜRZEL" => $row["Kürzel"],
            "NAME" => $row["Name"],
            "BILD" => [
              "EXISTIERT" => file_exists($this->prefixImage.$row["Bild"]) && null!==$row["Bild"],
              "ADRESSE" => $row["Bild"],
              "PFAD" => "/".$this->prefixImage,
            ],
          ],
          "SUB" => [
          	"EINGEWIESENE" => $this->getSub("EINGEWIESENE", $row["Eingewiesene"]),
          ],
        ];
        $this->addEntryToOutput("Fahrzeuge", $entry, $id);
      }
      if ($id && $res->num_rows==0) {
        $this->man->AddMessage("Couldn't find requested resource!");
        return 404;
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error." / Qry: ".$qry);
      return 500;
    }
    return 200;
  }
  
  protected function fillOptions($admin = false) {
    $ret = array();
    $res = $this->db->query("SELECT ID, OFnr, Pnr, Vornamen, Nachnamen FROM Personal ORDER BY Nachnamen ASC, Vornamen ASC");
    while ($row = $res->fetch_assoc()) {
      $ret["EINGEWIESENE"][] = ["ID" => $row["ID"], "NAME" => preg_replace("/(?<![ -])\p{Ll}+/u", ".", $row["Vornamen"])." ".$row["Nachnamen"]." (".$row["OFnr"]."-".$row["Pnr"].")"];
    }
    return $ret;
  }
}
