<?php #lnk/xx_dateien/class.php

class DateienLink extends BaseLink
{
  public function __construct($database, $keyvaluestore, $manager, $info, $page) {
    parent::__construct($database, $keyvaluestore, $manager, $info, $page);
  }
  
  protected function insert($ids) {
    if (isset($_FILES["file"])) {
      $source = $_FILES ["file"]["tmp_name"];
      $dest_dir = "upl/";
      $keys = [];
      $vals = [];
      // ids should be [%TABLENAME => %ENTRYID, %FIELDNAME => NULL]
      foreach ($ids as $path => $id) {
        $dest_dir.= $path."/";
        $keys[] = $path;
        $vals[] = $id;
      }
      if (!file_exists($dest_dir)) {
        mkdir($dest_dir, 0770, true);
      }
      
      $mime = mime_content_type($source);
      switch ($mime) {
        case "image/gif": $filename = $vals[0].".gif"; break;
        case "image/jpeg": $filename = $vals[0].".jpg"; break;
        case "image/png": $filename = $vals[0].".png"; break;
        case "image/svg": $filename = $vals[0].".svg"; break;
        default: $this->man->AddMessage("Unbekannter Dateityp"); return 400;
      }
      
      // Delete existing files
      foreach (glob($dest_dir.$vals[0].".*") as $existingfile) {
        unlink($existingfile);
      }
      if (move_uploaded_file($source, $dest_dir.$filename)) {
        if ($stmt = $this->db->prepare("UPDATE `".$keys[0]."` SET `".$keys[1]."` = ? WHERE ID = ?")) {
          $stmt->bind_param("si", $filename, $vals[0]);
          if ($stmt->execute()) {
            return 201;
          }
        } else {
          $this->man->AddMessage("Mysql error: ".$this->db->error);
        }
      } else {
        $this->man->AddMessage("File could not be moved");
        return 403;
      }
    } 
    return 400;
  }
  
  protected function remove($ids) {
    $dest_dir = "upl/";
    $keys = [];
    $vals = [];
    // ids should be [%TABLENAME => %ENTRYID, %FIELDNAME => NULL]
    foreach ($ids as $path => $id) {
      $dest_dir.= $path."/";
      $keys[] = $path;
      $vals[] = $id;
    }

    // Delete existing files
    $files = glob($dest_dir.$vals[0].".*");
    if (empty($files)) {
      $this->man->AddMessage("No files were found!");
    }
    foreach ($files as $existingfile) {
      unlink($existingfile);
    }
    
    if ($stmt = $this->db->prepare("UPDATE `".$keys[0]."` SET `".$keys[1]."` = NULL WHERE ID = ?")) {
      $stmt->bind_param("i", $vals[0]);
      if ($stmt->execute()) {
        $this->man->AddMessage("Datei erfolgreich gelöscht!");
        return 200;
      } else {
        $this->man->AddMessage("Mysql error: ".$this->db->error);
      }
    } else {
      $this->man->AddMessage("Mysql error: ".$this->db->error);
    }
    return 500; // Should not reach this stage
  }
}
