<?php
declare(strict_types=1);

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

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

$payload = json_decode(file_get_contents('php://input'), true);

if (!is_array($payload)) {
    http_response_code(400);
    echo json_encode(['message' => 'Ungültige Daten']);
    exit;
}

// payload = [{file: "lidl.json"}, ...]
try {
    $pdo->beginTransaction();

    foreach ($payload as $position => $store) {
        if (!isset($store['file'])) {
            continue;
        }
        $file = (string)$store['file'];
        $stmt = $pdo->prepare('UPDATE stores SET sort_order = :sort WHERE file = :file');
        $stmt->execute([
            ':sort' => (int)$position,
            ':file' => $file,
        ]);
    }

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