<?php
/* Upload einer zusätzlichen Datei direkt in den Bericht.
 * POST: berichtid, token, file (multipart)
 */
require_once __DIR__.'/_inc.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';

global $db, $user;

if (!$user->hasRight('bericht', 'write')) bericht_ajax_fail('Permission denied', 403);

$berichtid = (int) ($_POST['berichtid'] ?? 0);
$bericht = new Bericht($db);
if ($bericht->fetch($berichtid) <= 0) bericht_ajax_fail('Bericht nicht gefunden', 404);

if (empty($_FILES['file']['tmp_name'])) bericht_ajax_fail('Keine Datei hochgeladen');

$origname = dol_sanitizeFileName($_FILES['file']['name']);
$ext = strtolower(pathinfo($origname, PATHINFO_EXTENSION));
$allowed = array('pdf', 'png', 'jpg', 'jpeg');
if (!in_array($ext, $allowed)) bericht_ajax_fail('Dateityp nicht erlaubt');

$workdir = DOL_DATA_ROOT.'/bericht/work/'.$berichtid;
if (!is_dir($workdir)) dol_mkdir($workdir);

$target = $workdir.'/'.dol_print_date(dol_now(), '%Y%m%d_%H%M%S').'_'.$origname;
if (!move_uploaded_file($_FILES['file']['tmp_name'], $target)) bericht_ajax_fail('Upload fehlgeschlagen');

$relpath = str_replace(DOL_DATA_ROOT.'/', '', $target);

// Zur Bericht-Page-Liste hinzufügen
$res = $db->query("SELECT COALESCE(MAX(page_order),0) AS m FROM ".$db->prefix()."bericht_page WHERE fk_bericht = ".((int) $berichtid));
$next_order = ($res && ($o = $db->fetch_object($res))) ? ((int) $o->m) + 1 : 1;

if ($ext === 'pdf') {
    require_once __DIR__.'/add_attachment.php'; // bericht_pdf_pagecount
}

$created = array();
if ($ext === 'pdf') {
    $pagecount = function_exists('bericht_pdf_pagecount') ? bericht_pdf_pagecount($target) : 1;
    for ($p = 1; $p <= $pagecount; $p++) {
        $page = new BerichtPage($db);
        $page->fk_bericht  = $berichtid;
        $page->page_order  = $next_order++;
        $page->source_type = 'pdf';
        $page->source_path = $relpath;
        $page->source_page = $p;
        if ($page->create() > 0) $created[] = $page->id;
    }
} else {
    $page = new BerichtPage($db);
    $page->fk_bericht  = $berichtid;
    $page->page_order  = $next_order++;
    $page->source_type = 'upload';
    $page->source_path = $relpath;
    if ($page->create() > 0) $created[] = $page->id;
}

bericht_ajax_ok(array('created' => $created, 'relpath' => $relpath));
