<?php
/* Speichert Fabric.js-JSON + Notiz + optional Composite-PNG für eine Seite.
 *
 * POST:
 *   pageid     — Seiten-ID
 *   fabric_json — Fabric-Serialisierung (für späteren Edit)
 *   note       — Notiz für den PDF-Footer
 *   rotation   — Rotation 0/90/180/270
 *   composite  — (optional) multipart/form-data file: PNG der kompletten Seite
 *   token
 */
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);

$pageid = (int) ($_POST['pageid'] ?? 0);
if (!$pageid) bericht_ajax_fail('pageid fehlt');

$fabric   = (string) ($_POST['fabric_json'] ?? '');
$note     = (string) ($_POST['note'] ?? '');
$rotation = (int)    ($_POST['rotation'] ?? 0);
$rotation = (($rotation % 360) + 360) % 360;

// Page laden und fk_bericht ermitteln
$res = $db->query("SELECT rowid, fk_bericht FROM ".$db->prefix()."bericht_page WHERE rowid = ".((int) $pageid));
if (!$res || !($row = $db->fetch_object($res))) bericht_ajax_fail('Page nicht gefunden', 404);
$fk_bericht = (int) $row->fk_bericht;

// Composite-PNG speichern wenn hochgeladen
$composite_relpath = null;
if (!empty($_FILES['composite']['tmp_name']) && is_uploaded_file($_FILES['composite']['tmp_name'])) {
    $workdir = DOL_DATA_ROOT.'/bericht/work/'.$fk_bericht;
    if (!is_dir($workdir)) dol_mkdir($workdir);
    $filename = 'composite_'.$pageid.'.png';
    $target = $workdir.'/'.$filename;
    if (move_uploaded_file($_FILES['composite']['tmp_name'], $target)) {
        $composite_relpath = str_replace(DOL_DATA_ROOT.'/', '', $target);
    }
}

// Prüfen ob composite_path-Spalte existiert
$has_composite = false;
$ccheck = $db->query("SHOW COLUMNS FROM ".$db->prefix()."bericht_page LIKE 'composite_path'");
if ($ccheck && $db->num_rows($ccheck) > 0) $has_composite = true;

$sets = array(
    "fabric_json = ".($fabric !== '' ? "'".$db->escape($fabric)."'" : "NULL"),
    "note = ".($note !== '' ? "'".$db->escape($note)."'" : "NULL"),
    "rotation = ".((int) $rotation),
);
if ($composite_relpath !== null && $has_composite) {
    $sets[] = "composite_path = '".$db->escape($composite_relpath)."'";
}

$sql = "UPDATE ".$db->prefix()."bericht_page SET ".implode(', ', $sets)." WHERE rowid = ".((int) $pageid);
if (!$db->query($sql)) bericht_ajax_fail('DB-Fehler: '.$db->lasterror());

bericht_ajax_ok(array('composite_saved' => $composite_relpath !== null));
