<?php

use mystic\forum\orm\User;

$userId = $_GET["user"] ?? call_user_func(function() {
    http_response_code(400);
    msg_error(__("Missing user id"));
    exit;
});
$user = new User();
$user->id = $userId;
if (!$db->fetch($user)) {
    http_response_code(404);
    msg_error(__("No user exists with this id"));
    exit;
}

$ifNoneMatch = $_SERVER["HTTP_IF_NONE_MATCH"] ?? null;
if ($ifNoneMatch !== null)
    $ifNoneMatch = trim($ifNoneMatch, '"');

if ($user->profilePicture === null) {
    $fallback = __ROOT__ . "/application/assets/user-fallback.jpg";
    $etag = md5("\0");
    header("Content-Type: image/jpeg");
    header("Content-Length: " . filesize($fallback));
    header("Cache-Control: no-cache");
    header("ETag: \"" . $etag . "\"");
    if ($ifNoneMatch === $etag)
        http_response_code(304);
    else
        readfile($fallback);
} else {
    $etag = md5($user->profilePicture);
    header("Content-Type: image/jpeg");
    header("Content-Length: " . strlen($user->profilePicture));
    header("Cache-Control: no-cache");
    header("ETag: \"" . $etag . "\"");
    if ($ifNoneMatch === $etag)
        http_response_code(304);
    else
        echo $user->profilePicture;
}