<?php
/* Erstellt eine neue Multi-Image-Seite mit gewähltem Layout
 * und setzt mehrere Bilder gleich rein.
 * POST: berichtid, layout, relpaths[] (JSON-Array), token
 */
require_once __DIR__.'/_inc.php';

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

$berichtid = (int) ($_POST['berichtid'] ?? 0);
$layout    = (string) ($_POST['layout'] ?? 'grid_4');
$relpaths_raw = (string) ($_POST['relpaths'] ?? '[]');
$relpaths = json_decode($relpaths_raw, true);
if (!is_array($relpaths) || empty($relpaths)) bericht_ajax_fail('Keine Bilder ausgewählt');

$valid_layouts = array('grid_2', 'grid_2v', 'grid_4', 'grid_6', 'before_after');
if (!in_array($layout, $valid_layouts, true)) $layout = 'grid_4';

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

// Höchste page_order ermitteln
$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;

// Neue Page anlegen — dummy source_path, da Bilder über page_image kommen
$page = new BerichtPage($db);
$page->fk_bericht  = $berichtid;
$page->page_order  = $next_order;
$page->source_type = 'grid';
$page->source_path = ''; // bei grid leer
$page->layout      = $layout;
$page->image_scale = 1.0;
$page->image_align = 'fit';
if ($page->create() <= 0) bericht_ajax_fail('Page-Insert fehlgeschlagen');

// Bilder in Slots verteilen
$slot_count = BerichtPage::slotCountForLayout($layout);
$slot = 0;
foreach ($relpaths as $rel) {
    if ($slot >= $slot_count) break;
    $full = bericht_resolve_data_path($rel);
    if (!$full || !file_exists($full)) continue;
    $page->setSlotImage($slot, $rel, 0);
    $slot++;
}

bericht_ajax_ok(array('pageid' => $page->id, 'created_slots' => $slot));
