<?php
declare(strict_types=1);

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

$name = trim($_POST['name'] ?? '');

if ($name === '') {
    header('Location: ../start.php');
    exit;
}

// Slug wie bisher: name -> slug.json
$slugBase = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '_', $name), '_'));
if ($slugBase === '') {
    $slugBase = 'store';
}
$slug = $slugBase . '.json';

// sort_order bestimmen
$stmt = $pdo->query('SELECT COALESCE(MAX(sort_order) + 1, 0) FROM stores');
$nextSort = (int)$stmt->fetchColumn();

// Insert
$stmt = $pdo->prepare('INSERT INTO stores (name, file, sort_order) VALUES (:name, :file, :sort)');
try {
    $stmt->execute([
        ':name' => $name,
        ':file' => $slug,
        ':sort' => $nextSort,
    ]);
} catch (Throwable $e) {
    // bei Unique-Konflikt o.ä. einfach zurück
}

header('Location: ../start.php');
exit;
