<?php
declare(strict_types=1);

require __DIR__ . '/../auth.php';
requireLogin();

header('Content-Type: application/json; charset=utf-8');

$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['newOrder']) || !is_array($input['newOrder'])) {
    http_response_code(400);
    echo json_encode(['message' => 'Ungültige Daten']);
    exit;
}

$newOrder = array_map('intval', $input['newOrder']);

try {
    $pdo->beginTransaction();

    foreach ($newOrder as $pos => $itemId) {
        if ($itemId <= 0) continue;
        $stmt = $pdo->prepare('UPDATE items SET sort_order = :sort WHERE id = :id');
        $stmt->execute([
            ':sort' => (int)$pos,
            ':id'   => $itemId,
        ]);
    }

    $pdo->commit();
    echo json_encode(['message' => 'Reihenfolge gespeichert']);
} catch (Throwable $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['message' => 'Fehler beim Speichern']);
}
