<?php
include 'renderer.php';

class Documents extends Renderer {
    protected array $formFields = [
        ['label' => 'Dokumenttitel', 'type' => 'text', 'size' => 50, 'name' => 'documenttitle', 'combine_with_next_line' => false, 'filter' => FILTER_SANITIZE_STRING, 'optional' => false],
        ['label' => 'Dokumentdatei', 'type' => 'file', 'size' => 50000, 'name' => 'document', 'combine_with_next_line' => false, 'optional' => true],
        ['label' => 'Oder Datei erstellen aus', 'type' => 'textarea', 'cols' => 80, 'rows' => '15', 'name' => 'newtext', 'combine_with_next_line' => false, 'optional' => true],
    ];
    protected string $formSendButtonLabel = 'Dokument hinzufügen';
    protected string $encType = 'multipart/form-data';
    
    public function __construct() {
        parent::__construct();
    }
    
    protected function formAction(): void {
        $this->formCheckFields();
        if (count($this->errors) === 0) {
            $newFileName = $this->generateRandomString(64);
            $salt = $this->generateRandomString();
            $this->saveFile($newFileName, $salt);
            $query = sprintf('INSERT INTO ffajs.document
                    (title, original_filename, local_filename, salt)
                    VALUES("%s", "%s", "%s", "%s")', trim(filter_input(INPUT_POST, 'documenttitle', $this->formFields[0]['filter'])),
                    $this->getOriginalFileName(),
                    $newFileName, $salt);
            mysqli_query($this->dbConnection, $query);
        }
    }

    protected function formCheckFields(): bool {
        parent::formCheckFields();
        $result = mysqli_query($this->dbConnection, 'SELECT `id` FROM `document` WHERE `title` = "' . trim(filter_input(INPUT_POST, 'documenttitle', $this->formFields[0]['filter'])) . '"');
        if (mysqli_num_rows($result) > 0) {
            $this->errors['documenttitle'] = 'Der Titel existiert bereits';
        }
        return count($this->errors) === 0;
    }

    protected function saveFile(string $newFileName, string $salt): void {
        if (trim(filter_input(INPUT_POST, 'newtext', FILTER_SANITIZE_STRING)) !== '') {
            $content = filter_input(INPUT_POST, 'newtext', FILTER_SANITIZE_STRING);
        } elseif ($_FILES['document']['tmp_name']) {
            $content = file_get_contents($_FILES['document']['tmp_name']);
        } else {
            $this->errors['newtext'] = 'Es muss eine Datei hochgeladen oder hier ein Text eingegeben werden.';
            return;
        }
        $this->saveFileLocal($newFileName, $content, $salt);
    }
    
    protected function generateContent(): void {
        $result = mysqli_query($this->dbConnection, 'SELECT * FROM `document` ORDER BY `title`');
        $tableBody = '';
        while ($row = mysqli_fetch_assoc($result)) {
            $tableBody .= '<tr>';
            $tableBody .= '<td>' . $row['title'] . '</td>';
            $tableBody .= '<td>' . $row['original_filename'] . '</td>';
            $tableBody .= '<td><a href="download?file=' . $row['local_filename'] . '">Download</a></td>';
            $tableBody .= '<td><button type="button" name="delete" value="' . $row['local_filename'] . '">Löschen</button></td>';
            $tableBody .= '</tr>';
        }
        $this->content['documents'] = $tableBody;
    }
    
    protected function getOriginalFileName(): string {
        return trim(filter_input(INPUT_POST, 'newtext', FILTER_SANITIZE_STRING)) !== '' 
                ? trim(filter_input(INPUT_POST, 'documenttitle', $this->formFields[0]['filter'])) . '.txt'
                : $_FILES['document']['name'];
    }
}
