<?php
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/upload.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../pages/dokumentenarchiv.php');
    exit;
}

$back = '../pages/dokumentenarchiv.php';

$allowed_kategorien = ['Fortbildungsnachweis', 'Zeugnis', 'Bescheinigung', 'Sonstiges'];
$kategorie   = trim($_POST['kategorie']   ?? '');
$beschreibung = trim($_POST['beschreibung'] ?? '');

if (!in_array($kategorie, $allowed_kategorien, true)) {
    redirect_error($back, 'Bitte eine Kategorie auswählen.');
}

$filesize = $_FILES['datei']['size'] ?? 0;
$up = handle_upload($_FILES['datei'] ?? [], [
    'allowed' => UPLOAD_TYPES_DOCS,
    'dir'     => dirname(__DIR__) . '/uploads/',
    'prefix'  => 'dokument',
]);
if (!$up['ok']) {
    redirect_error($back, $up['error']);
}

$safe_name     = $up['filename'];
$original_name = $up['original_name'];

$user_id  = current_user()['id'];
$now      = date('c');

db()->prepare(
    'INSERT INTO dokumente (user_id, kategorie, beschreibung, filename, original_name, filesize, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?)'
)->execute([$user_id, $kategorie, $beschreibung, $safe_name, $original_name, $filesize, $now]);

redirect_ok($back, 'ok');
