<?php
require "../.php/format.inc";
require "../.php/auth.inc";

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    authenticate();

    $name = substr($_SERVER['PATH_INFO'], 1);
    if (str_contains($name, "..") || str_contains($name, "/")) {
        header('Status: 403');
        header('Content-Type: text/plain');
        header('Content-Length: 17');
        exit("403 Forbidden :(\n");
    }

    $upload = fopen("php://input", "r");
    $fp = fopen($name, "wb+");
    while ($data = fread($upload, 4096)) fwrite($fp, $data);
    fclose($fp);
    fclose($upload);

    header('Status: 200');
    header('Content-Type: text/plain');
    header('Content-Length: 10');
    exit("200 OK :)\n");
} else if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'HEAD') {
    header('Status: 405');
    header('Allow: GET, HEAD, PUT');
    header('Content-Type: text/plain');
    header('Content-Length: 26');
    exit("405 Method Not Allowed :(\n");
}

global $getProd;
global $getVers;
$getProd = null;
$getVers = null;
$info = explode('/', $_SERVER['PATH_INFO']);
if (sizeof($info) > 1 && ($info[1] === 'elwig' || $info[1] === 'winziprint')) {
    $getProd = $info[1];
    $getVers = $info[2];
    if (sizeof($info) > 3) {
        header('Status: 404');
        header('Content-Length: 0');
        exit();
    }
} else if ($_SERVER['PATH_INFO'] !== '') {
    header('Status: 404');
    header('Content-Length: 0');
    exit();
}

$files = [];
foreach (scandir('.') as $file) {
    if (str_starts_with($file, ".") || str_ends_with($file, ".php")) continue;
    $files[$file] = [filesize($file), filemtime($file), filectime($file)];
}

$entities = [];
foreach ($files as $name => [$size, $mtime, $ctime]) {
    $p1 = strrpos($name, '-') + 1;
    $p2 = strrpos($name, '.');
    $vers = substr($name, $p1, $p2 - $p1);
    $url = "https://elwig.at/files/$name";
    $mod = date(DATE_ATOM, $mtime);
    $cre = date(DATE_ATOM, $ctime);
    $prod = strtolower(substr($name, 0, $p1 - 1));
    $entities[$name] = [
        $prod,
        $vers,
        $url,
        $size,
        $mtime,
        $ctime,
        $mod,
        $cre
    ];
}

if ($getVers === 'latest') {
    $versions = [];
    foreach ($entities as $name => [$prod, $vers, $url, $size, $mtime, $ctime, $mod, $cre]) {
        if ($prod === $getProd) $versions[] = $vers;
    }
    usort($versions, 'version_compare');
    $getVers = $versions[sizeof($versions) - 1];
}

$entities = array_filter($entities, function($e) {
    global $getProd;
    global $getVers;
    return (empty($getProd) || $getProd === $e[0]) && (empty($getVers) || $getVers === $e[1]);
});

$format = get_fmt();
if ($format === 'json') {
    header('Content-Type: application/json; charset=UTF-8');
    echo "{\"status\": \"success\", \"data\": [\n";
    $first = true;
    foreach ($entities as $name => [$prod, $vers, $url, $size, $mtime, $ctime, $mod, $cre]) {
        if (!$first) echo ",\n";
        echo "  {\"product\": \"$prod\", \"version\": \"$vers\", \"name\": \"$name\", \"url\": \"$url\", \"size\": $size, \"created\": \"$cre\", \"modified\": \"$mod\"}";
        $first = false;
    }
    echo "\n]}\n";
} else if ($format === 'text') {
    header('Content-Type: text/plain; charset=UTF-8');
    foreach ($entities as $name => [$prod, $vers, $url, $size, $mtime, $ctime, $mod, $cre]) {
        echo "$name\t" . number_format($size / 1024 / 1024, 1) . " MB\n";
    }
} else if ($format === 'html') {
    if (isset($getProd) && isset($getVers) && sizeof($entities) === 1) {
        header('Status: 303');
        header('Location: ' . $entities[array_key_first($entities)][2]);
        exit();
    }
    header('Content-Type: application/xhtml+xml; charset=UTF-8');
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    ?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="de-AT">
<head>
  <meta charset="UTF-8"/>
  <title>Downloads - Elwig - Elektronische Winzergenossenschaftsverwaltung</title>
  <link rel="icon" href="/favicon.ico" sizes="16x16 20x20 24x24 30x30 32x32 36x36 40x40 48x48 60x60 64x64 72x72 80x80 96x96 128x128 256x256"/>
  <link rel="stylesheet" href="/res/style.css"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
  <main>
    <section>
      <h3>Downloads</h3>
      <p style="text-align: center;"><a href="/">Startseite</a></p>
      <table>
        <thead><tr><th>Name</th><th>Größe</th><th>Änderungsdatum</th></tr></thead>
        <tbody>
<?php foreach (array_reverse($entities) as $name => [$prod, $vers, $url, $size, $mtime, $ctime, $mod, $cre]) {
    echo "          <tr><td><a href='/files/$name'>$name</a></td><td>" . number_format($size / 1024 / 1024, 1) . " MB</td><td>" . date('d.m.Y, H:i', $mtime) . "</td></tr>\n";
} ?>
        </tbody>
      </table>
      <p style="text-align: center;"><a href="?format=json">JSON-Format</a></p>
    </section>
  </main>
</body>
</html>
<?php }