<?php
include 'renderer.php';

class Download extends Renderer {

    public function render(): void {
        if ($_SESSION['userid'] === 0 && in_array($this->getScriptName() , $this->internalMenuItems, false)) {
            $this->templateName = 'login_error';
            parent::render();
            return;
        }
        $params = $this->getUriParams();
        $query = sprintf('SELECT `original_filename`, `salt` FROM `document` WHERE `local_filename` = "%s"', $params['file']);
        $result = mysqli_query($this->dbConnection, $query);
        if (mysqli_num_rows($result) < 1) {
            die ('Datei nicht gefunden');
        }
        $row = mysqli_fetch_assoc($result);
        $encryptedFile = file_get_contents('/var/shared/fvajs/' . $params['file']);
        $decryptedFile = $this->decode($encryptedFile, $row['salt']);
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header("Cache-Control: no-cache, must-revalidate");
        header("Expires: 0");
        header('Content-Disposition: attachment; filename="' . $row['original_filename'] . '"');
        header('Content-Length: ' . strlen($decryptedFile));
        header('Pragma: public');
        flush();
        echo $decryptedFile;
    }
}
